text:
Q: how to install c compiler without internet connectivity on opensuse 15? I am having OpenSUSE Linux server 15 without internet connectivity and I was trying to install Nginx from the source.
while installing Nginx dependency pcre from the source I am getting the below error.
ip-10-10-4-30:/home/ec2-user/softwares # cd pcre-8.44/
ip-10-10-4-30:/home/ec2-user/softwares/pcre-8.44 # ./configure
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... no
checking whether make supports nested variables... no
checking whether make supports nested variables... (cached) no
checking whether make supports the include directive... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/home/ec2-user/softwares/pcre-8.44':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details

A: nginx is available for OpenSUSE. One thing you might try is to download the DVD ISO image then use imagewriter to write it to a USB flash drive. You can then add it as a software repository using Yast and install nginx, gcc, or whatever else you need that way.  It isn't complete, but it should contain enough.
You might try installing the pcre-devel and the various libpcre RPMs which has version 8.45.
Here is what my system currently has installed (OpenSUSE 15.3):
rpm -q -a | grep pcre
pcre-devel-8.45-20.10.1.x86_64
libpcre16-0-8.45-20.10.1.x86_64
libpcre1-debuginfo-8.41-6.4.2.x86_64
libpcre2-16-0-10.31-3.3.1.x86_64
pcre-doc-8.45-20.10.1.noarch
pcre-tools-8.45-20.10.1.x86_64
libpcre1-32bit-8.45-20.10.1.x86_64
libpcre1-8.45-20.10.1.x86_64
pcre2-tools-10.31-3.3.1.x86_64
libpcre2-posix2-10.31-3.3.1.x86_64
pcre2-doc-10.31-3.3.1.noarch
libpcre2-8-0-10.31-3.3.1.x86_64
libpcrecpp0-8.45-20.10.1.x86_64
libpcreposix0-8.45-20.10.1.x86_64
libpcre2-32-0-10.31-3.3.1.x86_64
pcre-debugsource-8.41-6.4.2.x86_64

You will also need gcc7.
pcre-devel has the following dependencies, which I assume you will also require if compiling it:
rpm -q --requires pcre-devel
/bin/sh
/usr/bin/pkg-config
libpcre1 = 8.45
libpcre16-0 = 8.45
libpcrecpp0 = 8.45
libpcreposix0 = 8.45
libstdc++-devel
pkgconfig(libpcre)
rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib(FileDigests) <= 4.6.0-1
rpmlib(PayloadFilesHavePrefix) <= 4.0-1
rpmlib(PayloadIsXz) <= 5.2-1

gcc and g++ also have a number of dependencies:
rpm -q --requires gcc7
binutils
cpp7 = 7.5.0+r278197-4.30.1
glibc-devel
ld-linux-x86-64.so.2()(64bit)
ld-linux-x86-64.so.2(GLIBC_2.3)(64bit)
libasan4 >= 7.5.0+r278197-4.30.1
libatomic1 >= 7.5.0+r278197-4.30.1
libc.so.6()(64bit)
libc.so.6(GLIBC_2.11)(64bit)
libc.so.6(GLIBC_2.14)(64bit)
libc.so.6(GLIBC_2.2.5)(64bit)
libc.so.6(GLIBC_2.3)(64bit)
libc.so.6(GLIBC_2.3.3)(64bit)
libcilkrts5 >= 7.5.0+r278197-4.30.1
libgcc_s1 >= 7.5.0+r278197-4.30.1
libgmp.so.10()(64bit)
libgomp1 >= 7.5.0+r278197-4.30.1
libisl.so.15()(64bit)
libitm1 >= 7.5.0+r278197-4.30.1
liblsan0 >= 7.5.0+r278197-4.30.1
libm.so.6()(64bit)
libm.so.6(GLIBC_2.2.5)(64bit)
libmpc.so.3()(64bit)
libmpfr.so.6()(64bit)
libmpx2 >= 7.5.0+r278197-4.30.1
libmpxwrappers2 >= 7.5.0+r278197-4.30.1
libtsan0 >= 7.5.0+r278197-4.30.1
libubsan0 >= 7.5.0+r278197-4.30.1
libz.so.1()(64bit)
rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib(FileDigests) <= 4.6.0-1
rpmlib(PayloadFilesHavePrefix) <= 4.0-1
rpmlib(PayloadIsXz) <= 5.2-1

nginx lists the following dependencies for my system (I do not have it installed):
libpthread.so.0()(64bit)
libdl.so.2()(64bit)
libz.so.1()(64bit)
libpthread.so.0(GLIBC_2.2.5)(64bit)
libcrypto.so.1.1()(64bit)
libcrypto.so.1.1(OPENSSL_1_1_0)(64bit)
libpthread.so.0(GLIBC_2.3.2)(64bit)
libxml2.so.2()(64bit)
libxml2.so.2(LIBXML2_2.4.30)(64bit)
/usr/bin/perl
libxml2.so.2(LIBXML2_2.6.0)(64bit)
libdl.so.2(GLIBC_2.2.5)(64bit)
libc.so.6(GLIBC_2.28)(64bit)
libssl.so.1.1()(64bit)
libssl.so.1.1(OPENSSL_1_1_0)(64bit)
libcrypt.so.1()(64bit)
libpcre.so.1()(64bit)
libcrypt.so.1(XCRYPT_2.0)(64bit)
libxslt.so.1()(64bit)
libxslt.so.1(LIBXML2_1.0.11)(64bit)
libssl.so.1.1(OPENSSL_1_1_1)(64bit)
libperl.so()(64bit)
libxslt.so.1(LIBXML2_1.0.18)(64bit)
libgd.so.3()(64bit)
libexslt.so.0()(64bit)
perl = 5.26.1
/bin/sh
shadow
sysuser-shadow

It also recommends:
logrotate
vim-plugin-nginx
nginx-module-fancyindex
nginx-module-geoip2
nginx-module-headers-more
nginx-module-http-flv

though I do not know the dependencies of these modules.
To compile it you will likely need the -devel packages for many of these.


text:
Q: Does Google Earth Engine (GEE) compute Vegetation Condition Index (VCI) time series correctly? The formula to compute VCI from long term dataset is
VCI= (NDVI_current-NDVI_min)/(NDVI_max-NDVI_min) * 100, refer to Drought monitoring using the Vegetation Condition Index (VCI)
Map.centerObject(geometry, 7);

var scaleMOD = function(img) {
        return  img
          .divide(10000)
          .float()
          .set("system:time_start", img.get("system:time_start"));
};

var modis = ee.ImageCollection("MODIS/006/MOD13Q1")
            .map(scaleMOD)
            .filterBounds(geometry)
            .select('NDVI');

Let, months selected for VCI calculation are September and October from the year 2000 to 2010 (11 years time period).
var startyear = 2000;
var endyear = 2010;
print ('no of years in study period', endyear - startyear + 1);
var startmonth = 9;
var endmonth = 10;
print ('no of months in study period', endmonth - startmonth + 1);

var startdate = ee.Date.fromYMD(startyear, startmonth, 1);
var enddate = ee.Date.fromYMD(endyear , endmonth, 30);
var years = ee.List.sequence(startyear, endyear);
var months = ee.List.sequence(startmonth,endmonth);

var modis_list = [];
for(var i = startmonth; i <=endmonth; i++) {
  for(var j = startyear; j <=endyear; j++){
    modis_list.push(modis.filter(ee.Filter.calendarRange(i, i, 'month'))
                          .filter(ee.Filter.calendarRange(j, j, 'year')));
  }
}
print(modis_list);
var modis_filtered_flattened = ee.ImageCollection(ee.FeatureCollection(modis_list).flatten());

These are the monthly composites of NDVI using MODIS dataset MOD13Q1,
// NDVI composites for every month
var monthlyNDVI =  ee.ImageCollection.fromImages(
  years.map(function (y) {
    return months.map(function(m) {
      var monthly = modis_filtered_flattened
        .filter(ee.Filter.calendarRange(y, y, "year"))
        .filter(ee.Filter.calendarRange(m, m, "month"))
        .mean();
      return monthly
        .set("year", y)
        .set("month", m)
        .set("system:time_start", ee.Date.fromYMD(y, m, 1).millis());}); })
  .flatten());

Here, the total no of monthly composite images of NDVI in the collections will be 22:-
11 of september and 11 of October from 2000 to 2010,
print (monthlyNDVI, 'monthly NDVI composites in study period = no of months * no of years')
Map.addLayer (monthlyNDVI.first().clip(geometry),  {min:0, max:1,  'palette': ['red','yellow', 'green']}, 'MonthlyNDVI')

The image having maximum pixel value of NDVI (max_NDVI) i.e containing the maximum value at each pixel in the raster generated from the time series of 11 years will be 2 (one for each month i.e september and october),
// Extract max values for each month over all years
var MonthlyMAX =  ee.ImageCollection.fromImages(months
  .map(function (m) {
    var maxNDVI = monthlyNDVI
      .filter(ee.Filter.eq("month", m))
      .select("NDVI")
      .reduce(ee.Reducer.max())
      .rename("max_NDVI");
  return maxNDVI
    .set("month", m);})
  .flatten());
