Q: Get single value count across the whole dataset I'm new at pandas and surveying the internet for my learning I've used count(), value_counts() to count values column wise but now I'm stuck in a problem. I've a car crash reporting dataset that has it's empty value replaced with "Not Reported" so I wanted to count the number of cells that have this value across the whole data set and show it column wise.Is there any way for me to achieve such out come?
The dataset has values like this
| Location     | Severity     | Time         | Outcome      | Substance Used | Traffic Signal |
| --------     | --------     | ----------   | -----------  | -------------- | -------------- |
| New York     | Level 1      | Not Reported | Casualty     | Alcohol        | Red            |
| Texas        | Not Reported |  7:00:00     | Minor Injury | Not Reported   | Green          |
| Not Reported | Level 4      | Not Reported | Not Reported | Smoking        | Yellow         |

The output required is this.
| Column         | Value        | Count |
| -------------- | ------------ | ----- |
| Location       | Not Reported | 1     |
| Severity       | Not Reported | 1     |
| Time           | Not Reported | 2     |
| Outcome        | Not Reported | 1     |
| Substance Used | Not Reported | 1     |
| Traffic Signal | Not Reported | 0     |

A: You can use:
(df.where(df.eq('Not Reported')).stack(dropna=False)
   .groupby(level=1).agg(Value='first', Count='count')
   .reset_index()
)

Output:
            index         Value  Count
0        Location  Not Reported      1
1         Outcome  Not Reported      1
2        Severity  Not Reported      1
3  Substance Used  Not Reported      1
4            Time  Not Reported      2
5  Traffic Signal          None      0

A: You can count Not Reported by compare all values by Not Reported with sum, no groupby necessary:
s = df.eq('Not Reported').sum()
print (s)
Location          1
Severity          1
Time              2
Outcome           1
Substance Used    1
Traffic Signal    0
dtype: int64

Your expected ouput is possible get in DataFrame constructor:
df1 = pd.DataFrame({'Column': s.index, 'Value':'Not Reported', 'Count': s.to_numpy()})
print (df1)
           Column         Value  Count
0        Location  Not Reported      1
1        Severity  Not Reported      1
2            Time  Not Reported      2
3         Outcome  Not Reported      1
4  Substance Used  Not Reported      1
5  Traffic Signal  Not Reported      0


Q: Resolving component from class name in Angular 4 Is it possible to resolve a component from string?
Previously in Angular 2, we are able to do this see here. However, in Angular 4, the same method will throw error.
private resolver: ComponentFactoryResolver

var factories = Array.from(this.resolver['_factories'].keys());
var factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);

A: It looks like you might be relying on an implementation detail. However, to get around the error, you can explicitly cast the type to any in order to access the indexer.  Assuming there is a _factories property, this should work:
var factories = Array.from((<any>this.resolver)['_factories'].keys());


Q: Similarity between two probability distribution I am not sure how to put the question. I am not even sure if this question makes sense at all.
I know that the similarity of two discrete (or continuous) distributions can be quantified by Kullback–Leibler distance. However, I wonder if it makes sense to quantify the Kullback–Leibler distance between two random variables which one is discrete and the other one is continuous?
Is there any probabilistic measure for quantifying the similarity of continuos distribution with a discrete one.

A: There exist a lot of statistical distances for two distributions.
http://en.wikipedia.org/wiki/Statistical_distance
What motivated you to use KL convergence? Although it is often intuited as a metric or distance, the KL divergence is not a true metric — for example, it is not symmetric: the KL divergence from P to Q is generally not the same as that from Q to P.
But if you want to extend the definition of the KL divergence to the case when $X$ is continuous and $Y$ is discrete I think I know how to do it.
Any discrete PMF (probability measure function) can be represented as a continuous PDF using a Dirac delta function.
http://en.wikipedia.org/wiki/Dirac_delta_function

A: In more details, the Dirac delta function $\delta(x)$ is defined as follows
$$
\delta(x) =
\begin{cases}
\ +\infty, & x = 0 \\
\ 0, & x \neq 0
\end{cases}
$$
and also
$$
\int_{-\infty}^\infty \delta(x) = 1.
$$
Now if your discrete PMD is defined as $P(k) = P(Y = k) = p_k$ for all integer $k$ then its PDF has the form
$$
p_Y(y) = \sum_{k=-\infty}^{\infty} p_k \delta(y-k).
$$
Indeed, for every infinitesimal $\epsilon > 0$ we have
$$
P(k - \epsilon < Y < k + \epsilon) = \int_{k - \epsilon}^{k + \epsilon} p_k \delta(y-k) dy = p_k.
$$
Further,
$$
D_{KL}(X||Y) = \int_{-\infty}^\infty \ln(\frac{p_X(x)}{p_Y(x)})p_X(x) dx = \ldots
$$
Probably, this approach will give some result...

A: You can't do KL between discrete and continuous usefully.
If you did KL between discrete and continuous, you'd have to do D(discrete||continuous) (else, it would always be infinite due to supports). And even then, theres no mass at a single point in a continuous distribution, so it doesn't really have compatibility there either (if you wanted the full version of KL divergence, you need to have $D(p||q)$ to be such that $p << \mu, q << \mu$ and then define this in terms of their Radon-Nikodym derivatives).
See this thread as well.


Q: Finding the prime numbers used in RSA I got this question in a local hacking event, but I couldn't solve it.
Problem Statement ----
Continuing their snooping habit, NSA kept bugging Alice's communication. Resorting to the age old RSA encryption, Alice used 128-bit RSA encryption to exchange messages. Alice shares her public key as

$0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807$

and her public key exponent $\phi(n)$ as $0x11$ with Warden.
However, NSA, with its enormous resource, cracked this 128 bit encryption super easily. Seeing your work on the previous ciphers, NSA decided to offer you a job in their Cryptography group. As a final test, NSA shared this public key which they intercepted from Alice and Warden's conversation. They also gave away the private key that they computed from their message exchange.

$Public$ $Key -
  (0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807,
  0x11)$
$Private$ $Key -
  (0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807,$
                        $0xc3c3c3817b3335577e69b9d0e48e2bc1fdf71f1f4f73a38a7d628d39739bbaf1)$

What are the values of $p$ and $q$? (the prime numbers used in key generation)


Q: Volta with yarn run build system cannot find the path specified This is the first time I'm using Volta, so bear with me.
I have installed globally typescript, node and yarn
yarn -v >> 1.22.10
node -v >> v14.15.4
npm -v >> 6.14.10

These commands work inside and outside my project folder, with the same results.
However if I use yarn build from inside vscode the output is an error stating:
System cannot find the path specified

If I do the same from outside vscode I get the same result:

If I go to the node_modules/.bin folder inside vscode, the command still doesn't work (this time I just only run tsc). The error is the following:
The term tsc is not a cmdlet recognized command, function, script file or executable program. Verify if the name is written correctly or, if there is an access route, verify the route is correct and try again.

But if the command is executed from outside vscode in a cmd window, it works as expected, because tsc is really there:

Additionally, if I run npm run build inside vscode, the command works as expected. This is my package.json:
{
  "name": "socket-server",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "license": "MIT",
  "scripts": {
    "build": "tsc",
    "dev": "yarn build --watch --preserveWatchOutput",
    "lint": "eslint src --ext js,ts",
    "test": "jest"
  },
  "devDependencies": {
    "eslint": "^7.19.0",
    "jest": "^26.6.3",
    "typescript": "^4.1.3"
  },
  "volta": {
    "node": "14.15.4",
    "yarn": "1.22.10"
  }
}

I do suspect of volta because volta is managing yarn version, but no npm; but I don't really know what's the issue.
I'm using Windows and my PATH has the following entries:

What am I doing wrong?
Edit: Yes, Shell command shortcut exists:

A: the problem is about vsCode, you should run code . in cmd because if you Open the Command Palette (Ctrl + Shift + P) and type
Shell Command: Install 'code' command in PATH

you won't see noting, after running code . in cmd when you should see like this photo, every things will be fine

A: I’m not sure for Windows, but usually the scripts in node_modules/.bin are symbolic links to scripts. For instance, node_modules/.bin/tsc might point to node_modules/typescript/bin/tsc.
It works outside of the directory because then it uses the global version of tsc.
Seeing your error, I’m suspecting that the symlinks are broken. Maybe just try to remove node_modules directory and redo an npm install.
PS: I’m not familiar with Volta, but it looks more like an NPM problem.


Q: giving a default value for an angular number formcontrol I am working with angular. I am astonished that we cannot give an empty default value for an angular number formcontrol. At the beginning, I set it to 0, but it isn't my requirement, since my input display 0 before entering anything. It must be a solution

A: You can create a FormControl in a reactive form using an empty value, empty string, or even undefined:
Component:
foo = new FormControl();

Template:
<input type="number" [formControl]="foo" />

Here is an example in action that demonstrates the number input being initialized without any value.
Hopefully that helps!


Q: why does tar command in bash script with file list within quotes not work In the code below:
#!/bin/bash

echo AAAAAA > a.txt
echo BBBBBB > b.txt
echo CCCCCC > c.txt

files="a.txt b.txt c.txt"

tar -cvf archive1.tar $files  # this line works

tar -cvf archive2.tar "$files"  # this line doesn't work - why???

the first tar command works fine, but the 2nd tar line, with "$files" does not.  Why is this?


Q: PHP and OpenSSL stopped working after service change Recently I asked my hosting company to setup a new package and since then my existing package is now giving me errors with anything to do with using openSSL.
For instance, I have a function to generate a GUID:
function generateGUIDV4($data)
{
    assert(strlen($data) == 16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

$newID = generateGUIDV4(openssl_random_pseudo_bytes(16));

This now throws an error: Fatal error: Call to undefined function openssl_random_pseudo_bytes(). From what I've researched this has to do with Fatal error: Call to undefined function openssl_random_pseudo_bytes().
Now I'm also getting an error now when I call any web services from my application which again point to the openSSL.
Error:
Objectfaultcode: "WSDL"faultstring: "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://*******'"__proto__: Object

.I've hidden the web service as it's not public. From what I've researched this points to OpenSSL again: SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>.
PHP Ini is showing openSSL IS installed
OpenSSL support enabled
OpenSSL Version OpenSSL 0.9.8b 04 May 2006

Anyone have any ideas or point me in the right direction? I've got the hosting company looking into this.

A: I've fixed this and it had nothing to do with the hosting company.
I published a new version of the site, but in the publish profile I told it to delete all files which deleted the .htaccess file which contained the version of PHP in.
Unfortunately, I needed version 5.4 or above to run my code but since the file was removed it dropped down to 5.2 of PHP.
So I've uploaded a new .htaccess file with the correct version in and everything is working.
Hopefully this may help someone if they're as daft as I am.


Q: Loop in property in constructor If you have a look at my code below. Is there ANY way to write some kind of loop instead of having repeat Row and ColumnDefinitions?
var grid = new Grid
            {
                RowSpacing = 12,
                ColumnSpacing = 12,
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
            },
                ColumnDefinitions =
            {
                new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
            }
            };

A: You can use loops to create an array of rows and an array of columns beforehand and assign these to the RowDefinitions and ColumnDefinitions properties.
I should have thought you'd need to call RowDefinitions.Add() and ColumnDefinitions.Add() in a loop to do so, though.

A: No, this is not possible because the only way this would work is if you could assign a completely new value to the RowDefinitions property, which you can't:
public RowDefinitionCollection RowDefinitions { get; }
                                                ^^^^

The syntax as shown in your question is just a handy way of calling .Add on the object in that property, so there is no way for you to inline in that syntax do this. Your code is just "short" for this:
var temp = new Grid();
temp.RowSpacing = 12;
temp.ColumnSpacing = 12;
temp.VerticalOptions = LayoutOptions.FillAndExpand;
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns

Specifically, your code is not doing this:
temp.RowDefinitions = ...
                    ^

You would probably want code like this:
var grid = new Grid()
{
    RowSpacing = 12,
    ColumnSpacing = 12,
    VerticalOptions = LayoutOptions.FillAndExpand,
    RowDefinitions = Enumerable.Range(0, 100).Select(_ =>
        new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }),
    ColumnDefinitions = Enumerable.Range(.....

But you cannot do this as this would require that RowDefinitions and ColumnDefinitions was writable.
The closest thing is like this:
var temp = new Grid
{
    RowSpacing = 12,
    ColumnSpacing = 12,
    VerticalOptions = LayoutOptions.FillAndExpand,
};

for (int index = 0; index < rowCount; index++)
    temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns
var grid = temp;

A: RowDefinitions is RowDefinitionCollection. RowDefinitionCollection is internal which you cannot create outside Grid.


Q: Difference between Tomcat's extraResourcePaths and aliases to access an external directory Simple question: In Tomcat7, what's the difference between using extraResourcePaths and aliases to access an directory outside the application?
I can use either of these two server.xml snippets and they both seem to work.  Both seem to load this URL successfully: http://localhost/app/images/box.jpg.  Is there an advantage to using one over the other?
<Context docBase="Eclipse_Project" path="/app"
        reloadable="true" source="org.eclipse.jst.j2ee.server:Eclipse_Project"
        aliases="/images=D:\path\to\images"/>

or
<Context docBase="Eclipse_Project" path="/app"
        reloadable="true" source="org.eclipse.jst.j2ee.server:Eclipse_Project">
        <Resources className="org.apache.naming.resources.VirtualDirContext"
                extraResourcePaths="/images=D:\path\to\images"/>
</Context>

A: This is the result of having multiple different ways of pulling in resources that aren't part of a WAR or exploded directory. Frankly it is a mess long overdue a clean-up. The 'overlay' (or whatever it ends up being called) feature proposed for Servlet 3.1  (i.e. Tomcat 8) has prompted a major clean-up. All the current implementations will be unified into a single implementation. It isn't pretty though, and it is going to take a while to complete.
Aliases are treated as external to the web application resources. The DirContext checks aliases before it checks its internal resources. Hence when you request the real path you get the original.
If you use extraResourcePaths they are treated as part of the web application resources. It looks like Eclipse has triggered a copy of application resources to the work directory. This is usually done to avoid file locking. Since the extraResourcePaths are treated as part of the webapp, they get copied too and getRealPath() reports the copied location since that is where Tomcat is serving the resources from.

A: After investigating further, I found this difference.
The results of this Java code is different.  I still don't know why.
String path = getServletContext().getRealPath("/images");

Using extraResourcePaths, path is below, which is a folder under where Eclipse explodes my web app and not a valid directory.
C:\Projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\Eclipse_Project\images

Using aliases, path is below and is what I actually need.
D:\path\to\images

Now if someone could actually explain this.  :-)


Q: Is it important to study plane algebraic curves before read Fulton's book I'm studying Fulton's algebraic curves book and I would like to know how important study plane algebraic geometry before read Fulton's book.
Example of books on this subject:
Algebraic Curves - Robert J. Walker
Plane Algebraic Curves -  Gerd Fischer
I know it's perfectly possible to study Fulton's book without this background, I'm wondering if study algebraic plane curves could help me to have more intuition in some problems algebraic geometry, to sum up, what's the advantages to study the books above before study more advanced subjects.
thanks in advance


Q: Invalid results from SQL Server "NOT IN" clause I have run a query on our SQL Server 2012 which returned no results. I discovered that this was incorrect and I SHOULD have gotten 16 records. I changed the query and get the answer expected but I am at a loss to understand why my original query did not work as expected.
So my ORIGINAL query which returned no results was:
SELECT
    WPB.[ID number]
FROM
    [Fact].[REPORT].[WPB_LIST_OF_IDS] WPB
WHERE
    [ID number] NOT IN (SELECT DISTINCT IdNumber
                        FROM MasterData.Dimension.Customer DC)

The reworked query is this:
SELECT
    WPB.[ID number]
FROM
    [Fact].[REPORT].[WPB_LIST_OF_IDS] WPB
LEFT JOIN
    MasterData.Dimension.Customer DC ON WPB.[ID number] = DC.IdNumber
WHERE
    DC.IdNumber IS NULL

Can anyone tell me WHY the first query (which incidentally runs in fractions of a second vs the 2nd which takes a minute) does not work? I don't want to repeat this mistake in the future!

A: Don't use not in with a subquery.  It doesn't work the way you expect with NULL values.  If any value returned by the subquery is NULL, then no rows are returned at all.
Instead, use not exists.  This has the semantics that you expect:
select wpb.[ID number]
from [Fact].[REPORT].[WPB_LIST_OF_IDS] wpb
where not exists (select 1
                  from MasterData.Dimension.Customer dc
                  where wpb.[ID number] = dc.IdNumber
                 );

Of course, the left join method also works.


Q: Return two different sections in my UITableView I'm trying to return two seperate .counts in my UITableView. I kind of know the logic behind it but not using the syntax right. How can I do this? What I want it to do is fill my tableview up with the both .counts. I would also like to put in a label on top of the first section and second section. Anything would help!
Here is what I have so far but I'm only getting the first section of cells. Why isnt it displaying both .counts?
func tableView(tableView: UITableView, numberOfSectionsInTableView: Int) -> Int{
        return 2;
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if (section == 0){
           return featSubNames.count
        }
        else{
            return subCatNames.count
        }

    }
    func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
        if (section == 0){
            ????
        }
        if (section == 1){
            ????
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell
        switch (indexPath.section) {

        case 0:
            cell.textLabel?.text = featSubName[indexPath.row]
            cell.textLabel?.textColor = UIColor.whiteColor()
        case 1:
            cell.textLabel?.text = subCatNames[indexPath.row]
            cell.textLabel?.textColor = UIColor.whiteColor()
        default:
            cell.textLabel?.text = "Other"

        }

        return cell
    }

A: Your code seems to be right. To get the UIViews on the header of each section, you can return any object that inherits from a UIView(this doesn't mean that would be nice to). So, you can return a small container with a UIImageView and a UILabel, if you want this for example.
Your code for the viewHeader would be something like this:
func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
    // instantiate the view to be returned and placed correctly
    let commonLabel = UILabel(frame: CGRectMake(0, 0, tableWidth, 30))
    commonLabel.textColor = .blackColor()
    commonLabel.textAlignment = .Center
    // ... other settings in the properties

    if section == 0 {
        commonLabel.text = "section1"
        // other settings for the first section
    }
    if section == 1 {
        commonLabel.text = "section2"
        // other settings ...
    }
    return commonLabel
}

Notes:
Be sure to set the container view's frame,for sectionHeaders the top view in the hierarchy don't accept auto layout.
Implementing the viewForHeaderInSection method is more accessible to custom UI's, you can use the TitleForHeaderInSection if you wish, but it's limited for more complex stuffs.
EDIT:
If you're using storyboards, you still can use this code, although it's not so elegant in terms of apps that use IB for the UI. For this, you might take a look at this link: How to Implement Custom Table View Section Headers and Footers with Storyboard
. This implements only the view using storyboards, but the delegate part must to be wrote.


Q: Spring MVC - lookup validators automatically Suppose I have a sample entity class like this:
public class Address {
    ...
}

and a corresponding validator:
@Component
public AddressValidator implements Validator {

    @Override
    public boolean supports(Class<?> entityClass) {
        return entityClass.equals(Address.class);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ...
    }
}

When I use a controller like the following, everything works:
@RestController
@RequestMapping("/addresses")
public class AddressController {

    @Autowired
    private AddressValidator validator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    @RequestMapping(method=POST)
    public Long addNewAddress(@Valid @RequestBody Address address) {
        ...
    }
}

However, if I omit the validator registering part (i.e. the following), validation is not performed.
@Autowired
private AddressValidator validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}

Having to register validators manually seems pointless. Can I instruct Spring to look up validators automatically (similar to how controllers are looked up)?
It's a Spring Boot based application.

A: You can use my example from gist or below. The idea is to have a main CompositeValidator that will be a holder of all your Validator or SmartValidator instances.
It supports hints and can be also integrate with Hibernate Annotation Validator (LocalValidatorFactoryBean). And also it's possible to have more that one validator per specific Model.

CompositeValidator.java
@Component
public class CompositeValidator implements SmartValidator {
    @Autowired
    private List<Validator> validators = Collections.emptyList();

    @PostConstruct
    public void init() {
        Collections.sort(validators, AnnotationAwareOrderComparator.INSTANCE);
    }