print (MonthlyMAX, 'MonthlyMAX no of images = no of months in study period');
Map.addLayer (MonthlyMAX.first().select('max_NDVI').clip(geometry),  {min:0, max:1,  'palette': ['red','yellow', 'green']}, 'MonthlyMAX')

Similarly, the image having minimum value for each pixel of NDVI in the raster (min_NDVI) will also be 2 (one for each month),
// Extract min values for each month over all years
var MonthlyMIN =  ee.ImageCollection.fromImages(months
  .map(function (m) {
    var minNDVI = monthlyNDVI
      .filter(ee.Filter.eq("month", m))
      .select("NDVI")
      .reduce(ee.Reducer.min())
      .rename("min_NDVI");
  return minNDVI
    .set("month", m);})
  .flatten());
print (MonthlyMIN, 'MonthlyMIN  no of images = no of months in study period');
Map.addLayer (MonthlyMIN.first().select('min_NDVI').clip(geometry), {min:0, max:1,  'palette': ['red','yellow', 'green']}, 'MonthlyMIN')

As I am exporting the rasters, the script till here is working fine,
Like from all the monthly composites i.e monthlyNDVI
the value of min_NDVI and max_NDVI is being extracted as asked
i.e maximum value at each pixel in the raster out of 11 years time period in case of max_NDVI and same in case of min_NDVI
// Extract VCI for each month over all years
var vci_monthly = monthlyNDVI.map(function(img){
 var id = img.id();
 var min =  img.reduceRegion(ee.Reducer.min(), geometry,250).get('NDVI');
 var max = img.reduceRegion(ee.Reducer.max(), geometry,250).get('NDVI');
 return img.expression(
   "((NDVI-min)/(max-min))*100",{
     "NDVI" : img,
     "max" : ee.Number(max),
     "min" : ee.Number(min)
   }).copyProperties(img,['system:time_start','system:time_end']);
});

print(vci_monthly)
print (vci_monthly, 'vci_monthly composites in study period = no of months * no of years')
Map.addLayer (vci_monthly.first().clip(geometry),  {min:-100, max:100,  'palette': ['red','yellow', 'green']}, 'vci_monthly')

But I have doubt in case of VCI
Suppose if I want to compute the VCI of October 2005,
then VCI_Oct_2005 should be = (NDVI_Oct_2005 - NDVI_min)/(NDVI_max-NDVI_min) * 100
for example, in here, the VCI values generate by GEE is VCI: 61.16399754930089 from the corresponding value of
NDVI_Oct_2005: 0.4822999835014343,
NDVI_max: 0.7001000046730042,
NDVI_min: 0.4424000084400177,
You will get these values in the inspector of the console, as you will run the script, and click on the raster layers.
Here, according to the calculations of the formula, the value of VCI should have been
= (0.482 - 0.442)/(0.700 - 0.442) * 100 = ~15.5%

But the GEE yield different results from it,
The script is here @ VCI Script
Where is the script wrong (if it is) or
which part of the my interpretation regarding VCI formula is wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not connect to printer on one laptop So me and my wife have two laptops. Both of them are Macs. We also have a printer (Canon MG3600, though I really doubt this matters).
On one machine, we can print just fine. On the other, printing hangs indefinitely and displays "The printer is not responding". However, and here's where things get crazy, when viewing in CUPS, the printer appears just fine. Additionally, using the Printer's network diagnostic to print an IP address, pinging from one machine produces (as expected):
   64 bytes from xxx.xxx.x.x: icmp_seq=547 ttl=64 time=4.758 ms
   64 bytes from xxx.xxx.x.x: icmp_seq=548 ttl=64 time=4.361 ms

While on the other computer
   Request timeout for icmp_seq 582
   ping: sendto: Host is down

.... which... That's crazy right? I could understand printing not working but a simple network ping should be fine shouldn't it? (And yes the wifi works just fine).


text:
Q: How to create an HKQuantitySample from HKStatistics? I'm trying to process HKStatistics that are heart rates and create an HKQuantitySample so that I can append to a local array. I can't figure out what dates to use for startDate and endDate, currently I'm just using Date()but I would rather be more precise and use the actual sample's date.  statistics.StartDate just gives you the date that the statistic collection started, but not the date of the individual sample/statistic.  I see that the statistic also has a mostRecentQuantityDateInterval() property but not sure how to use it here.
 private func processStatistics(withStatistics statistics: HKStatistics?) {

        // Make sure we got non `nil` parameters.
        guard let statistics = statistics else {
            fatalError("no statistics in processStatistics")
        }

        // Dispatch to main, because we are updating the interface.
        DispatchQueue.main.async {
            switch statistics.quantityType {
            case HKQuantityType.quantityType(forIdentifier: .heartRate):

                if let unwrappedQuantity = statistics.mostRecentQuantity() {
                    let statisticAsHKQuantitySample = HKQuantitySample(type: statistics.quantityType, quantity: unwrappedQuantity, start: Date(), end: Date())

                    self.heartRateSamples.append(statisticAsHKQuantitySample)
                }

A: I think you're looking for: mostRecentQuantityDateInterval()
let interval = statistics.mostRecentQuantityDateInterval()
interval.start
interval.end


text:
Q: What does $\bigcup_{i=0}^{\infty}[i, i+2]$ mean? I think I get it but I wanted to be sure before attempting the question:
Question
Describe the following set, and prove your answers correct. (Here brackets
denote intervals on $\mathbb{R}$.)
$\bigcup_{i=0}^{\infty}[i, i+2]$
Does it mean: {$0, 1, 2, 3, 4, 5...,\infty$} $\cup$ {$2, 3, 4, 5, 6, 7,...,\infty$}?
If so, what is the difference between:
$\bigcup_{i=0}^{\infty}[i, i+2]$ and $\bigcup_{i=0}^{\infty}(i, i+2)$

A: In the usual notation, for intervals in the real line $\mathbb{R}$, $[a,b]$ means the closed interval from $a$ to $b$. On the other hand, the notation $(a,b)$ means open interval.
In your question, following this notation, you are dealing with an infinite union of closed intervals. In particular,
$$[0,2]\cup[1,3]\cup[2,4]\cup\dots\cup[k,k+2]\cup\dots$$

A: $\bigcup_{i=0}^\infty [i,i+2]$ means the set $\{x\in\mathbb{R}:\exists i\in\mathbb{Z^+\cup\{0\}}\ \text{such that}\ x\in[i,i+2]\}$. And $\bigcup_{i=0}^\infty (i,i+2)$ means the set $\{x\in\mathbb{R}:\exists i\in\mathbb{Z^+}\cup\{0\}\ \text{such that}\ x\in(i,i+2)\}$. The most obvious difference is that $0$ is a member of the former set while it is not a member of the latter.


text:
Q: HTML Jquery .toggle not toggling back

Home

About

Central Plumping

Roof

Drainage

Gallery

Contact

Home

About

Central Plumping

Roof

Drainage

Gallery

Contact

Hello all, currently trying to learn basic JQuery. I have managed to create a simple navigation bar, with responsive burger menu that hides and shows each navigation bar based on screen size. I then created a burger div that is 100% screen size fixed when displayed but is currently set it display:none. Now i have got my toggle working to display it, but when i try to close the menu bar, it doesn't seem to toggle back. Any help would be great thankyou.
My Jquery script is as follows:

A: i guess your problem is that you're using an anchor tag with empty href attribute.
try chaging in

see example in this FIDDLE

A: I'm getting directed off when I click the element you're trying to tie the click event to.
Here's a working fiddle: https://jsfiddle.net/p85kazv0/
I've simply prevented the a element you're using from its default action (which is of course to direct someone to another location, dictated by whats in the href=""):
$("#toggleburger").click(function(e){
    e.preventDefault();
    $(".menu").toggle();
});

A: Reasons for unexpected behaviour:

*

* has href set to some other page. If you have to implement the menu or buttons that are only for in page activity you should set it as href="#". Meaning do not redirect me anywhere just perform the event linked with this action, which in your case is toggling of another div.

While e.preventDefault() is a workaround, it is not recommended here as the link is sitting there doing nothing. It would suit more if say you had a form that would submit itself but you wanted to do some processing/sanitation before submitting, thereby overriding default action with your logic.

*There are two elements with id=toggleburger. Keep your id unique on one html page. This can give you a lot of pain while debugging.

Here is a working fiddle, I have replaced the hamburger image with text "ToggleBurger".

A: Set the href attribute of the  element equals to #:


text:
Q: Can't connect from an amazon ec2 instance to a mysql server on an external host I have a mysql server hosted on a dedicated server on hostgator. I have an amzon ec2 instance with mysql installed on it. I connected to the ec2 instance through SSH using putty. I am trying to connect the mysql server on my external host from the ec2 instance
mysql -h XXX.XXX.XX.XXX -u XXXX -p
i get a ERROR 2003 (HY000) ...
I have checked all possible issue and the only thing tha i can think of is the amazon firewall.
If I reverse the process and try to connect to the ec2 mysql db from my external serverthrough SSh. it works.
I have also connected to the same external server from another external server.
Please does anyone have a solution why i can't connect to an external db from an amazon ec2 instance

A: From: http://alestic.com/2009/08/ec2-connectivity
edit /etc/mysql/my.cnf and replace this line:
bind-address = 127.0.0.1

with
bind-address = 0.0.0.0

and restart the mysqld server.

A: I had a big problem with external conection in EC2 too, I could only connect after I created a new user with all grant options, I seems like root access can only connect on localhost.
I did evething I could, oppened my firewall, changed my.conf directives and it only worked when I created another user with all grants.

A: Hmm.. external db might be firewalled or your mysql on external server only accept connections from that host.

A: Do you have a security group (in AWS) set up for the box?
If so, have you allowed the port you've specified?


text:
Q: CORS Filter not working as intended I am trying to send a request from my Webstorm application to my backend application, which both are at different ports, I am working with angularJS in the front end and java in backend. I have read up a bit about CORS Filters and I learned that in order to do Cross Origin Requests I need to implement these. However, after doing this my error, being
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access. http://localhost:8080/register?password=&username=
XMLHttpRequest cannot load http://localhost:8080/register?password=&username=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access.

did not change at all which led me to believe I have done something wrong, here is the code from which I am sending the request:
var charmanderServices = angular.module('charmanderServices', ['ngResource']);

var hostAdress = "http://localhost:8080";

charmanderServices.factory("register", ["$resource",
    function($resource){
        console.log('in service');
        return $resource(hostAdress + "/register", {}, {
            'registerUser' : { method: 'POST', isArray: false,
            params: {
                username: '@username',
                password: '@password'
            }
            },
            headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
        });

    }
]);

My corsFilter is written like this:
@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
         //This is not even printing
        System.out.println("Cheers lads, I'm in the filter");
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, X-Auth-Token, Content-Type");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}

This is my web.xml:
<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">

    <display-name>Project</display-name>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.robin.filters.SimpleCORSFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/spring/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

This is the controller where I am catching the request:
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register" , method= RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public boolean register(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password){
        System.out.println("Im in register hurray");
        return userService.register(username, password);
    }
}

Update: I have tried implementing the filter as a OncePerRequestFilter, still doesn't work. Is anyone able to help me further here?
Update#2: Also tried this one, http://software.dzhuvinov.com/cors-filter-installation.html, no luck
Update#3: This was my output in the console, I can see that the response did not add any headers:
Request URL:http://localhost:8080/register?password=g&username=g
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:63343
Referer:http://localhost:63343/Project/index.html?uName=g&uPassword=g&uPasswordConfirm=g
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
Query String Parametersview sourceview URL encoded
password:g
username:g
Response Headersview source
Allow:GET, HEAD, POST, PUT, DELETE, OPTIONS
Content-Length:0
Date:Fri, 04 Apr 2014 09:50:35 GMT
Server:Apache-Coyote/1.1

Update#4: Annotated the filter with @WebFilter instead of @Component, didn't help
Update#5: Here is my applicationContext.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:component-scan base-package="com.robin"/>
    <mvc:annotation-driven/>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <array>
                <value>com.robin.model</value>
            </array>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.robin.model.User</value>
            </list>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <import resource="mysql-context.xml"/>
</beans>

I also added the code from my controller and register.html file here:
charmanderControllers.controller('registerController', ['$scope', 'register',

    function($scope, register){
    $scope.username = '';
    $scope.password = '';

    $scope.register = function () {
        register.registerUser({'username': $scope.username, 'password': $scope.password}).$promise.then(function(data){
            switch(data.response){
                case true:
                    //succes
                    $scope.registered = true;
                    $scope.userExists = false;
                    break;
                case false:
                    //user exists
                    $scope.registered = false;
                    $scope.userExists = true;
                    break;
            }
            console.log(data.response);
        })
    };

        $scope.checkValidRegister = function (invalid) {
            console.log(invalid);
            console.log($scope.passwordConfirm);
            console.log($scope.password);
            console.log($scope.username);
            if (invalid || $scope.password != $scope.passwordConfirm) {
                console.log("I shouldnt be here");
                $scope.validation = true;
                if ($scope.password != $scope.passwordConfirm) {
                    $scope.passwordError = true;
                }
            } else {
                register();
            }
        };
}]);

register.html

Register now!

    <form method="post" class="register" novalidate>

            E-mail:
            <input type="text" name="login" id="email" placeholder="E-mail address..." required ng-model="username">

            Password:
            <input type="password" name="password" id="password" placeholder="Password..."
                   required ng-model="password">

            Confirm password:
            <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm password..."
                   required ng-model="passwordConfirm">
            Passwords do not match!

            <button type="submit" class="register-button" ng-click="checkValidRegister()">Register</button>

    </form>

A: Your code and configuration looks good in general and I was able to run it on local environment. Please remove @Component annotation from your SimpleCORSFilter, because you use it as a plain Servlet Filter and it doesn't need to be a part of Spring context.
UPD. Tomcat 7 has its own CORS filter implementation. You can check documentation and source code for more details. I have modified the headers to reflect its default configuration, should work as expected now.
Since you are already using Spring and if you are using Spring 4.2 or higher, you dont need CorsFilter, but can simply annotate your controller method with CrossOrigin. Here is the excellent article on this, worth a read.
Please also check nice resource which describes CORS configuration for different platforms.
Here is my working example using plain Filter implementation:
Controller:
@Controller
public class UserController {

    private static Logger log = Logger.getAnonymousLogger();

    @RequestMapping(
            value = "/register",
            method = RequestMethod.POST,
            consumes = "application/x-www-form-urlencoded")
    @ResponseBody
    public String register(@RequestParam(value = "user") String username,
                           @RequestParam(value = "password") String password) {
        log.info(username + " " + password);
        return "true";
    }

}

Filter:
public class CorsFilter implements Filter {

    private static final Logger log = Logger.getAnonymousLogger();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("Adding Access Control Response Headers");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

Filter mapping in web.xml:
    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.udalmik.filter.CorsFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/register</url-pattern>
    </filter-mapping>

JS to perform request from separate web app (JQuery):
$(document).ready(function() {
    $('#buttonId').click(function() {
        $.ajax({
            type: "POST",
            url: "http://localhost:8080/register",
            success : function(data){
                console.log(data);
            },
            data : {
                user : 'test.user@acme.com',
                password : 'password'
            }
        });
    }
}


text:
Q: LINQ expression doesn't work (Entity Framework) I have a very simple LINQ expression here, but I don't see why it doesn't work.
I have a function like this:
public FileResult ImageForMovie(Int32? ID)
{
    String image = _entities.Movies
                            .Where(x => x.movie_ID == ID)
                            .Select(x => x.filename)
                            .First();

    return File("~/images/" + image, "image/jpg");
}

I don't get any errors, but the selection doesn't give any results. The view is okay, because if I write directly the image source, it gives the picture.


text:
Q: Need help redirecting a txt file into 3 different array of structs of different sizes (number of elements in the struct) This is the txt file:
P 20.0 2.0 20.1 60.1
P 20.0 2.0 58.1 60.1
P 20.0 2.0 20.1 20.1
P 20.0 2.0 58.1 20.1
O 1.0 1.0
O 2.0 70.0
O 70.0 10.0
X 8.0 8.0
X 8.0 70.0
X 70.0 70.0
X 70.0 8.0

All structures starting with the same letter have to be in the same array. The code I'v been trying looks like this, but I know I'm way off. I feel as though I need to do something like "if struct has 5 elements" then store.
typedef struct {
    char   id;
    double trans_pow;
    double sig_freq;
    double x_cord;
    double y_cord;
    } WAP_t;

void wap_struct_reader(WAP_t waps[], int *counter) {
    int i=0;
    while(scanf("%c %lf %lf %lf %lf", &waps[i].id, &waps[i].trans_pow,
            &waps[i].sig_freq, &waps[i].x_cord, &waps[i].y_cord)!=EOF) {
        i++;
    }
}

A: I guess you need something like this:
void wap_struct_reader(WAP_t p_waps[], WAP_t o_waps[], WAP_t x_waps[], int *counter) {
  int pcount = 0, ocount = 0, xcount = 0;
  char id;
  double trans_pow, sig_freq, x_cord, y_cord;
  *counter = 0;
  while (scanf("%c %lf %lf %lf %lf", &id, &trans_pow, &sig_freq, &x_cord, &y_cord) != EOF)
  {
    WAP_t *p;
    int i;
    switch (id)
    {
    case 'P': p = p_waps; i = pcount++;  break;
    case 'O': p = o_waps; i = ocount++;  break;
    case 'X': p = x_waps; i = xcount++;  break;
    default:
      // TODO: handle case line starts neither with P, O or X.
    }

    p[i].id = id;
    p[i].trans_pow;
    p[i].sig_freq;
    p[i].x_cord = x_cord;
    p[i].y_cord = y_cord;

    (*counter)++;
  }
}

P, O and X lines may be mixed in the input file, so this file is valid.
X 8.0 70.0
P 20.0 2.0 20.1 60.1
X 70.0 70.0
P 20.0 2.0 58.1 20.1
O 1.0 1.0
O 2.0 70.0

Call it like that:
WAP_t pwaps[10], owaps[10], xwaps[10];
int counter;

wap_struct_reader(pwaps, owaps, xwaps, &counter);

Disclaimers:

*

*There is no boundschecking whatsoever done here for brevity.

*You certainly need 3 counters, one for the P lines, one for O lines and one for X lines. I leave this as an exercise to the reader.


text:
Q: Access Form Vba Update Record I want to update a record in Microsoft Access database using forms but is giving and error Expected en of statement. :|
CurrentDb.Execute "UPDATE [Ensamblador]" _
"SET NumerodeEnsamblador=" & Me.textboxone  & "" _
", NombredeEnsamblador='" & Me.textboxtwo & "'" & _
", Especialidad='" & Me.textboxthree & "'" & _
" WHERE NumerodeEnsamblador=" & Me.textboxone

A: It should probably read:
CurrentDb.Execute "UPDATE Ensamblador " & _
"SET NombredeEnsamblador = '" & Me.textboxtwo & "'" & _
", Especialidad='" & Me.textboxthree & "' " & _
"WHERE NumerodeEnsamblador=" & Me.textboxone & ""


text: Q: Finding the Weibull Distribution from the Exponential I've been asked to find the Weibull Distribution using a previously known distribution, which in this case is the Exponential. Could anyone assist me?


text:
Q: Hide Product without Disabling or putting product out of stock I have a product that I want to hide on the front-end but if you have the direct URL I want the product to be accessible and have stock.
What is the best way to achieve this?
I was thinking of wrapping an IF statement around the product content in category grid etc and checking if the product has a custom attribute that says hidden. Is this a crazy way of doing this?

A: You can remove the product from all categories and make the visibility field Catalog. This will remove it from search results also.
And you will still have access to it if you have the correct url.

A: I would just not include that product in the category. If you don't include it in your category then that product will not appear there.
If you want to do it in the code, then your way to do it seems the best option.


text:
Q: How to use Google analytics to track open rates, click rates in a email? I have read the document and there is a track code should be able to help me.
However, how can i actually use it to get the open rates, url click rates?
For the open rates:
I am using swiftmailer to send the mail, is it a way to add the track code (How? Since mail is plain html , no javascript or php is allowed) What i should do in the html/text mail template?
For the url click rates:
Is it separate from the mailing? that means i just have to add the link in the page i append in the mail.  However, are there ways to do it more automatically? For instance, when the mail is sent, i find the url and  add the track code for each link one by one?(But how can i create different track code using php?)
That 's lot of question, sorry.I am inexperience in it, Since it takes sometime to answer the question ,any part of the answer is highly appreciated and i will vote up it.  Thank you again

A: The second part of your question:
If you are creating the email with php, you can easily add customized code to the url GET request, like this:
www.yoururl.com/...?yourvar=345
Then you pass the get variable to js (+validation).
Then on the page itself you can add customized event sending to analytics:
_gaq.push(['_trackEvent', 'name', value]);


text:
Q: To print output of SparkSQL to dataframe I'm currently running Analyze command for particular table and could see the statistics being printed in the Spark-Console
However when I try to write the output to a DF I could not see the statistics.
Spark Version : 1.6.3
val a : DataFrame = sqlContext.sql("ANALYZE TABLE sample PARTITION (company='aaa', market='aab', edate='2019-01-03', pdate='2019-01-10') COMPUTE STATISTICS").collect()

Output in spark Shell
    Partition sample{company=aaa, market=aab, etdate=2019-01-03, p=2019-01-10} stats: [numFiles=1, numRows=215, totalSize=7551, rawDataSize=461390]
19/03/22 02:49:33 INFO Task: Partition sample{company=aaa, market=aab, edate=2019-01-03, pdate=2019-01-10} stats: [numFiles=1, numRows=215, totalSize=7551, rawDataSize=461390]

Output of dataframe
    19/03/22 02:49:33 INFO PerfLogger: </PERFLOG method=runTasks start=1553237373445 end=1553237373606 duration=161 from=org.apache.hadoop.hive.ql.Driver>
19/03/22 02:49:33 INFO PerfLogger: </PERFLOG method=Driver.execute start=1553237373445 end=1553237373606 duration=161 from=org.apache.hadoop.hive.ql.Driver>
19/03/22 02:49:33 INFO Driver: OK
19/03/22 02:49:40 INFO Executor: Running task 0.0 in stage 2.0 (TID 2)
19/03/22 02:49:40 INFO Executor: Finished task 0.0 in stage 2.0 (TID 2). 940 bytes result sent to driver
19/03/22 02:49:40 INFO TaskSetManager: Finished task 0.0 in stage 2.0 (TID 2) in 4 ms on localhost (1/1)
19/03/22 02:49:40 INFO DAGScheduler: ResultStage 2 (show at <console>:47) finished in 0.004 s
19/03/22 02:49:40 INFO TaskSchedulerImpl: Removed TaskSet 2.0, whose tasks have all completed, from pool
19/03/22 02:49:40 INFO DAGScheduler: Job 2 finished: show at <console>:47, took 0.007774 s
+------+
|result|
+------+
+------+

Could you please let me know how to get the same statistics output into the Dataframe.
Thanks.!

A: If you want to print from a Dataframe the way you are using, you can use,
val a : DataFrame = sqlContext.sql("ANALYZE TABLE sample PARTITION (company='aaa', market='aab', edate='2019-01-03', pdate='2019-01-10') COMPUTE STATISTICS")

a.select("*").show()


text:
Q: Ignore image name while getting hash I'm coding a program which'll take an image for an input, check it against images in a database and output the image with the same hash
However, when using hash("imagepath") 2 of the same images give different hashes, even when the only difference is the image's name, which makes me believe the name is the issue
Is there a way to easily ignore the name of the image? (png)

A: How I solved it:
I ended up not using "hashing" but the average pixel by scrambeling pieces of code together, and then find an image with the same average pixel (the average pixels are in a list so it gets the index which it then uses to find a name)
import requests

#Database of possible image average pixels
clone_imgs = [88.0465, 46.2568, 102.6426 ...]

image = <image url>
img_data = requests.get(image).content
with open('image.png', 'wb') as handler: #Download the image as "image.png" (Replace "image.png" with the path where you want to save it)
    handler.write(img_data)
img = Image.open(r"image.png") #Open the image for reading
img = img.resize((100, 100), Image.ANTIALIAS) #A series of compressions to the image
img = img.convert("L")
img_pixel_data = list(spawn.getdata())
img_avg_pixel = sum(spawn_pixel_data)/len(spawn_pixel_data) #Get the average pixel values

clone_img_index = clone_imgs.index(img_avg_pixel) #Find the same pixel value in the database

This worked for me but it has a few downsides:

*

*The images need to be 100% the same in color (A single pixel off can ruin it)

*One of these average pixels can make an infinite amount of images, my database only contained 800 so it still worked (However I had to go from compression to 10x10 to 100x100 to not end up with clones)


text:
Q: Issue hibernate (java.sql.SQLSyntaxErrorException: ORA-01722: invalid number) Not sure what can be causing this error...
I have a class named StudentUnit that can contain a  list of Units.
If I get only StudentUnit objects, the result comes ok, but if I try to get the Units (adding fetchType== eager), then I get java.sql.SQLSyntaxErrorException: ORA-01722: invalid number
But note the fields I mapped on the Unit (unitCode, unitNm) are both Strings. I keep wondering if that could be a problem to have the unitCode as @id, or something related to that...
@Entity
@Table(name = "STUDENT_UNITS")
@NamedQuery (name ="StudentUnit.findByCourseAttemptNo",
query ="SELECT  su FROM StudentUnit su WHERE su.studentNo = :studentNo and su.courseNo = :courseNo and su.courseAttemptNo = :courseAttemptNo")
@FetchProfile(name = "studentUnit", fetchOverrides = { @FetchProfile.FetchOverride(entity = StudentUnit.class, association = "units", mode = FetchMode.JOIN) })
public class StudentUnit{

    @Id
    @Column(name = "STUDENT_NO")
    private Integer studentNo;

    @Column(name = "COURSE_NO")
    private Integer courseNo;

    @Column(name = "UNIT_CODE")
    private String unitCode;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "unitCode")//this one gives problems,which proves the issue is on Unit
    //@OneToMany(mappedBy = "unitCode"): this one is ok, once never tries to get the Unit
    private List<Unit> units;
}

@Entity
@Table(name="UNITS")
public class Unit {

    @Id
    @Column(name = "UNIT_CODE")
    private String unitCode;

    @Column(name = "UNIT_NM")
    private String unitNm;

    @Column(name = "GRADE_CODE_NO")
    private Integer gradeCodeNo;

    @Column(name = "IMPLEMENTATION_DATE")
    private Date implementationDate;

     //getters/setters

}

Information from database:
  STUDENT_UNITS
    (
      STUDENT_NO              NUMBER(10),
      COURSE_NO               NUMBER(5),
      COURSE_ATTEMPT_NO       NUMBER(5),
      UNIT_CODE               VARCHAR2(16 BYTE),
      ORIGINATING_DBKEY       NUMBER
    )

    UNITS
    (
      UNIT_CODE                 VARCHAR2(16 BYTE),
      UNIT_STEM                 VARCHAR2(15 BYTE),
      UNIT_ANTA_VERSION_NO      VARCHAR2(1 BYTE),
      UNIT_NM                   VARCHAR2(100 BYTE),
      IMPLEMENTATION_DATE       DATE
    )

More of the error log:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
root cause

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:130)
    org.springframework.orm.hibernate4.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:56)
    org.springframework.orm.hibernate4.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:43)
    org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
    org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    $Proxy207.findStudentUnits(Unknown Source)
    servicePack.service.student.StudentUnitsService.findStudentUnits(StudentUnitsService.java:21)
    servicePack.service.student.StudentUnitsService$$FastClassByCGLIB$$bfb0625f.invoke(<generated>)
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    servicePack.service.student.StudentUnitsService$$EnhancerByCGLIB$$6133a5f5.findStudentUnits(<generated>)
    servicePack.controller.StudentUnitsController.retrieveStudentUnits(StudentUnitsController.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
root cause

org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
    org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)
    org.hibernate.loader.Loader.getResultSet(Loader.java:2031)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1832)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811)
    org.hibernate.loader.Loader.doQuery(Loader.java:899)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:311)
    org.hibernate.loader.Loader.loadCollection(Loader.java:2228)
    org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:65)
    org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:674)
    org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:80)
    org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1848)
    org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:681)
    org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:1030)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:346)
    org.hibernate.loader.Loader.doList(Loader.java:2516)
    org.hibernate.loader.Loader.doList(Loader.java:2502)
    org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2332)
    org.hibernate.loader.Loader.list(Loader.java:2327)
    org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
    org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268)
    org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    myPack.StudentUnitsSearchDaoImpl.findStudentUnits(StudentUnitsSearchDaoImpl.java:44)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    $Proxy207.findStudentUnits(Unknown Source)
    servicePack.service.student.StudentUnitsService.findStudentUnits(StudentUnitsService.java:21)
    servicePack.service.student.StudentUnitsService$$FastClassByCGLIB$$bfb0625f.invoke(<generated>)
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    servicePack.service.student.StudentUnitsService$$EnhancerByCGLIB$$6133a5f5.findStudentUnits(<generated>)
    servicePack.controller.StudentUnitsController.retrieveStudentUnits(StudentUnitsController.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
root cause

java.sql.SQLSyntaxErrorException: ORA-01722: invalid number

    oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
    oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
    oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879)
    oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
    oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
    oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
    oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
    oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:884)
    oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1167)
    oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
    oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
    oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
    oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
    org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:462)
    org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:56)
    org.hibernate.loader.Loader.getResultSet(Loader.java:2031)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1832)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811)
    org.hibernate.loader.Loader.doQuery(Loader.java:899)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:311)
    org.hibernate.loader.Loader.loadCollection(Loader.java:2228)
    org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:65)
    org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:674)
    org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:80)
    org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1848)
    org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:681)
    org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:1030)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:346)
    org.hibernate.loader.Loader.doList(Loader.java:2516)
    org.hibernate.loader.Loader.doList(Loader.java:2502)
    org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2332)
    org.hibernate.loader.Loader.list(Loader.java:2327)
    org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
    org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268)
    org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    myPack.StudentUnitsSearchDaoImpl.findStudentUnits(StudentUnitsSearchDaoImpl.java:44)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    $Proxy207.findStudentUnits(Unknown Source)
    servicePack.service.student.StudentUnitsService.findStudentUnits(StudentUnitsService.java:21)
    servicePack.service.student.StudentUnitsService$$FastClassByCGLIB$$bfb0625f.invoke(<generated>)
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    servicePack.service.student.StudentUnitsService$$EnhancerByCGLIB$$6133a5f5.findStudentUnits(<generated>)
    servicePack.controller.StudentUnitsController.retrieveStudentUnits(StudentUnitsController.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

Thank you in advance,
Thais.

A: The attribute:
    mappedBy = "unitCode"

is wrong: mappedBy should point to attribute of class StudentUnit, not String.
So just clear mappedBy = "unitCode" or try bidirectional mapping like this:
public class StudentUnit{

    ...

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "studentUnit")
    private List<Unit> units;
}