    @Override
    public boolean supports(Class<?> clazz) {
         for (Validator validator : validators) {
            if (validator.supports(clazz)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void validate(Object target, Errors errors) {
        validate(target, errors, javax.validation.groups.Default.class);
    }

    @Override
    public void validate(Object target, Errors errors, Object... validationHints) {
        Class<?> clazz = target.getClass();

        for (Validator validator : validators) {
            if (validator.supports(clazz)) {
                if (validator instanceof SmartValidator) {
                    ((SmartValidator) validator).validate(target, errors, validationHints);
                } else {
                    validator.validate(target, errors);
                }
            }
        }
    }
}

SomeController.java
@Controller
@RequestMapping("/my/resources")
public class SomeController {

    @RequestMapping(method = RequestMethod.POST)
    public Object save(
            @Validated(javax.validation.groups.Default.class) // this interface descriptor (class) is used by default
            @RequestBody MyResource myResource
    ) { return null; }
}

Java Config
 @Configuration
    public class WebConfig {
        /** used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy */
        // @Bean
        // public Validator jsr303Validator() {
        //   LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        //   // validator.setValidationMessageSource(...);
        //   return validator;
        // }

        @Bean
        public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
            return new WebMvcConfigurerAdapter() {
                @Autowired
                private CompositeValidator validator;

                @Override
                public Validator getValidator() {
                    return validator;
                }
            }
        }

Or XML Config
<!-- used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy -->
<!--<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">-->
<!--  <property name="validationMessageSource" ref="messageSource"/>-->
<!--</bean>-->

<mvc:annotation-driven validator="compositeValidator">
  //...
</mvc:annotation-driven>

A: You can configure global Validator.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-mvc
If you are using Java based spring configuration with WebMvcConfigurationSupport, you can override getValidator()
/**
 * Override this method to provide a custom {@link Validator}.
 */
protected Validator getValidator() {
    return null;
}

You may call setValidator(Validator) on the global WebBindingInitializer. This allows you to configure a Validator instance across all @Controller classes. This can be achieved easily by using the Spring MVC namespace:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven validator="globalValidator"/>

</beans>

A: I have not found a build in Spring solution for this, but here is what I do.
I declare my validator beans in the spring java configuration like so:
@Bean
public Validator studentValidator(){
    return new StudentValidator();
}

@Bean
public Validator carValidator(){
    return new CarValidator();
}

Then I have all controllers extends a base controller like so:
public abstract class BaseController <T> {
     public BaseController(List<Validator> validators) {
        super();
        this.validators = validators;
      }
  //Register all validators
  @InitBinder
  protected void initBinder(WebDataBinder binder) {
    validators.stream().forEach(v->binder.addValidators(v));
  }

}

The concrete class of this controller gets the List injected via dependency injection, like so:
@Controller
public class StudentController extends BaseController<Student>{

    @Inject
      public StudentController(List<Validator> validators) {
        super(validators);
      }

}

The base Controller uses the @InitBinder call-back method to register all Validators.
I am surprised that spring doesn't automatically register all objects in class path that implement the Validator interface.


Q: Runtime error while working with 2D arrays in a loop C I wrote this piece of code to find the GCD of any two numbers, and as I am working with multiple test cases,  I used a 2D array with each testcase as a row and the first two elements in each row to store the numbers. FOr example, a[0][0] stores the first number of the first test case.
It works well up to user input, but the part which calculates the gcd, I'm getting a runtime error. I checked to see if I was trying to access an undefined location in the array, but with no luck.
const int testCase;
scanf("%d", &testCase);
int a[testCase][3], i, j, k;

for(k = 0; k < testCase; k++){
    scanf("%d %d", &a[k][0], &a[k][1]);
}

// problem occurs after this

for(j = 0; j < testCase; j++){

    for(i = 0; i <= a[j][0] && i <= a[j][1]; i++){
        if(a[j][0] % i == 0 && a[j][1] % i == 0){
            a[j][2] = i;
        }
    }
    printf("%d\n", a[j][2]);


Q: PHP inheritance - methods and properties I'm obviously not understanding inheritance correctly. I'll let my code do the talking:
abstract class Calc {
private $x;
private $y;
public function AddNumbers() {
    echo $this->x. " + " .$this->y;
}
}

class myCalc extends Calc {
public function __construct ($x,$y) {
    $this->x = $x;
    $this->y = $y;
   }
}

$calc1 = new myCalc(3,4);
$calc1->AddNumbers();
echo 'done';
exit;

OK, so what's going on here: I'd like to have an abstract class, that would define two properties (x and y) and an abstract method, (nevermind the concatenation of numbers, implementation of the method is out of the scope of my question) which would access there properties.
Then, a concrete class extends that abstract one. As you can see, I can successfully access the properties and set them, but when I call add numbers, it appears as if the properties are not set.
What is going on, why is this not working and how can I fix it?
I could just define a method for adding numbers in concrete class, but I want to have a method in abstract class with a definition that can be reused.
Thanks!

A: The two properties in the abstract class are private, which means they are NOT present and known in any class that extends this one.
So MyCalc does not write to these properties, and you cannot read them in the AddNumbers function. The MyCalc constructor actually creates new, public properties instead.
Make the properties "protected", and it will work.

A: The private keyword defines that only the methods in Calc can modify those variables. If you want methods in Calc and methods in any of its subclasses to access those variables, use the protected keyword instead.
You can access $this->x because PHP will let you create a member variable on the object without declaring it. When you do this the resulting member variable is implicitly declared public but it doesn't relate to the private variable defined in Calc, which is not in scope in myCalc.


Q: How to show jquery confirmation dialogue with multiple forms and submit buttons mvc I have a mvc project and on one page there is a table of data with a submit button that is inside its own form tag.  I want to have a pop up modal dialogue when the user clicks the delete button to ask for confirmation of the delete.  How would you do this with jquery?

A: you can use the ajax.actionlink
@Ajax.ActionLink("Delete", "DeleteUser", new { id = user.user_id }, new AjaxOptions { Confirm = "Are You sure to delete?", UpdateTargetId = "article_1" })


Q: Kohana 3 ORM query using NOTIN() Is there a way to use a http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_not-in with Kohana's ORM? Something like:
$products = ORM::factory('products')->notin('contry_id', $csl)->find_all();

A: Use where statement:
$products = ORM::factory('products')->where('contry_id', 'NOT IN', $csl)->find_all();

$csl must be array


Q: How to focus on form input after appending it to dom? The snippet below adds a form to the page on click:
$(document).ready(function () {
  $(".reply").click(function () {
    var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
    $(".placeholder").append(form);
  });
});

to the html:
 Reply

The Reply link can appear anywhere on the page. The problem is that after appending the form, the browser jumps to the top of the page.
I'm wondering how to scroll/focus to the title input field after appending the form.
I've tried adding focus() or scroll() after .append(form) but none worked. I've also searched SO, but could not find useful answers to similar question.

A:

$(document).ready(function() {
  $(".reply").click(function(event) {
    event.preventDefault();
    $('.placeholder').html('');
    var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
    $(".placeholder").append(form);
    $("input.title").focus();
  });
});
input,
textarea {
  display: block;
  width: 100%;
  margin-top: 10px;
  box-sizing: border-box;
}

form {
  max-width: 400px;
}

Reply

First , if you donot want it to scroll to top.  Use the  event.preventDefault();
Second , use $('.placeholder').html(''); if you donot want repeated comment form on click.
third , $("input.title").focus(); works just fine. Already tested

A: Use this code it works
  $("[data-scroll-to]").click(function() {
   var form = '<form id="rform" action="/sendme" method="POST"><input class="title" id="id2" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
      $("#id1").append(form);

  var $this = $(this),
      $toElement      = $this.attr('data-scroll-to'),
      $focusElement   = $this.attr('data-scroll-focus'),
      $offset         = $this.attr('data-scroll-offset') * 1 || 0,
      $speed          = $this.attr('data-scroll-speed') * 1 || 500;

  $('html, body').animate({
    scrollTop: $($toElement).offset().top + $offset
  }, $speed);
  if ($focusElement) $($focusElement).focus();

});

https://codepen.io/Thaks123/pen/byWmGo?editors=1111
It works with scroll also.

A: The page is jumping to the top because you are navigating to an anchor. Remove href="#" from the reply link. You could replace it with href="javascript:void(0);"
You should then be able to use .focus() to position the page where you like.


Q: Cast different objects and call a method in same line? I have the code:
        foreach(var o in objects)
        {
            o.Update(time);

            if(o is Portal)
            {
                var a = (Portal)o;
                a.Interact(ref player, player.Interact);
            }
            else if(o is Enemy)
            {
                var e = (Enemy)o;
                e.Update(time, player);
            }
        }

I don't know if anything like this is possible?
I want to do it in one line.
This is what I have in mind:
(Enemy)o => Update(time, player);

I know it's stupid but I want something similar. The method that has player as a parameter is unique to the Enemy object. I have to parse to call it.

A: You can make your loop simpler (in case you use C# 6 or higher):
foreach(var o in objects)
{
    o.Update(time);

    (o as Portal)?.Interact(ref player, player.Interact);
    (o as Enemy)?.Update(time, player);
}

For C# 5 or lower you should use:
foreach(var o in objects)
{
    o.Update(time);

    if (o is Portal)
    {
        ((Portal)o).Interact(ref player, player.Interact);
    }
    else if(o is Enemy)
    {
        ((Enemy)o).Update(time, player);
    }
}

In this case you have less lines of code but you cast two times.
You can cast only one time:
foreach(var o in objects)
{
    o.Update(time);

    var e = o is Portal;
    if (e != null)
    {
        e.Interact(ref player, player.Interact);
    }
    else
    {
        ((Enemy)o).Update(time, player);
    }
}

A: Try this:
((Enemy)o).Update(time, player);

Remember about possible Null Reference Exception if you didn't check a type of this object. In your code everything is fine.

A: You can replace those two lines with a single line as follows:
else if(o is Enemy)
{
    ((Enemy)o).Update(time, player);
}

A: You call the function in that way:
var a = ((Portal)o).Interact(ref player, player.Interact);

so the type of a will be the returned type of Interact, but in context of your code it won't matter much.

A: To go further than other response, you could use the visitor pattern.
First create a IVisitorClient and a IVisitor interface.
interface IVisitorClient
{
    Accept(IVisitor visitor);
}

interface IVisitor
{
    Visit(SceneObject o); // here the types of your objects
    Visit(Enemy e);
    Visit(Portal p);
}

Make your different object implement IVisitorClient.
abstract class SceneObject : IVisitorClient
{
    public virtual void Accept(IVisitor visitor)
    {
         visitor.Visit(this);
    }
}

class Portal : SceneObject
{
...

    public override void Accept(IVisitor visitor)
    {
         visitor.Visit(this);
    }
...
}

class Enemy: SceneObject
{
...

    public override void Accept(IVisitor visitor)
    {
         visitor.Visit(this);
    }
...
}

Then build an updater that implement IVisitor :
class UpdaterVisitor : IVisitor
{
    readonly Player player;
    readonly Time time;

    public UpdaterVisitor(Player player, Time time)
    {
        this.player = player;
        this.time = time;
    }

    public void Visit(SceneObject o)
    {
        e.Update(time);
    }

    public void Visit(Enemy e)
    {
        e.Update(time, player);
    }

    public void Visit(Portal p)
    {
        p.Interact(ref player, player.Interact);
    }
}

Finally, to update the object, the code will look like this.
var updateVisitor = new UpdaterVisitor(player, time);
foreach(var o in objects)
{
    o.Accept(updateVisitor);
}

A: Or do it this way to avoid the double cast...
foreach(var o in objects)
{
    o.Update(time);

    Portal p = o as Portal;

    if(p != null)
    {
        p.Interact(ref player, player.Interact);
    }
    else
    {
        Enemy e = o as Enemy;
        if (e != null)
        {
            e.Update(time, player);
        }
    }
}


Q: Can a variadic template match a non-variadic template parameter? Consider the following snippet:
template<template<class> class T,class U>
struct apply
{
     typedef T<U> type;
};

typedef apply<std::tuple,int>::type tuple_of_one_int; //Should be std::tuple<int>

GCC 4.8.2. says:
type/value mismatch at argument 1 in template parameter list for [...] struct apply
expected a template of type ‘template<class> class T’, got ‘template<class ...> class std::tuple’

Which basically means that a variadic template like std::tuple is not a valid template argument for T in apply.
Is this a GCC bug or does the standard mandates this behaviour?

A: Someone correct me if I'm wrong but it seems like it's correct from this quote:

3 A template-argument matches a template template-parameter (call it P) when each of the template parameters in the template-parameter-list of the template-argument’s corresponding class template or [FI 11] template aliasalias template (call it A) matches the corresponding template parameter in the template-parameter-list of P

A (the given template) has to match each of it's templates parameters to P's the template template.
From the second part of the section we learn the restriction doesn't apply in the reverse, meaning a template template containing a parameter pack can match anything.

When P’s template-parameter-list contains a template parameter pack (14.5.3), the template parameter pack will match zero or more template parameters or template parameter packs in the template-parameter- list of A with the same type and form as the template parameter pack in P

As you probably already knew the way to make it work is
template<template<class> class T,class U>
struct apply
{
         typedef T<U> type;
};

template<class T> using tuple_type  = std::tuple<T>;
typedef apply<tuple_type,int>::type tuple_of_one_int;

The c++11 standard also has an equivalent example to yours.
template <class ... Types> class C { /∗ ... ∗/ };

template<template<class> class P> class X { /∗ ... ∗/ };

X<C> xc; //ill-formed: a template parameter pack does not match a template parameter

The last comment completely describes your situation, class C would be the equivalent of std::tuple in this case.

A: Your code is ill-formed, there is equivalent example in the standard (under 14.3.3/2):
...
template <class ... Types> class C { /∗ ... ∗/ };

template<template<class> class P> class X { /∗ ... ∗/ };
...
X<C> xc; // ill-formed: a template parameter pack does not match a template parameter
...

A: The fix:
template<template<class...> class T,class U>
struct apply
{
     typedef T<U> type;
};

typedef apply<std::tuple,int>::type tuple_of_one_int;
typedef apply<std::vector,int>::type vector_of_int;


Q: Unable to use Imagick class I have installed imagick version:6.8.6-7 on my PC
Operating system:Windows 7 32-bit
Now i want to use Imagick for my PHP project.I am using Wampserver which provides me PHP version:5.3.10.So i also installed a .dll file,made changes in php.ini,verified if the path is set with php_info() before using Imagick class and everything was ok.
Problem description:
I wrote the script to test if i can use Imagick.Following is the script:
<?PHP
function alist ($array) {  //This function prints a text array as an html list.
$alist = "
";
for ($i = 0; $i < sizeof($array); $i++) {
  $alist .= "
$array[$i]";
}
$alist .= "
";
return $alist;
}
exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode
"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"

if(class_exists("imagick") )
{
echo "Ready to use Imagick class";
}
else
{
echo "Cannot use Imagick class";
}
?>

Output
Version return code is 0

    Version: ImageMagick 6.8.6-7 2013-07-23 Q16 http://www.imagemagick.org
    Copyright: Copyright (C) 1999-2013 ImageMagick Studio LLC
    Features: DPC OpenMP
    Delegates: bzlib djvu fftw fontconfig freetype jng jp2 jpeg lcms lzma openexr pango png ps tiff x xml zlib

Cannot use Imagick class

So even if the Version is properly displayed,i am not able to use Imagick class.How to fix this,help

A: 1: Install ImageMagick software Link
2: Download pecl-5.2-dev.zip (choose the version relevant to your PHP) from http://snaps.php.net/
3: Copy php_imagick.dll from the archive you've downloaded to your PHP extention folder.
4: Add the following line to php.ini (in the exntentions section):
extension=php_imagick.dll
5: Restart your server

A: cmorrissey's link for 2) seems to be broken but dlls can be downloaded here.
If you get a "CORE_RL_wand_.dll is missing" error, the solution is here. In my case, I had to take all the "CORE" dlls from the ImageMagic installation folder and copy them into the /php folder.


Q: How do I plot a predicted vs actual graph for my Logit Model I'm new to R, and was wondering if any of you could help me out with the code to make a predicted vs actual graph. I am trying to predict the direction of stock price movements using a GLM Logit Model. Your help will be appreciated.
   cat("\014");
   library(readxl);
   Smarket = read_excel("C:/Users/Sohaib/Desktop/data.xlsx");

   # Download introduction to statistical learning package
   library(ISLR)

   # Define train and test sample
   train = (Smarket$year<2019)
   test = Smarket[!train,]

   # Fitting the LR model on the data
   fit = glm(direction ~ lag1 + open + high + low , data=Smarket, family=binomial, subset=train)

   # Predicting against test data
   prob = predict(fit, test, type="response")

A: Provided that test also has a column of the variable you are predicting you can just run something like
test$prediction <- prob

Then both the actual outcome as well as your prediction are in the same data.frame and you can easily plot them
test <- test[order(test$prediction, decreasing = TRUE),]
test$id = seq(nrow(test),1)

library(ggplot2)
ggplot(data = test) +
  geom_line(aes(x = id, y = prediction)) +
  geom_point(aes(x = id, y = direction))

Naturally this is a less beautiful graph than in an ordinary regression model because your dependant variable is binary.


Q: Eliminating a distinctive blur edge between UINavigationBar and UIVisualEffectView Currently, my view hierarchy consists of a UIViewController (NOT UITableViewController), a UITableView nested in the view controller and a UIVisualEffectView (set to Extra Light) in front of the UITableView, aligned to the bottom of a UINavigationBar. The effect I want to achieve is somewhat similar to that of the App Store's segmented view.
However, I noticed a weird blur edge occurring at the boundary between the navigation bar and the UIVisualEffectView that makes the view look inconsistent, as pictured below (highlighted by the red circle):

Optimally, I would prefer that the UIVisualEffectView blends perfectly with the UINavigationBar's blur.
Thanks.

A: Try to use a UIToolBar instead of a UIVisualEffectView as the background of the segment. The navigation bar has translucent background rather than blur effect. UIToolBar has the same translucent background as navigation bar, so it would look seamless at the edge.

A: Looking to your picture it seems your issue is not attributable to UINavigationBar but to a view where you have added UISegmentedControl.
I don't know your structure but it could be the tableHeaderView (self.tableView.tableHeaderView) so a reasonable way to solve this problem is to change the header color:
Code example:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
        header.contentView.backgroundColor = UIColor.clearColor()
        return header
}


Q: How to replace string value with numeric then change string object to numeric? I have a dataset that has numeric values but in some cells it has <0.0001 which is string.  How can I replace these with 0.00005.  Then I can try to convert to float from string, it won't let me do it since this has to be replaced first.  Here is what I have tried and it hasn't worked.
dataframe 'new':

ID
ALL

1
<0.0001

1
<0.0001

1
15.2

1
<0.0001

2
0.030

2
<0.0001

3
<0.0001

new.ALL[new.ALL == '<0.0001'] = '0.00005'
new.select_dtypes(exclude=np.number).replace(to_replace=['<0.0001'],value='0.00005')

neither one works and no error is thrown, it just won't replace it.

A: Does this work:
df['ALL'].str.replace('<0.0001','0.00005').astype('float')
0     0.00005
1     0.00005
2    15.20000
3     0.00005
4     0.03000
5     0.00005
6     0.00005
Name: ALL, dtype: float64


Q: on mouse over show associated div I have a div class "asset-container" with a data-id attribute.
I also have a div class "popover-content" with an associated data-id.
When I hover over "asset-container", I want the "popover-content" show.
There are a lot of these, which is why I have data-id attached to each of the two divs so I can call the associated div to show.
I have tried several iterations of script and am not getting anywhere
js:
$(document).ready(function() {
    custom_popover();
});
function custom_popover() {
    $(".asset-container").mouseover(function() {
    $('.popover-content [data-id=' + this.value + ']').show();

   });
}

html:

    <video class="img-responsive portrait" type="video/mp4" src="https://ternpro-development.s3.amazonaws.com/media/films/71/mobile/3.mp4" data-id="71">      </video>

    <video class="img-responsive landscape" type="video/mp4" src="https://ternpro-development.s3.amazonaws.com/media/films/69/mobile/2.mp4" data-id="69"></video>

A: Change your code to:
$(".asset-container").mouseover(function() {
   var id = $(this).children("video").data("id");
   $(this).parent().children('.popover-content[data-id=' + id + ']').show();
});


Q: Postgresql: Searching a string with similar characters I have a POSTGRESQL Database with names like:
ʿImād ad-Daula Abu ᾽l-Ḥasan

The user may select this value by typing into a text field. But I would like the user to use similar characters. So, that he can type: "imad" or "hasan".
And still get the same result.
It seems a kinda basic problem to me, but I have not found a solution so far.
I tried it with:
SELECT * FROM person WHERE name ILIKE '%hasan%' ORDER BY name ASC

But it doesn't work for these characters.
I would be really greatful for suggestions.
Thanks

A: You can install the extension unaccent:
CREATE EXTENSION unaccent;

And then you are able to do:
SELECT * FROM person WHERE unaccent(name) ILIKE '%hasan%' ORDER BY name ASC


Q: How does step function selects best linear Models which includes polynomial effects and interaction effects in R? I try to find "best" linear models with continuous and categorical covariables with Interaction Effect by BIC. The continuous covariables should have a quadratic effect on the response variable.
Additional to that, I want to extract the significant covariates from the full model by the following rule:
- If  $Covariable_1*Covariable_i !=0$   for one of the i Covariates, then Covariates_1 and Covariates_i remain in the model (i.e also if just the first order term of the polynomial is significant wrt. p-value then we include also the quadratic term), also all significant interactions
 - If $Covariates_1*Covariates_i==0$ for all i then we exlude this Interaction Term and look at the maineffects of covariate_1: if there is no effect at all, then we remove this covariate.
Does this rule make any sense?
I wonder whether the step function in R considers this rule automatically and if not, whether there is any procedures/methods to this in R.
How would you start and find the best linear model with polynomial effect if you had to choose?

A:
Does this rule make any sense?

It's sensible in empirical modelling to follow the Principle of Marginality: See Venables (1998), "Exegeses on linear models", S-Plus Users' Conference, Washington DC, Including the interaction but not the main effects in a model, Do all interaction terms need their individual terms in a regression model?, & Does triple interaction need to include all main effect variables?.

I wonder whether the step function in R considers this rule automatically and if not, whether there is any procedures/methods to this in R.

Don't know about step—check the manual or code.

How would you start and find the best linear model with polynomial effect if you had to choose?

If I had to use some automatic method for model selection (& I'd rather not—see Algorithms for automatic model selection, & Flom & Cassell (2007), "Stopping stepwise", NESUG), I'd use LASSO in almost all situations that come up in practice (see What are modern, easily used alternatives to stepwise regression?). Otherwise, I'd treat it as a matter of deciding how best to spend degrees of freedom in modelling curvilinear relationships: see the hand-outs for Frank Harrell's Regression Modeling Strategies course, §4.1.


Q: How to merge df1 & df2 but only keep the new rows of df2 I've been searching up for hours how to resolve my issue but found nothing.
I have 2 dataframes that i want to merge on column X but i want to keep y column from df1 and only add the new rows from df2.
Basically this situation:
df1:

x
y

A
1

B
2

C
3

df2:

x
y

A
45

B
37

D
4

desired result:

x
y

A
1

B
2

C
3

D
4

To achieve this, I have tried ;
pd.merge(df1, df2, on = ['x','y'] , how = 'left')

however this does not yield what I need. I have also tried concat but didn't succeed.
The problem seems trivial but I just can't find how to get around it.

A: I think you should be able to do it with append. You can add the rows from df2 where the 'x' value isn't in df1 already.
df1 = df1.append(df2[~df2['x'].isin(df1['x'])], ignore_index=True)


Q: SQLite DB accessed from multiple threads Consider following: I've got Service, which writes into DB in AsyncTask. And my Activity reads data from DB(consider UI thread for simplicity). I access DB using SQLiteOpenHelper. I create single instance in Application onCreate() and then obtain it in service and activity. Is there any possibility that I would get my DB 'dead locked'? Previously, I used ContentProvider for such operations. Though, it is based on using single SQLiteOpenHelper instance, I decided to simplify my project by excluding ContentProvider.
Consider code:
public class App extends Application {

    private OpenHelper openHelper;

    @Override
    public void onCreate(){
        super.onCreate();
            openHelper=new OpenHelper();
    }

        public OpenHelper getHelper(){
            return openHelper;
        }
}

In Activity:
OpenHelper helper=(App)getApplication().getHelper();
SQLiteDatabase db=helper.getReadableDatabase();
// Do reading

And inside Serice, in separate thread:
OpenHelper helper=(App)getApplication().getHelper();
SQLiteDatabase db=helper.getWritableDatabase();
//Do writing

Would it be safe?
UPD This might be the solution, but not sure how to use it.

A: Late, late answer.  You're totally fine.  That's the proper way to do it, actually.  See my blog post: http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection/.  Dig through my profile here.  Lots of examples of this.  ContentProvdier is just a lot of overhead and not needed unless you're sharing data outside of your app.  Transactions are good to speed things up and (obviously) improve consistency, but not needed.
Just use one SqliteOpenHelper in your app and you're safe.

A: My bet: it isn't safe.
To be in safer position you should use SQL transactions. Begin with beginTransaction() or beginTransactionNonExclusive() and finish with endTransaction(). Like shown here

A: This is my solution
I created a class and a private static object to syncronize all db access
public class DBFunctions {
// ...
private static Object lockdb = new Object();

/**
 * Do something using DB
 */
public boolean doInsertRecord(final RecordBean beanRecord) {
    // ...
    boolean success = false;

    synchronized (lockdb) {
              // ...
              //
              // here ... the access to db is in exclusive way
              //

              // ...
      final SQLiteStatement statement = db.compileStatement(sqlQuery);

        try {
            // execute ...
            statement.execute();
            statement.close();

            // ok
            success = true;
        } catch (Exception e) {
            // error
            success = false;
        }
            }

       return success;
    }

}
I tryed using ASYNC task and it works fine .
I hope is the right way to solve the problem.
Any other suggestions ???

A: Good question.  My first thought is it wouldn't be safe.  However, according to the SQLite docs, SQLite can be used in 3 modes. The default mode is "serialized" mode:

Serialized. In serialized mode, SQLite
  can be safely used by multiple threads
  with no restriction

So I assume this it's compiled in serialized mode on Android.

A: Just saw this while I was looking for something else.
This problem looks like it would be efficiently solved by using a ContentProvider. That way both the Activity as well as the Service can use the content provider and that will take care of the Db contention issues.


Q: numerical integration of equation obtained by ParametricNDSolve I am trying to find a definite integral of the solution obtained using ParametricNDSolve (i.e. y[x,a,b]) from 0 to 1 and plot the obtained solution in two variables (i.e. a,b) with a.
Can you please suggest me a solution for the same as my equation is given by
ParametricNDSolve[{Cos[y[x]]*y''[x]*y'[x] + Sin[y[x]]*y'''[x] -
 Sin[y[x]]*y'[x]*y'''[x] + Cos[y[x]]*y''''[x] +
 4*a*(Sin[y[x]])*(Cos[y[x]])^3 - a*(Sin[y[x]])*(Cos[y[x]])^2 +
 b*Sin[y[x]]*Cos[y[x]] == 0, y[0] == 0, y''[1] == 0, y'[1] == 0,
 y'''[1] == -1*a*(Cos[y[1]])}, y, {x, 0, 1}, {a, b}]

all I want is a plot of the integral of Sin[y[x]] from 0 to 1 with a and b.

A: One can integrate an expression within an NDSolve/ParametricNDSolve command. To integrate Sin[y[x]], use the DE u'[x] == Sin[y[x]].
psol = ParametricNDSolve[
  {Cos[y[x]]*y''[x]*y'[x] + Sin[y[x]]*y'''[x] -
     Sin[y[x]]*y'[x]*y'''[x] + Cos[y[x]]*y''''[x] +
     4*a*(Sin[y[x]])*(Cos[y[x]])^3 - a*(Sin[y[x]])*(Cos[y[x]])^2 +
     b*Sin[y[x]]*Cos[y[x]] == 0, y[0] == 0, y''[1] == 0, y'[1] == 0,
   y'''[1] == -1*a*(Cos[y[1]]),
   u'[x] == Sin[y[x]], u[0] == 0},
  {y, u}, {x, 0, 1}, {a, b}];

Plot3D[u[a, b][1] /. psol // Evaluate, {a, 0, 3}, {b, 0, 3}]

A: I am not sure I understand your question correctly. Do these commands do what you want?
Plot[y[2, 3][x] /. sol, {x, 0, 1}]

plPoints =
 Table[With[{f = Sin[y[a, b][x]] /. sol},
   NIntegrate[f, {x, 0, 1}]], {a, 0, 3, 0.1}, {b, 0, 3, 0.1}]

ListPointPlot3D[plPoints]


Q: AutoLayout - UIImageView that doesn't rotate How can I get a UIImageView to not rotate when the user rotates their phone?
All other views in the view controller should update with auto-layout as normal, but I want the UIImageView to stay constant.
How can I accomplish this? Right now I'm rotating the image in viewWillTransitionToSize, but that looks terrible and doesn't account for LandscapeLeft vs. LandscapeRight

A: There's no magic flag to have a UIView not rotate, but you could rotate it back with the following code:
-(void) viewDidLoad {
    [super viewDidLoad];
    // Request to turn on accelerometer and begin receiving accelerometer events
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)orientationChanged:(NSNotification *)notification {
    // Respond to changes in device orientation
    switch ([UIDevice currentDevice].orientation)
    {
        case UIDeviceOrientationLandscapeLeft:
            self.img.transform = CGAffineTransformMakeRotation(-M_PI/2);
            break;
        case UIDeviceOrientationLandscapeRight:
            self.img.transform = CGAffineTransformMakeRotation(M_PI/2);
            break;
        case UIDeviceOrientationPortrait:
            self.img.transform = CGAffineTransformMakeRotation(0);
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            self.img.transform = CGAffineTransformMakeRotation(0);
            break;
        case UIDeviceOrientationFaceUp:
            break;
        case UIDeviceOrientationFaceDown:
            break;
        case UIDeviceOrientationUnknown:
            break;
    }
}

-(void) viewDidDisappear {
    // Request to stop receiving accelerometer events and turn off accelerometer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}


Q: Find the properties of an mp3 file via command line Is it possible, via command line (shell command), to check for properties of a file (like when I right click on a file via Nautilus).
Specifically, given an mp3 audio file, I would like to know how I can extract the info related to title and artist from the audio section of its properties.

A: use the command
mp3info -p %a %t file.mp3

*

*%a for artists

*%t for track title

if mp3info is not installed in you system
sudo apt-get install mp3info

A: If you want a more complete output of the metadata you can use mediainfo or exiftool.
exiftool
To use exiftool simply use the command:
exiftool file.mp3

if it not yet installed, you can install it using:
sudo apt install libimage-exiftool-perl

Output sample:
exiftool 10.\ Trova\ Di\ Danú.mp3
ExifTool Version Number         : 10.10
File Name                       : 10. Trova Di Danú.mp3
Directory                       : .
File Size                       : 6.7 MB
File Modification Date/Time     : 2009:03:06 02:21:58-03:00
File Access Date/Time           : 2017:11:10 09:41:16-03:00
File Inode Change Date/Time     : 2017:11:10 09:41:14-03:00
File Permissions                : rwxrwxrwx
File Type                       : MP3
File Type Extension             : mp3
MIME Type                       : audio/mpeg
MPEG Audio Version              : 1
Audio Layer                     : 3
Audio Bitrate                   : 192 kbps
Sample Rate                     : 44100
Channel Mode                    : Joint Stereo
MS Stereo                       : On
Intensity Stereo                : Off
Copyright Flag                  : False
Original Media                  : True
Emphasis                        : None
ID3 Size                        : 1422
Encoded By                      :
User Defined URL                :
Copyright                       :
Title                           : Trova Di Danú
Album                           : Trova di Danú
Year                            : 2004
Track                           : 10
Comment (esl)                   : Subido por Davisote
Genre                           : Folk Metal
Composer                        :
Original Artist                 :
Artist                          : Tuatha de Danann
Comment                         : ICQ 12126479
Date/Time Original              : 2004
Duration                        : 0:04:50 (approx)

mediainfo
To use mediainfo simply use the command:
mediainfo file.mp3

To install it:
sudo add-apt-repository ppa:shiki/mediainfo
sudo apt-get update
sudo apt-get install mediainfo

Output sample:
mediainfo 10.\ Trova\ Di\ Danú.mp3
General
Complete name                            : 10. Trova Di Danú.mp3
Format                                   : MPEG Audio
File size                                : 6.65 MiB
Duration                                 : 4mn 50s
Overall bit rate mode                    : Constant
Overall bit rate                         : 192 Kbps
Album                                    : Trova di Danú
Track name                               : Trova Di Danú
Track name/Position                      : 10
Performer                                : Tuatha de Danann
Genre                                    : Folk Metal
Recorded date                            : 2004
Writing library                          : LAME3.96
Comment                                  : Subido por Davisote / ICQ 12126479

Audio
Format                                   : MPEG Audio
Format version                           : Version 1
Format profile                           : Layer 3
Mode                                     : Joint stereo
Duration                                 : 4mn 51s
Bit rate mode                            : Constant
Bit rate                                 : 192 Kbps
Channel(s)                               : 2 channels
Sampling rate                            : 44.1 KHz
Compression mode                         : Lossy
Stream size                              : 6.65 MiB (100%)
Writing library                          : LAME3.96


Q: Apply an operation across multiple lists I know in R if I have a list of matrices, I can use the Reduce function to apply an operation across all the matrices.  For example:
l <- list(matrix(rnorm(16), 4, 4), matrix(rnorm(16), 4, 4))
Reduce(`*`, l)

But what if I want to apply this operation across multiple lists?  I could do a brute-force approach with a for loop but I feel like there should be a better way.  I can do two lists with mapply
l2 <- l
mapply(`*`, l, l2, SIMPLIFY = FALSE)

But if I have more that two I'm not sure how to solve that.
The following thoughts all result in errors:
l3 <- l2
mapply(`*`, l, l2, l3, SIMPLIFY = FALSE)
Error in .Primitive("*")(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) :
  operator needs one or two arguments

Reduce(`*`, list(l, l2, l3))
Error in f(init, x[[i]]) : non-numeric argument to binary operator

The desired output is a list of length 2 with the elementwise products of each matrix within each list.  The brute-force loop would look like this:
out <- vector("list", length = 2)
for(i in 1:2){
  out[[i]] <- l[[i]] * l2[[i]] * l3[[i]]
}

A: This combination of Reduce and Map will produce the desired result in base R.
# copy the matrix list
l3 <- l2 <- l

out2 <- Reduce(function(x, y) Map(`*`, x, y), list(l, l2, l3))

which returns
out2
[[1]]
              [,1]        [,2]        [,3]       [,4]
[1,] -5.614351e-01 -0.06809906 -0.16847839  0.8450600
[2,] -1.201886e-05  0.02008037  5.64656727 -2.4845526
[3,]  5.587296e-02 -0.54793853  0.02254552  0.4608697
[4,] -9.732049e-04 11.73020448  1.83408770 -1.4844601

[[2]]
              [,1]         [,2]       [,3]        [,4]
[1,] -4.7372339865 -0.398501528  0.8918474  0.12433983
[2,]  0.0007413892  0.151864126 -0.2138688 -0.10223482
[3,] -0.0790846342 -0.413330364  2.0640126 -0.01549591
[4,] -0.1888032661 -0.003773035 -0.9246891 -2.30731237

We can check that this is the same as the for loop in the OP.
identical(out, out2)
[1] TRUE


Q: AudioRecord object not initializing In the below code my audioRecord object is not initializing. I tried moving it to the onCreate method and made it a global. I've logged the state and that returns a value of 1 which means ready to use. The debugger says that startRecording is being called on an uninitialized object. It is also saying that it could not get the audio source.
Why am I getting these errors?
    package com.tecmark;

    import java.io.BufferedOutputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import android.app.Activity;
    import android.media.AudioFormat;
    import android.media.AudioRecord;
    import android.media.MediaRecorder;
    import android.os.Bundle;
    import android.os.Environment;
    import android.util.Log;
    import android.view.View;
    import android.widget.TextView;

    public class recorder extends Activity  {

        private Thread thread;
        private boolean isRecording;
        private AudioRecord recorder;
        private FileOutputStream os;
        private BufferedOutputStream bos;
        private DataOutputStream dos;
        private TextView text;
        private int audioSource = MediaRecorder.AudioSource.MIC;
        private int sampleRate = 22050;
        private int channel = AudioFormat.CHANNEL_CONFIGURATION_MONO;
        private int encoding = AudioFormat.ENCODING_PCM_16BIT;
        private int result = 0;
        private int bufferSize;
        private byte[] buffer;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            Log.v("onCreate", "layout set, about to init audiorec obj");
            text = (TextView)findViewById(R.id.TextView01);

             bufferSize = AudioRecord.getMinBufferSize(sampleRate,channel,encoding);
             buffer = new byte[bufferSize];

            recorder = new AudioRecord(audioSource, sampleRate,channel,encoding,
                    AudioRecord.getMinBufferSize(sampleRate, channel,encoding));
            Log.i("recorder obj state",""+recorder.getRecordingState());
        }

        public void onClickPlay(View v){

        }

        public void record(){
            Log.i("inside record method", "******");
        File path = Environment.getExternalStorageDirectory();
            Log.v("file path", ""+path.getAbsolutePath());

            File file = new File(path, "test.wav");

            if(file.exists()){
            file.delete();
            }

            path.mkdirs();
            Log.v("file path", ""+file.getAbsolutePath());

            try {
             os = new FileOutputStream(file);
             bos = new BufferedOutputStream(os);
                 dos = new DataOutputStream(bos);
            } catch (Exception e1) {
             e1.printStackTrace();
            }

            int bufferSize = AudioRecord.getMinBufferSize(sampleRate,channel,encoding);
            byte[] buffer = new byte[bufferSize];
            recorder.startRecording();
            isRecording = true;
            try{
                while (isRecording){
            result = recorder.read(buffer, 0, bufferSize);
            for(int a=0; a<result;a++){
                 dos.write(buffer[a]);

                 if(!isRecording){
                   recorder.stop();
                   break;
                 }

            }

             }
             dos.flush();
             dos.close();
        }catch(Exception e){
             e.printStackTrace();
        }

    }// end of record method

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");
        isRecording=false;
    }
    public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");
    }
    public void onClickRecord(View v){
        Log.v("onClickRecourd", "record clicked, thread gona start");
        text.setText("recording");
        thread = new Thread(new Runnable() {
            public void run() {
                isRecording = true;
                record();
            }
        });

        thread.start();
        isRecording = false;
    }
}//end of class

Logcat
01-30 15:23:16.724: ERROR/AudioRecord(12817): Could not get audio input for record source 1 01-30 15:23:16.729:
ERROR/AudioRecord-JNI(12817): Error creating AudioRecord instance: initialization check failed. 01-30 15:23:16.729:
ERROR/AudioRecord-Java(12817): [ android.media.AudioRecord ] Error code
-20 when initializing native AudioRecord object. 01-30 15:23:16.729: INFO/recorder obj state(12817): 1 01-30 15:23:16.729:
WARN/dalvikvm(12817): threadid=13: thread exiting with uncaught exception (group=0x4001b180) 01-30 15:23:16.729:
ERROR/AndroidRuntime(12817): Uncaught handler: thread Thread-7 exiting due to uncaught exception 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord. 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817):     at android.media.AudioRecord.startRecording(AudioRecord.java:495) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817):     at com.tecmark.recorder.record(recorder.java:114) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817):     at com.tecmark.recorder$1.run(recorder.java:175) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817):     at java.lang.Thread.run(Thread.java:1096)

A: The trick with using AudioRecord is that each device may have different initialization settings, so you will have to create a method that loops over all possible combinations of bit rates, encoding, etc.
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
public AudioRecord findAudioRecord() {
    for (int rate : mSampleRates) {
        for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
            for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
                try {
                    Log.d(C.TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
                            + channelConfig);
                    int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);

                    if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
                        // check if we can instantiate and have a success
                        AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);

                        if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
                            return recorder;
                    }
                } catch (Exception e) {
                    Log.e(C.TAG, rate + "Exception, keep trying.",e);
                }
            }
        }
    }
    return null;
}