@Entity
@Table(name="UNITS")
public class Unit {

    @Id
    @Column(name = "UNIT_CODE")
    private String unitCode;

    @ManyToOne
    @JoinColumn(name="STUDENT_NO_ID")
    private StudentUnit studentUnit;

    @Column(name = "UNIT_NM")
    private String unitNm;
}


text:
Q: Calculate average speed from gps based on an equation I am trying to calculate the average battery length in minutes of a motor using the following equation: https://i.imgur.com/CBYRdyR.jpg
I get the average speed by using the following code:
for (Location location : locationResult.getLocations()) {
    int speed = (int) (location.getSpeed() * 2.2369);
    float addedSpeed = avgMPH + speed;
    avgMPH = addedSpeed / 2;
    float math1 = 45 / avgMPH;
    batteryView.setText("Battery: " + String.valueOf(math1 * 60) + " Minutes Remaining");
    }

The issue is that every time the location loops it doubles my battery life each loop even though it is still at 1 miles per hour. it should not loop like this, help appreciated, thanks!

A: I think you are calculating average speed wrong.
You should calculate like this:
 float addedSpeed = avgMPH * numSamples + speed;
 avgMPH = addedSpeed / (numSamples + 1);
 numSamples = numSamples + 1;

Not like this:
float addedSpeed = avgMPH + speed;
avgMPH = addedSpeed / 2;