AudioRecord recorder = findAudioRecord();
recorder.release();

A: I had the same issue, it was solved by putting
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

into the manifest.
Since Lollipop, you also need to specifically ask the user for each permission. As they may have revoked them. Make sure the permission is granted.

A: Problem with initializing few AudioRecord objects could by fixed by using audioRecord.release(); before creating next object...
More here: Android AudioRecord - Won't Initialize 2nd time

A: Now, with lollipop, you need to specifically ask the user for each permission. Make sure the permission is granted.

A: Even after doing all of the above steps I was getting the same issue, what worked for me was that my os was marshmallow and I had to ask for permissions.

A: Just had the same problem.
The solution was to restart the device. While playing with the code I did not release the AudioRecord Object which obviously caused the audio device to stuck.
To test whether the audio device worked or not I downloaded Audalyzer from Google Play.

A: If your mobile phone system is Android M or above,perhaps you need to apply record audio permission in Android M.http://developer.android.com/guide/topics/security/permissions.html

A: in my case I had to manually allow the permission in android 7 for microphone, as sean zhu commented.

A: According to the javadocs, all devices are guaranteed to support this format (for recording):
44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT.
Change to CHANNEL_OUT_MONO for playback.

A: I noticed that when the SDCard on the avd I am running gets full the AudioRecord constructor returns null.  Have you tried clearing the SDCard?