For example, think you went 1 mph for 10 hours and 100 mph for a hour.
Former will give you average 10 mph which is correct and latter will give you average 55.5 mph which is wrong.


text:
Q: Linking project and framework paths netbeans PHP I am trying to develop an OpenCart module. I've done this already but now, I would like to have different paths for developing it more comfortable:
I would like to have the OpenCart installation (as it were a framework or whatever) with all its files in a different path and have my little module in another path. Is there any way to "import" all OpenCart files when running the project?

A: You should add it to your include path, that way it will see the install but not be in the same path as your project.
Go to your project in the project explorer, expand to see folder 'include path' > right click > properties > PHP Include Path > Add Folder.


text:
Q: Exibir o ano e mês que está vindo do array Já consigo exibir o ano dentro do foreach pela posição, como eu faço pra exibir o mês também?
O array está vindo assim, o mês no caso seria aquele 3, 2, 3, 4 queria exibir esse valor dentro do meu foreach (esse é o var_dump na variavel arquivos)
    array (size=2)
  2016 =>
    array (size=1)
      3 =>
        array (size=1)
          2 =>
            object(stdClass)[44]
              ...
  2017 =>
    array (size=3)
      2 =>
        array (size=1)
          1 =>
            object(stdClass)[45]
              ...
      3 =>
        array (size=1)
          3 =>
            object(stdClass)[46]
              ...
      4 =>
        array (size=1)
          2 =>
            object(stdClass)[47]
              ...

Esse é o meu foreach, como eu poderia fazer isso?

                        <?php foreach ($arquivos as $k => $a): ?>

                                <?= $k; ?>

<?= 'exibir o mes' ?>

                        <?php endforeach; ?>

A: O que você tem é uma matriz, um array multi-dimensional.
Para resolver essa questão você vai precisar aninhar um foreach dentro de outro. Seria basicamente isso:

    <?php foreach ($arquivos as $indice1 => $valor1): ?>

            <?= $indice1; ?>

                <?php foreach ($valor1 as $indice2 => $valor2): ?>

<?= $indice2; ?>

                <?php endforeach; ?>

    <?php endforeach; ?>

Caso tenha intenção de exibir os dias também, basta seguir o mesmo raciocínio.


text:
Q: ExtJS 4: Deactivate all tabs in tab panel I would like to deactivate tabs in the tabbar, but I didn't find any method or config property in Sencha docs http://docs.sencha.com/ext-js/4-0/#!/api/Ext.tab.Panel.

*

*When panel is created, first tab is automatically selected (I would like to prevent this)