A: I think this has to do with the thread not knowing that you've paused the main activity and still trying to record after you've stopped the recorder.
I solved it by changing my onResume() and onPause() methods to modify the isRecording boolean.
public void onResume() {
    ...
    isRecording = true;
}

public void onPause() {
    ...
    isRecording = false;
}

Then in your thread, surround both your startRecording() and stop() with if-statements checking for isRecording:
if(isRecording)
    recorder.startRecording();
...
if(isRecording)
    recorder.stop(); // which you've done

A: I rewrote the answer from @DustinB for anyone who is using Xamarin Android AudioRecord with C#.
int[] sampleRates = new int[] { 44100, 22050, 11025, 8000 };
Encoding[] encodings = new Encoding[] { Encoding.Pcm8bit, Encoding.Pcm16bit };
ChannelIn[] channelConfigs = new ChannelIn[]{ ChannelIn.Mono, ChannelIn.Stereo };

//Not all of the formats are supported on each device
foreach (int sampleRate in sampleRates)
{
    foreach (Encoding encoding in encodings)
    {
        foreach (ChannelIn channelConfig in channelConfigs)
        {
            try
            {
                Console.WriteLine("Attempting rate " + sampleRate + "Hz, bits: " + encoding + ", channel: " + channelConfig);
                int bufferSize = AudioRecord.GetMinBufferSize(sampleRate, channelConfig, encoding);

                if (bufferSize > 0)
                {
                    // check if we can instantiate and have a success
                    AudioRecord recorder = new AudioRecord(AudioSource.Mic, sampleRate, channelConfig, encoding, bufferSize);

                    if (recorder.State == State.Initialized)
                    {
                        mBufferSize = bufferSize;
                        mSampleRate = sampleRate;
                        mChannelConfig = channelConfig;
                        mEncoding = encoding;
                        recorder.Release();
                        recorder = null;
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(sampleRate + "Exception, keep trying." + ex.Message);
            }
        }
    }
}


Q: $\text{Ext}(H, \mathbb{Z})$ is isomorphic to the torsion subgroup of $H$ if $H$ is finitely generated From Hatcher, page 196, before corollary 3.3.
We are first given these three properties of the Ext functor:
$\text{Ext}(H \oplus H', G) \cong \text{Ext}(H, G)\oplus\text{Ext}(H′, G)$.
$\text{Ext}(H, G) = 0$ if $H$ is free.
$\text{Ext}(Z_n, G) \cong G/nG.$
Then, Hatcher writes "these three properties imply that $\text{Ext}(H, \mathbb{Z})$ is isomorphic to the torsion subgroup of $H$ if $H$ is finitely generated".
I'm trying to understand why that is.
I know a torsion subgroup is the subgroup composed of all elements of finite order. Also, a finitely generated abelian group $H$ is the direct sum of a free abelian group (which I'll call $H'$) and its torsion subgroup (which I'll call $T$).
So $$\text{Ext}(H)=\text{Ext}(H'\oplus T)$$
From the first property, this equals
$$\text{Ext}(H')\oplus\text{Ext}(T).$$
As $H'$ is free, this equals (from the second property)
$$0\oplus \text{Ext(T)}=\text{Ext(T)}.$$
But why does $\text{Ext}(T)=T$ hold?

A: The third property (with $G=\mathbb{Z}$) tells you that if $C$ is a finite cyclic group, then $\operatorname{Ext}(C,\mathbb{Z})\cong C$.  Furthermore, any finitely generated torsion abelian group is a direct sum of cyclic groups.  So $T$ is a direct sum of cyclic groups, so by the first and third properties, $\operatorname{Ext}(T,\mathbb{Z})\cong T$.  Note, however, that the isomorphism in the third property is not canonical, so while $\operatorname{Ext}(H,\mathbb{Z})$ is isomorphic to $T$, it is not canonically isomorphic to $T$.

A: To elaborate on my comment, applying $\text{Ext}^{\bullet}(A, -)$ to the short exact sequence $0 \to \mathbb{Z} \to \mathbb{R} \to S^1 \to 0$ produces the long exact sequence
$$0 \to \text{Hom}(A, \mathbb{Z}) \to \text{Hom}(A, \mathbb{R}) \to \text{Hom}(A, S^1) \to \text{Ext}^1(A, \mathbb{Z}) \to 0$$
where we can ignore the rest of the sequence because $\text{Ext}^1(A, \mathbb{R})$ vanishes, thanks to the fact that $\mathbb{R}$ is divisible and hence injective. (So is $S^1$; in fact what we've written down above is an injective resolution of $\mathbb{Z}$.)
If $A$ is torsion, then $\text{Hom}(A, \mathbb{R}) = 0$, and the long exact sequence above produces a natural isomorphism
$$\text{Hom}(A, S^1) \cong \text{Ext}^1(A, \mathbb{Z}).$$
The group $\text{Hom}(A, S^1)$ is known as the Pontryagin dual $\widehat{A}$ of $A$. If $A$ is finite it is noncanonically isomorphic to $A$. In general it naturally has a topology making it a profinite abelian group, and every profinite abelian group arises in this way.


Q: how to highlight ListView multiple views on click? Well I want to highlight the view so the user can see which item it have selected. I tried like this:
View.setBackground(COLOR.RED);

Inside listView on item click listener and it works, but if the list get scrolled random views start changing backgrounds. How can I highlight them and don't lose what item is highlighted on listView scroll?
Note: I'm using a custom adapter with one imageView and 3 textView per row.
Thanks
EDIT: Sorry forgot to say that I want to be able to select multiple items.

A: Set the background color of the items layout? look here https://github.com/cplain/custom-list the concepts should be the same - just ignore my runnable

A: A quick way to do this is to create a couple custom styles; in the drawable folder you can create styles for normal and hover or pressed states:
So in ../drawable/ you want to make a couple elements:
1) The list_bg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#db0000"
      android:centerColor="#c50300"
      android:endColor="#b30500"
      android:angle="270" />
</shape>

2) The list_bg_hover.xml file:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#db0000"
      android:centerColor="#c50300"
      android:endColor="#b30500"
      android:angle="270" />
</shape>

3) The list_selector.xml file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/list_bg" android:state_pressed="false" android:state_selected="false"/>
    <item android:drawable="@drawable/list_bg_hover" android:state_pressed="true"/>
    <item android:drawable="@drawable/list_bg_hover" android:state_pressed="false" android:state_selected="true"/>

</selector>

Now, in order to use this all you have to do is attach the style to your layout for the ListView row item like this, android:listSelector="@drawable/list_selector" and that should do the trick.


Q: Error With UICollectionView Sections While Accessing Cells I'm writing a loop that will go through each one of my cells, and make them wiggle. (Like the deletion effect on iOS's home screen). When I do this with just one cell, it works like a charm. When I write a loop to do this, I get an odd error:

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'request for number of
  items before section 2 when there are only 1 sections in the
  collection view'

Now, when I researched this error the only information I could find was that this occurred when a user tried deleting a cell. That's not my case. (Well, yet at least. Just want to make them all wiggle first).
Here is my code:
#define RADIANS(degrees) ((degrees * M_PI) / 180.0)
    CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5.0));
    CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5.0));

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {

  int visible = self.gridView.visibleCells.count;

    for (int i = 0; i < visible; i++) {

    NSIndexPath *path = [NSIndexPath indexPathWithIndex:i];
    myCell = [self.gridView cellForItemAtIndexPath:path];

    myCell.transform = leftWobble;

    [UIView beginAnimations:@"wobble" context:(__bridge void *)(myCell)];
    [UIView setAnimationRepeatAutoreverses:YES]; // important
    [UIView setAnimationRepeatCount:10];
    [UIView setAnimationDuration:1.25];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(wobbleEnded:finished:context:)];

    myCell.transform = rightWobble; // end here & auto-reverse

    }
  [UIView commitAnimations];

}
@end