*I listen to beforetabchange event and prevent it if some data was modified.

What am I waiting for:

*

*When tab panel is loaded, any tab shouldn't be activated (choosed)

*When user starts click on these tabs I should catch that event and handle it by beforetabchange handler

Thanks a lot for a help.

A: One of tabs will be selected. You can control which one by using activeItem, activeTab properties. Are you trying to create a tab panel without selected item at all?


text:
Q: Balance speed & memory to compute non-redundant cosine similarity matrix Suppose we have N items, where each consists of a 500-element vector. Now suppose we want to calculate all the cosine similarities for unique, unordered pairs and to skip the identity pairs (so for A, B, C, we want AB, AC, and BC, but not BA, CA, CB, AA, BB, CC). We could do this with a double loop (i = 0..(N-1), j = (i+1)..N, calculate cosine of items i and j), but this is very slow, and it may be better to use methods that just calculate the whole matrix (scipy pdist). If N is very big (e.g., 25,000 in my case), though, you run into memory problems (my case exhausts 64gb of RAM).
Is there a method for doing this relatively quickly without doing a double loop but without using tons of memory?


text:
Q: How to send a POST request with BODY in swift I'm trying to make a post request with a body in swift using Alamofire.
my json body looks like :
{
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List":[
        {
        "IdQuestion" : 5,
        "IdProposition": 2,
        "Time" : 32
        },
        {
        "IdQuestion" : 4,
        "IdProposition": 3,
        "Time" : 9
        }
    ]
}

I'm trying to make let list with NSDictionnary which look like :
[[Time: 30, IdQuestion: 6510, idProposition: 10], [Time: 30, IdQuestion: 8284, idProposition: 10]]

and my request using Alamofire looks like :
Alamofire.request(.POST, "http://myserver.com", parameters: ["IdQuiz":"102","IdUser":"iOSclient","User":"iOSClient","List":list ], encoding: .JSON)
            .response { request, response, data, error in
            let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
                println(dataString)
        }

The request has an error and I believe the problem is with Dictionary list, cause if I make a request without the list it works fine, so any idea ?

I have tried the solution suggested but I'm facing the same problem :
 let json = ["List":list,"IdQuiz":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]
        let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted,error:nil)
        let jsons = NSString(data: data!, encoding: NSUTF8StringEncoding)

    Alamofire.request(.POST, "http://myserver.com", parameters: [:], encoding: .Custom({
        (convertible, params) in
        var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
        mutableRequest.HTTPBody = jsons!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        return (mutableRequest, nil)
    }))
        .response { request, response, data, error in
        let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
           println(dataString)
    }

A: Xcode 8.X , Swift 3.X
Easy Use;
    let params:NSMutableDictionary? = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
        [
            "IdQuestion" : 5,
            "IdProposition": 2,
            "Time" : 32
        ],
        [
            "IdQuestion" : 4,
            "IdProposition": 3,
            "Time" : 9
        ]
    ]
];
            let ulr =  NSURL(string:"http://myserver.com" as String)
            let request = NSMutableURLRequest(url: ulr! as URL)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)

            let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
            if let json = json {
                print(json)
            }
            request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);

            Alamofire.request(request as! URLRequestConvertible)
                .responseJSON { response in
                    // do whatever you want here
                   print(response.request)
                   print(response.response)
                   print(response.data)
                   print(response.result)

            }

A: I don't like any of the other answers so far (except perhaps the one by SwiftDeveloper), because they either require you to deserialize your JSON, only for it to be serialized again, or care about the structure of the JSON itself.
The correct answer has been posted by afrodev in another question. You should go and upvote it.
Below is just my adaption, with some minor changes (primarily explicit UTF-8 charset).
let urlString = "https://example.org/some/api"
let json = "{\"What\":\"Ever\"}"

let url = URL(string: urlString)!
let jsonData = json.data(using: .utf8, allowLossyConversion: false)!

var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData

Alamofire.request(request).responseJSON {
    (response) in

    print(response)
}

A: I've slightly edited SwiftDeveloper's answer, because it wasn't working for me. I added Alamofire validation as well.
let body: NSMutableDictionary? = [
    "name": "\(nameLabel.text!)",
    "phone": "\(phoneLabel.text!))"]

let url = NSURL(string: "http://server.com" as String)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: body!, options: JSONSerialization.WritingOptions.prettyPrinted)

let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
    print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
let alamoRequest = Alamofire.request(request as URLRequestConvertible)
alamoRequest.validate(statusCode: 200..<300)
alamoRequest.responseString { response in

    switch response.result {
        case .success:
            ...
        case .failure(let error):
            ...
    }
}

A: Alamofire 5.5 and Swift 5
func postRequest() {
  let parameters: [String : Any] = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
      [
        "IdQuestion" : 5,
        "IdProposition": 2,
        "Time" : 32
      ],
      [
        "IdQuestion" : 4,
        "IdProposition": 3,
        "Time": 9
      ]
    ]
  ]

  let url = URL(string: "http://myserver.com/api/post")!
  AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
    .validate()
    .responseJSON { response in
      switch response.result {
      case .success(let response):
        print(response)
      case .failure(let error):
        print(error.localizedDescription)
      }
  }
}

A: There are few changes I would like to notify. You can access request, JSON, error from response object from now on.
        let urlstring = "Add URL String here"
        let parameters: [String: AnyObject] = [
            "IdQuiz" : 102,
            "IdUser" : "iosclient",
            "User" : "iosclient",
            "List": [
                [
                    "IdQuestion" : 5,
                    "IdProposition": 2,
                    "Time" : 32
                ],
                [
                    "IdQuestion" : 4,
                    "IdProposition": 3,
                    "Time" : 9
                ]
            ]
        ]

        Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
            response.result.error
        }

A:
Alamofire Fetch data with POST,Parameter and Headers

func feedbackApi(){
    DispatchQueue.main.async {
        let headers = [
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "------"
        ]
        let url = URL(string: "---------")
        var parameters = [String:AnyObject]()
        parameters =  [
            "device_id":"-----" as AnyObject,
            "user_id":"----" as AnyObject,
            "cinema_id":"-----" as AnyObject,
            "session_id":"-----" as AnyObject,
        ]
       Alamofire.request(url!, method: .post, parameters: parameters,headers:headers).responseJSON { response in
                switch response.result{
                case.success(let data):
                    self.myResponse = JSON(data)
                    print(self.myResponse as Any)
                    let slide = self.myResponse!["sliders"]
                    print(slide)
                    print(slide.count)
                    for i in 0..<slide.count{
                        let single = Sliders(sliderJson: slide[i])
                        self.slidersArray.append(single)
                    }
                    DispatchQueue.main.async {
                        self.getSliderCollection.reloadData()
                    }
                case .failure(let error):
                    print("dddd",error)
                }

        }
    }

}

A: If you are using Alamofire v4.0+ then the accepted answer would look like this:
let parameters: [String: Any] = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
        [
            "IdQuestion" : 5,
            "IdProposition": 2,
            "Time" : 32
        ],
        [
            "IdQuestion" : 4,
            "IdProposition": 3,
            "Time" : 9
        ]
    ]
]

Alamofire.request("http://myserver.com", method: .post, parameters: parameters, encoding: JSONEncoding.default)
    .responseJSON { response in
        print(response)
    }

A: Accepted answer in
Xcode 11 - Swift 5 - Alamofire 5.0
func postRequest() {
    let parameters: [String: Any] = [
        "IdQuiz" : 102,
        "IdUser" : "iosclient",
        "User" : "iosclient",
        "List": [
            [
                "IdQuestion" : 5,
                "IdProposition": 2,
                "Time" : 32
            ],
            [
                "IdQuestion" : 4,
                "IdProposition": 3,
                "Time" : 9
            ]
        ]
    ]
    AF.request("http://myserver.com", method:.post, parameters: parameters,encoding: JSONEncoding.default) .responseJSON { (response) in
        print(response)
    }
}

A: If you are using swift4 and Alamofire v4.0 then the accepted code would look like this :
            let parameters: Parameters = [ "username" : email.text!, "password" : password.text! ]
            let urlString = "https://api.harridev.com/api/v1/login"
            let url = URL.init(string: urlString)
            Alamofire.request(url!, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
                 switch response.result
                {
                case .success(let json):
                    let jsonData = json as! Any
                    print(jsonData)
                case .failure(let error):
                    self.errorFailer(error: error)
                }
            }

A: You're close. The parameters dictionary formatting doesn't look correct. You should try the following:
let parameters: [String: AnyObject] = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
        [
            "IdQuestion" : 5,
            "IdProposition": 2,
            "Time" : 32
        ],
        [
            "IdQuestion" : 4,
            "IdProposition": 3,
            "Time" : 9
        ]
    ]
]

Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
    .responseJSON { request, response, JSON, error in
        print(response)
        print(JSON)
        print(error)
    }

Hopefully that fixed your issue. If it doesn't, please reply and I'll adjust my answer accordingly.

A: Here is how I created Http POST request with swift that needs parameters with Json encoding and with headers.
Created API Client
BKCAPIClient as a shared instance which will include all types of requests such as POST, GET, PUT, DELETE etc.
func postRequest(url:String, params:Parameters?, headers:HTTPHeaders?, completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void){
    Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON {
        response in
        guard response.result.isSuccess,
            (response.result.value != nil) else {
                debugPrint("Error while fetching data: \(String(describing: response.result.error))")
                completion(nil,response.result.error)
                return
        }
        completion(response.result,nil)
    }
}

Created Operation class that contains all data needed for particular request and also contains parsing logic inside completion block.
func requestAccountOperation(completion: @escaping ( (_ result:Any?, _ error:Error?) -> Void)){
    BKCApiClient.shared.postRequest(url: BKCConstants().bkcUrl, params: self.parametrs(), headers: self.headers()) { (result, error) in
        if(error != nil){
            //Parse and save to DB/Singletons.
        }
        completion(result, error)
    }
}
func parametrs()->Parameters{
    return ["userid":"xnmtyrdx","bcode":"HDF"] as Parameters
}
func headers()->HTTPHeaders{
    return ["Authorization": "Basic bXl1c2VyOm15cGFzcw",
            "Content-Type": "application/json"] as HTTPHeaders
}

Call API In any View Controller where we need this data
func callToAPIOperation(){
let accOperation: AccountRequestOperation = AccountRequestOperation()
accOperation.requestAccountOperation{(result, error) in

}}

A: If anyone wondering how to proceed with models and stuff, see below
        var itemArr: [Dictionary<String, String>] = []
        for model in models {
              let object = ["param1": model.param1,
                            "param2": model.param2]
              itemArr.append(object as! [String : String])
        }

        let param = ["field1": someValue,
                     "field2": someValue,
                     "field3": itemArr] as [String : Any]

        let url: URLConvertible = "http://------"

        Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default)
            .responseJSON { response in
                self.isLoading = false
                switch response.result {
                case .success:
                    break
                case .failure:
                    break
                }
        }

A: func get_Contact_list()
{
    ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading..")
    let cont_nunber = contact_array as NSArray
    print(cont_nunber)

    let token = UserDefaults.standard.string(forKey: "vAuthToken")!
    let apiToken = "Bearer \(token)"

    let headers = [
        "Vauthtoken": apiToken,
        "content-type": "application/json"
    ]

    let myArray: [Any] = cont_nunber as! [Any]
    let jsonData: Data? = try? JSONSerialization.data(withJSONObject: myArray, options: .prettyPrinted)
    //        var jsonString: String = nil
    var jsonString = String()
    if let aData = jsonData {
        jsonString = String(data: aData, encoding: .utf8)!
    }

    let url1 = "URL"
    var request = URLRequest(url: URL(string: url1)!)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = jsonData as! Data

    //        let session = URLSession.shared

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
            return
        }

        print("response = \(String(describing: response))")

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")

        let json =  self.convertStringToDictionary(text: responseString!)! as NSDictionary
        print(json)

        let status = json.value(forKey: "status") as! Int

        if status == 200
        {

            let array = (json.value(forKey: "data") as! NSArray).mutableCopy() as! NSMutableArray

        }
        else if status == 401
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUD()

        }
        else
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
        }

    }
    task.resume()
}

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

A: Alamofire ~5.2 and Swift 5
You can structure your parameter data
Work with fake json api
struct Parameter: Encodable {
     let token: String = "xxxxxxxxxx"
     let data: Dictionary = [
        "id": "personNickname",
        "email": "internetEmail",
        "gender": "personGender",
     ]
}

 let parameters = Parameter()

 AF.request("https://app.fakejson.com/q", method: .post, parameters: parameters).responseJSON { response in
            print(response)
        }


text:
Q: UIView gradient does not change on second save I'm creating a preview from something that people can configure in settings. They can choose a color in settings.
My view hierarchy:

*

*Settings (Choose color for tree, and preview tree)

*Choose color for tree (Here the user can choose for colors of the tree, with a save button)

I have an unwindSegue for my save button, that calls the setupCell method. But the background gradient layer of my UIView does not want to change.
Code:
- (IBAction)setupCellSegue:(UIStoryboardSegue *)segue{
    [self setupCell];
}

-(void)setupCell{
    //Corners
    self.Preview.layer.cornerRadius = 25;
    self.Preview.layer.masksToBounds = YES;

    //Background
    self.Preview.backgroundColor = [UIColor clearColor];

    CAGradientLayer *grad = [CAGradientLayer layer];

    grad.frame = self.Preview.bounds;
    grad.colors = [[[Kleuren sharedInstance] kleurenArray] objectForKey:[standardDefaults objectForKey:@"Kleur"]];

    [self.Preview.layer insertSublayer:grad atIndex:0];

    //Text
    self.optionOutlet.textColor = [Kleuren.sharedInstance.tekstKleurenArray objectForKey:[standardDefaults objectForKey:@"TekstKleur"]];
}

EDIT:
Here is the NSLog from my sublayers from the view. How can i replace the old CAGradientLayer with the new one? Tried this:
[self.Preview.layer replaceSublayer:0 with:grad];

(
    "<CAGradientLayer: 0xcce9eb0>",
    "<CALayer: 0xccef760>"
)

EDIT 2:
After trying some more, i've noticed that the CAGradientLayer is just added and added on top? Maybe this is the problem?
(
    "<CAGradientLayer: 0x170220100>",
    "<CAGradientLayer: 0x170220e20>",
    "<CAGradientLayer: 0x170029f40>",
    "<CALayer: 0x17803d960>"
)

EDIT 3:
View hierarchy, so the View that is highlighted in the screenshot is the one with the background.

EDIT 4:
Tried this: but now it doesn't have a CALayer anymore:
[[self.Preview layer] replaceSublayer:[[[self.Preview layer] sublayers] objectAtIndex:0] with:grad];

So I would get the following error:
2014-07-08 18:57:18.365 ///[3324:60b] View hierarchy unprepared for constraint.
    Constraint: <NSIBPrototypingLayoutConstraint:0xe88e0b0 'IB auto generated at build time for view with fixed frame' UILabel:0xe88dae0.left == UIView:0xe88da50.left + 20>
    Container hierarchy:
<UIView: 0xe88da50; frame = (59 54; 202 202); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0xe88dab0>>
   | <CAGradientLayer: 0xe88cd50> (layer)
    View not found in container hierarchy: <UILabel: 0xe88dae0; frame = (20 20; 162 162); text = 'Option'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0xe88db90>>
    That view's superview: NO SUPERVIEW

So it seems to be that because the CALayer is deleted, the UILabel gives this error because it doesn't have a superview.

A: Try adding
 [self.Preview.layer setNeedsDisplay];

after setupCell. This should redraw the layer

A: Not immediately sure what your issue is.
The first thing that jumped out at me is that in your first EDIT, you misused replaceSublayer:with:. See the documentation for that method for details, but basically you used an integer literal when you need to pass a CALayer - I'm surprised the compiler didn't complain. The declaration of that method is:
- (void)replaceSublayer:(CALayer *)oldLayer with:(CALayer *)newLayer

To use this method correctly, you'll want to hold onto a reference to the gradient layer. Maybe make a new property called grad and store it there. Later, when you want to replace it, pass self.grad into replaceSublayer:with: as oldLayer.
After you've fixed that, here are some things to check:

*

*Are you sure setupCell gets called when you think it does? Set a breakpoint there to check.

*Are you sure that when you recalculate the gradient layer, the colors have changed? Use a breakpoint to examine the value of grad.colors each time you pass through setupCell.

A: Found it, I've placed my CAGradientLayer *grad; in my implementation declaration between the {}
By placing the declaration in my implementation of my class. I could re-use the declaration, and not making a new instance each time by putting it in the setupCell.
@implementation class {
   CAGradientLayer *grad
}

-(void)setupCell{
   // Do stuff here with the gradient layer.
}

I do not know that this is the right explanation but it works. Was the last thing I came up on!


text:
Q: How to create compressed archive split into multiple files while low on space I'm to backup 7GB on 9GB drive. Means, I have about 2GB of empty space only.
But tar related solutions require first - get everything into 1 file, next - split it.
Is there any possibility to archive (and probably but not necessarily compress) and split, to have an ability to transfer to a remote drive chunk by chunk.
I mean

*

*while 1st file is ready, I'm to move it to an external drive and delete from the system.

*when  2nd file is ready, I'm to move ....

A: Break it into multiple archives at source.
Use du to discover some of the largest directories and archive/compress these first (use tar | gzip or a direct tar compression option). Copy that .tgz file to a remote drive, check the size, then remove from your main disc.
Repeat for other large directories until you you have archived maybe 5GB.
Finally, archive and compress the base directory but use the exclude option in tar to name the directories already archived.
Alternatively, you can tar and gzip through pipes, and then pipe into  ssh to write it to your remote drive. Something like (check options):
tar cfz - myBaseDir | ssh myRemote 'cat > myArchive.tg z'