Like I said, it works fine for one cell, and throws that error when I try to write a loop to do them all. Does anyone know what's wrong here?
Side note, how can I add a small delete buttons inside the upper left of the collection view cells programmatically in this loop? I'm very, very new to collection views.
Also just found out, my entire view wobbles when I side scroll, not just the cells.... Very odd.

A: Try this:
#define RADIANS(degrees) ((degrees * M_PI) / 180.0)
CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5.0));
CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5.0));

for (UICollectionView *cell in self.gridView.visibleCells) {
    cell.transform = leftWobble;
}

[UIView beginAnimations:@"wobble" context:nil];
[UIView setAnimationRepeatAutoreverses:YES]; // important
[UIView setAnimationRepeatCount:10];
[UIView setAnimationDuration:1.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(wobbleEnded:finished:context:)];

for (UICollectionViewCell *cell in self.gridView.visibleCells) {
    cell.transform = rightWobble;
}
[UIView commitAnimations];

how can I add a small delete buttons inside the upper left of the collection view cells programmatically in this loop?

Add delete button as UIButton to your cell's subviews in you custom UICollectionViewCell subclass, and setHidden:NO when needed.

Also just found out, my entire view wobbles when I side scroll, not
  just the cells.... Very odd.

Edited.


Q: Are there Trojan family or Hilda family satellites locked in Earth's orbit? Jupiter has many Trojan asteroids located at Lagrangian points L4 and L5 and Hilda asteroids dispersed between points L3, L4, and L5.
Does the Earth have similar satellites?  If so, how many?

A: Yes, but just barely (i.e. only one so far), and only for the L4 point.  And this was only recently discovered.  Dr. Phil Plait (an Astronomer) covers this at his Discover Magazine blog in his usual easy to read style.

NASA’s Wide-field Infrared Survey Explorer (WISE) has found the very first asteroid that (more or less) shares an orbit with Earth! Called 2010 TK7, this asteroid is about 300 meters (roughly 1000 feet) across, and is the first in an up-to-now theoretical class of objects called Earth Trojans.

The University of Western Ontario astronomer Paul Weigert has a page describing this.
Additionally, you can get a pre-print of their paper (PDF).


Q: Valgrind's error message I got "Conditional jump or move depends on uninitialised value(s)" , and it is coming from function process_server(). I have tried to figure out where it is coming, but to no avail.
Message from valgrind.

==2468== Conditional jump or move depends on uninitialised value(s)
==2468==    at 0x402B3D: process_server (in /home/emeka/Desktop/dump/project/serverd)
==2468==    by 0x402DB3: main (in /home/emeka/Desktop/dump/project/serverd)
==2468==

#include "signal.h"
#include "string.h"
#include "sys/types.h"
#include "unistd.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "netdb.h"
#include "stdlib.h"
#include "ctype.h"
#include "stdio.h"
#include "utility.h"
#include "route.c"
#include "tokenize.c"
#include "bridge.c"