A: As far as I know, there is no one-liner for that. But I've written a small bash script, which put all files into several tar packages.
#!/bin/bash

package_i=1
all_files=$(find . -name "*" -type f)

# stop on every 100 MB for now
max_size=104857600

for f in $all_files; do
        #
        # add file to current tar file
        #
        tar -rvf package${package_i}.tar $f

        #
        # check if the size is more than 100 MB
        # if so, then wait till current package tar
        # was moved by user to another storage
        # and then proceed
        #
        size_of_current_package=$(stat --printf="%s" package${package_i}.tar)
        if [ $size_of_current_package -ge $max_size ]; then
                read -p "Will wait when you moved package${package_i}.tar to another storage ..."
                package_i=$(( $package_i + 1 ))
                echo "=== Package iterator is now '${package_i}' ==="
        fi
done

The script adds file for file into the current packageX.tar file (package1.tar, package2.tar, etc.). If that packageX.tar file exceeds some amount of bytes (in this example this amount is 100MB or 104857600 Bytes), then it will wait till the user copied the packageX.tar file to another storage and proceed after the user hit Enter.


text:
Q: How to remove automatic numbering of figure in LaTex? I would like the caption of my figure to be "Figure A". Is there a way to remove the automatic numbering of the figures?
\documentclass[jou]{apa7}
\usepackage{graphicx}
\begin{document}

\begin{figure}
\renewcommand{\figurename}{Figure A}
\centering
 \caption{Title}
\includegraphics[width=0.5\textwidth]{test.png}
\end{figure}

\end{document}

With the code above, the caption is "Figure A 1".
Thank you in advance!

A: Two quick hacks, either you can temporarily remove the number or you can latex do the numbering with capital letters:
\documentclass[jou]{apa7}
\usepackage{graphicx}

\begin{document}

\begin{figure}
\renewcommand{\figurename}{Figure A}
\renewcommand{\thefigure}{}
\centering
\caption{Title}
\includegraphics[width=0.5\textwidth]{example-image-duck}
\end{figure}

\begin{figure}
\renewcommand{\thefigure}{\Alph{figure}}
\centering
\caption{Title}
\includegraphics[width=0.5\textwidth]{example-image-duck}
\end{figure}

\end{document}


text:
Q: True or false: $n^2 + 2n^2 + 3n^2 + 4n^2 + ... n(n^2)$ is $O(n^2)$ I believe it is false, but having trouble coming up with the contradiction. My solution so far:
Suppose by contradiction $n^2 + 2n^2 + 3n^2 + 4n^2 +  ... n(n^2)$  is $O(n^2)$, then there exists c > 0 and $n_0 \ge 1$ such that $n^2 + 2n^2 + 3n^2 + 4n^2 +  ... n(n^2) < c n^2$
$n^2 + 2n^2 + 3n^2 + 4n^2 + 5n^2 ... n(n^2) = n^2(1 + 2 + 3 + 4 .. + n) \le cn^2$
$n^2\sum_{i=1}^n i = n^2(n(n+1)/2) \le cn^2$
$(n(n+1)/2) \le c$
$n^2 + n \le 2c $
Not sure where to go from here!

A: The last term in your sum is $n^3$, which is not $O(n^2)$.  Adding positive numbers cannot reduce the order so you could be done here.  In fact the whole sum is $\frac 12n(n+1)n^2=\frac 12(n^4+n^3)$ so it is $O(n^4)$

A: You have reached the point of $n^2+n \le 2C$ for a constant $C$ which is not possible because $n^2+n$ grows without bound.
Thus your proof is complete.


text:
Q: Change JSON String I have a JSON string I want to change it.
The JSON string looks like
string '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]' (length=114)

I want to convert this JSON to
string '[{"id":"AT02708872"},{"id":"DE60232348"}]' (length=114)

So I want to remove the dots and the last letter. I am using Symfony2 (PHP)
Anyone has any idea how can I do it.
Thanks

A: Decode, modify, re-encode.
<?php

$json = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]';

// Decode the JSON data into an array of objects.
// Symfony probably will have some JSON handling methods so you could look at
// those to keep the code more Symfony friendly.
$array = json_decode($json);

// Loop through the array of objects so you can modify the ID of
// each object. Note the '&'. This is calling $object by reference so
// any changes within the loop will persist in the original array $array
foreach ($array as &$object)
{
    // Here we are stripping the periods (.) from the ID and then removing the last
    // character with substr()
    $object->id = substr(str_replace('.', '', $object->id), 0, -1);
}

// We can now encode $array back into JSON format
$json = json_encode($array);

var_dump($json);

There is probably native JSON handling within Symfony2 so you may want to check that out.

A: You can use javascript regular expression to replace the unwanted elements with blank string. You should, however, do this before you parse the string to php object.

A: Is it one string?  Run a regular expression on it:
<?
   $str =  '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]' ;
   echo preg_replace('/\.[A-Z]"/','"',$str);
?>

This is assuming that all your id's end in . 1 capital letter.

A: $json = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]';

$json = json_decode($json, true);

$result = array();
foreach($json as $item) {
    $tmp = explode('.', $item['id']);
    $result[] = array('id' => $tmp[0] . $tmp[1]);
}

$result = json_encode($result);
echo $result;


text:
Q: Concat 2 columns in pandas - AttributeError: 'DataFrame' object has no attribute 'concat' I am trying to concat along 2 columns in pandas. The code :
import pandas as pd
import numpy as np
from statsmodels import api as sm
import pandas_datareader.data as web
import datetime

start = datetime.datetime(2015,2,12)
end = datetime.datetime.today()
df = web.get_data_yahoo(['F', '^GSPC'], start, end)

df1 = df.concat(columns=[F['Close'], gspc['Close']], axis=1)

But i am getting the following error:
AttributeError: 'DataFrame' object has no attribute 'concat'

A: You need to use pd.concat([df1, df2]), because df.concat() doesn't exist.
I'll make you an example:
import pandas as pd

df1 = pd.DataFrame(zip(list('bcdfg'), list('aeiou')), columns=['consonants', 'vowels'])
df2 = pd.DataFrame(range(5), columns=['numbers'])

  consonants vowels
0          b      a
1          c      e
2          d      i
3          f      o
4          g      u

   numbers
0        0
1        1
2        2
3        3
4        4

pd.concat([df1, df2], axis=1)

  consonants vowels  numbers
0          b      a        0
1          c      e        1
2          d      i        2
3          f      o        3
4          g      u        4


text:
Q: What can i do to use httpclient method in android studio. I am using HttpClient and defaultHttpClient Methods in getInternetData function on android studi. but these methods are no longer part of the SDK 23. how can i overcome this problem.i have used dependencies in build.gradle too , but still error remains here. Kindly tell me are there any other methods to call.?
public class GetMethodEx {
public String getInternetData() throws Exception{
    BufferedReader in = null;
    String data = null;
    try{
        HttpClient client = new DefaultHttpClient();
        URI website = new URI("http://api.twitter.com/1/statuses/public_timeline.json");
        HttpGet request = new HttpGet();
        request.setURI(website);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");
        while ((l = in.readLine()) !=null){
            sb.append(l + nl);
        }
        in.close();
        data = sb.toString();
        return data;
    }finally{
        if (in != null){
            try{
                in.close();
                return data;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

}


text:
Q: Scheduling a controller to run every one hour in Kubernetes I have a console application which does some operations when run and I generate an image of it using docker. Now, I would like to deploy it to Kubernetes and run it every hour, is it possible that I could do it in K8?
I have read about Cron jobs but that's being offered only from version 1.4

A: The short answer. Sure, you can do it with a CronJob and yes it does create a Pod. You can configure Job History Limits to control how many failed, completed pods you want to keep before Kubernetes deletes them.
Note that CronJob is a subset of the Job resource.


text:
Q: Way to expose appstore IDs but keep them secured for release I am working on an application that will allow the user to purchase content from the app store
https://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008267-CH1-SW1
These products require a "ProductID" that ties them to whatever is in the appstore.
I will need to store these IDs somewhere in the application so I know what to send the server when the purchase button is clicked.
I wish to expose these ID's and allow non-programmers to enter any ID they want in both our side and the server side, and not have to call on a programmer to go into the code and change some enum.
I figured a config file would not be very secure, for in the end it's just a text file that a user could potentially view after purchasing the app. May not be a huge problem if a user saw the ID, but I don't like the idea of anybody seeing the innards that go through a payment process
Assuming im making sense here, whats a good way to expose these IDs but still keep them secure so users may not find them?
Also curious, how secure is something like an enum in c++? Can people break the .exe down and see the code and its values?

A: For your final question, yes and no. If they have access to the debugging information (a PDB in Microsoft land) then yes. But armed with just an exe and disassembler, you will see only the constant values that are assigned to the enum members.