#define PORT 1253
#define ADDRESS "127.0.0.1"
#define START  "start"
#define  STOP  "stop"
#define LISTENQ 4

typedef struct sockaddr SA;
//#define INET6_ADDRSTRLEN 3000
requested_data *re_data;

int switch_ch;
struct sockaddr_in serveraddr;

int start_server(int port){
    int listenid;
    int optval=1;
    typedef struct sockaddr SA;
    if((listenid = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        error_message("Error in startServer <Failed to create socket>");
    }
    if (setsockopt(listenid, SOL_SOCKET, SO_REUSEADDR,
                   (const void *)&optval , sizeof(int)) < 0)
            return -1;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons((unsigned short)port);
    if(bind(listenid, (SA*)&serveraddr, sizeof(serveraddr)) < 0) {
        error_message("Error in startServer <Failed to bind socket>");
    }
    if(listen(listenid, LISTENQ) < 0) {
        error_message("Error in startServer <Failed to listen>");
    }

    return listenid;
}

void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) {
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

void process_server(int listenid){
    char remoteIP[INET6_ADDRSTRLEN];
    int fd, read_size;
        const int buffer_size = 1000;
    char *client_message = malloc(sizeof(char) * buffer_size);
        if(!client_message){
           printf("Not enough memory");
           abort();
         }
    struct sockaddr_storage remoteaddr; // client address
    socklen_t addrlen;
    addrlen = sizeof remoteaddr;
    char *gen, gen_int = 0, supplied_answer;
        while((fd = accept(listenid, (struct sockaddr *)&remoteaddr, &addrlen))) {
        while((read_size = recv(fd, client_message, buffer_size, 0)) > 0) {
            printf("%s", client_message);
            re_data = router(client_message, read_size);
            printf("Method %s --url::%s=+++\n", re_data->method, re_data->url);
            switch_ch = 1;
            free(client_message);
            client_message = malloc(sizeof(char) * buffer_size);
            if(!client_message){
                printf("Not enough memory");
                abort();
            }
            break;

        }
        printf("DE server: new connection from %s on "
                            "socket %d\n",
                            inet_ntop(remoteaddr.ss_family,
                                get_in_addr((struct sockaddr*)&remoteaddr),
                                remoteIP, INET6_ADDRSTRLEN),fd);
        str_query *rem_data;
        str_query *header_meta = re_data->meta_data;
         while(header_meta){
            if(strncasecmp(re_data->method, "PUT", 3) == 0){
                if(strncasecmp(re_data->url, "/answer", 7) == 0){
                    if(strlen(re_data->url) == 7){
                        if(strncasecmp(header_meta->req_name, "question", 8) == 0){

                            int res_int = parse_input(header_meta->req_value);

                            if(gen_int == res_int && supplied_answer == res_int){
                                send(fd, "HTTP status 200 OK" , 18, 0);
                            } else {
                                send(fd, "400 Bad Request" , 15, 0);
                            }

                            printf("\n Resulted from computation  of %s  result :: %d\n", header_meta->req_name, res_int);

                        }
                    }

                }
            }
            if(switch_ch){
                if(strncasecmp(re_data->url, "/question" , 9) == 0){
                    if(strncasecmp(re_data->method, "GET", 3) == 0){
                        gen = pmain();
                        send(fd, gen, strlen(gen), 0);
                        gen_int = parse_input(gen);
                        switch_ch = 0;
                        printf("\n Resulted from generated computation  of %s  result :: %d\n", header_meta->req_name, gen_int);
                        free(gen);
                    }
                }
            }
            if(strncasecmp(header_meta->req_name, "answer", 8) == 0){
                supplied_answer = atoi(header_meta->req_value);

            }

            printf("\nname %s    value %s\n", header_meta->req_name, header_meta->req_value);
            rem_data = header_meta;
            header_meta = header_meta->next;
            free(rem_data->req_name);
                        free(rem_data->req_value);

            free(rem_data);

        }
        if(!client_message){
           free(client_message);
        }
        free(re_data);
        close(fd);
    }
    return;

}

int main(int argc, char **argv) {
    int port, pid, server_conn = 1;
    int internet_address_len = 15;
    char serAdd[internet_address_len];
    char strAction[7];
    if(argc == 1) {
        port = PORT;
        strcpy(serAdd, ADDRESS);
    } else if(argc == 2){
        port = atoi(argv[1]);
        strcpy(serAdd, ADDRESS);
    } else if(argc == 3) {
        port = atoi(argv[1]);
        int n = strlen(argv[2]);
        strncpy(serAdd, argv[2], n);
        if(n >= internet_address_len){
            error_message("Internet address is incorrect");
        }
        serAdd[n] = '\0';
    }
    printf("\n\tDE is a basic server built to carry out simple things\n"
            "\t-----    -----\n"
            "\t|    |   |\n"
            "\t|    |   -----\n"
            "\t|    |   |\n"
            "\t-----    -----\n"
           "\tMethods implemented [Get & Put]\n"
           "\tTo start type start\n"
            "\tTo stop type stop\nDE]");
    scanf("%s", strAction);
    if (strcmp(strAction, START) == 0){
        printf("Server %sed\n", START);
        int listenid = start_server(port);
        printf("listen on port %d & listening is %d\nDE]", port,listenid);
        signal(SIGPIPE, SIG_IGN);
        while(server_conn) {
            pid =fork();
            if(pid == 0) {
                process_server(listenid);
                break;
            }
            scanf("%s", strAction);
            if (strcmp(strAction, STOP) == 0) {
                close(listenid);
                return 0;
            }

        }

    }

    return 0;

}


Q: protect folders via htaccess i want to protect some folders from a normal user but i (from localhost or my IP address) m unable to see the folder structure...so i do this
write a .htaccess file in that folder(eg.project/cms/js) and write below code
# no nasty crackers in here!
order deny,allow
deny from all
allow from 192.168.1.7

but by using this prohibit to everyone( including me) to see that folder structure.....
how do i protect that folder from other users except myself?

A: I think you got the allow and deny the wrong way around:
order allow,deny
allow from 192.168.1.7
deny from all

which first processes all the allow statements and next the deny statements.

A: I just checked, your above example works fine for me on my Apache 2.
Make sure your IP really is 192.168.1.7. Note that if it's the local machine you're trying to access, your IP will be 127.0.0.1.


Q: Upper bounding trace of matrix Let $[E]_{n\times n}$ be a symmetric positive semi definite matrix, and let $[X]_{n\times j}$ a matrix having orthonormal columns then, the problem is to give an upper and lower bound on the expression  $\text {Tr}\, ( XX^TE).$

A: You have $$\text {Tr}\, (XX^TE)=\text {Tr}\, (X^TEX)\geq0. $$ And $$0\leq\text {Tr}\, (X^TEX)\leq\|E\|\,\text {Tr}\, ( X^TX)=n\|E\|. $$ We can get a similar estimate, in the other direction, with the smallest eigenvalue of $E $.
In summary, if $\lambda_1$ and $\lambda_n $ are the biggest and smallest eigenvalues of $E $, we get
$$ n\lambda_n \leq\text {Tr}\, (XX^TE)\leq n\lambda_1. $$


Q: Exposing a DataGridView's Columns Property on the Designer in a composite UserControl Suppose I have a composite UserControl (called 'ListTable'), consisting of a label, two buttons and a DataGridView. The label is the title for the DataGridView, and the two buttons are Add Row and Delete Row, with basic, obvious functionality.
How do I expose the DataGridView's columns in the Designer, so that I can edit the DataGridView's columns through the UserControl in the exact same way I would if editing the DataGridView itself?
WHAT I'VE TRIED:
Various combinations of wrapping the DataGridView's Columns property in the ListTable via a property titled 'TableColumns' of the form 'List', with various attribute values, such as:
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
    [Editor(typeof(TableColumnEditor),
        typeof(System.Drawing.Design.UITypeEditor))]
    public List<DataGridViewColumn> TableColumns
    {
        get
        {
            List<DataGridViewColumn> columns = new List<DataGridViewColumn>();
            foreach (DataGridViewColumn col in table.Columns)
            {
                columns.Add(col);
            }

            return columns;
        }
        set
        {
            this.table.Columns.Clear();

            foreach (DataGridViewColumn col in value)
            {
                this.table.Columns.Add(col);
            }
        }
    }

Where TableColumnEditor is:
class TableColumnEditor : CollectionEditor
{
    public TableColumnEditor(Type type) : base(type) { }

    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        object result = base.EditValue(context, provider, value);
        ((ListTable)context.Instance).TableColumns = (List<DataGridViewColumn>)result;

        return result;
    }
}

None of this has seemed to work. Most of this is just prayful patchwork that I don't completely understand.
So, the classic dilemma: I do need to sit down and learn about these innards, but I don't have the (work)time to do an unfocused, leisurely tramp through MSDN's more esoteric WinForms articles. Is the code above salvageable? Is it in the right direction?

A: Does this help:
Put a BindingSource on the Form (BindingSource1).
Set your DataGridView's Datasource to Binding1.
Open the designer for the Form in question, and assuming you want to show the columns for the MyObject class, enter the following:
this.BindingSource1.Datasource = typeof(YourNamespace.MyObject);


Q: gwt component to auto-complete text I am using Google Web Toolkit to create a web based XML and Code editor- in this code/xml data will be in a text area... What I want to do is allow code auto-completion- so when user starts typing some text, the possible complete values for the partially typed in text are shown, now user can either select one of the shown values, or type in the entire value.
Is there a GWT component that does this? The only thing that I could think of is using a Tooltip to show possible auto-completion options, and enable the user to select one of the values from the tooltip (this value should then be entered into the text area).
Is this the only approach to solve my problem? Is there a better way of doing this?

A: GWT library has very robust SuggestBox component for that. See description and example here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SuggestBox.html
Plus, I'd recommend to review a video tutorial how to use it:
http://www.rene-pickhardt.de/building-an-autocomplete-service-in-gwt-screencast-part-3-getting-the-server-code-to-send-a-basic-response/
Actually there are set of videos, but suggestion box functionality is described exactly there.
Hope this helps.