text:
Q: No 'Access-Control-Allow-Origin' error with Spring RESTful hosted in Pivotal web services I create a RESTful API with Spring boot and host it in Pivotal web services.
Let's say the url is https://abc.cfapps.io/students and the json result will be
[

       {"id":1,"name":"Michael","score":8.5},
       {"id":2,"name":"Naomi","score":5.6}
]

Then I write an Angular client to send a request to that url:
angular.module("app", []).controller("listController", function($scope, $http)
{
    var url = 'https://abc.cfapps.io/students';
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', url, true);
    httpRequest.setRequestHeader('Access-Control-Allow-Origin', '*');
    httpRequest.setRequestHeader('Content-Type', 'application/json');
    httpRequest.onerror = function (XMLHttpRequest, textStatus, errorThrown) {
        console.log('failed');
        console.log(JSON.stringify(XMLHttpRequest));
    };
    httpRequest.onload = function () {
        console.log('SUCCESS!');
    }
    httpRequest.send();
});

My client run in localhost:52442 and in my Spring boot service I also allow CORS, too.
@RestController
@CrossOrigin(origins = "http://localhost:52442")
@RequestMapping(value="/students")
public class StudentService
{

    @RequestMapping(value="/",method = RequestMethod.GET)
    public ArrayList<Student> getListStudents()
    {
        // return list
    }

// other methods
}

But I keep getting this error:
XMLHttpRequest cannot load https://abc.cfapps.io/students.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:52442' is therefore not allowed access. The response had HTTP status code 403.

A: If your using the java code at backend
We can try to configure it in this way by creating a class for it
   package com.web;

   import org.springframework.stereotype.Component;

   import javax.servlet.*;
   import javax.servlet.http.HttpServletResponse;
   import java.io.IOException;

/**
 * Note this is a very simple CORS filter that is wide open.
 * This would need to be locked down.
 */
@Component
public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

I think this might be useful

A: Try the below format of $http GET call with header's set to allow cross origin
    $http({method: 'GET',
           url: 'https://abc.cfapps.io/students',
           cache:false,
           headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
                'X-Random-Shit':'123123123'
            }})
            .success(function(outputData) {
    });

A: import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements  Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        String origin = "";
        if(request.getHeader("origin") != null){
            origin = request.getHeader("origin");
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        if(origin.isEmpty()){
            response.setHeader("Access-Control-Allow-Origin", "*");
        }

        response.setHeader("Access-Control-Allow-Credentials", "true");
        //TRACE
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, PATCH, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http.cors()
                .and()
                .requestMatchers()
                    .antMatchers("/version", "/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().permitAll();
    }

    //.....
}


text:
Q: syntax error or access violation 1064 pdo in a query mysql I receive via URL a string which is an INSERT or DELETE query. Once received, I have to insert data in the mysql database.
The url is something like this:

www.mysite.com/page.php?query=INSERT INTO orders (IDCliente, IDOrdine, DTOrdine) VALUES ('0569', 2593, '19-09-2018')

My simple script:
include_once('../config/database.php');
include_once('../config/core.php');

$id=isset($_GET['query']) ? $_GET['query'] : die('ERROR: Empty string');

$id = '"'.$_GET['query'].'"';

try {

    $stmt = $con->prepare($id);

    if($stmt->execute()){

        header('Location: index.php');
    } else {
        die('Unable to delete record.');
    } catch(PDOException $exception) {
        die('ERROR: ' . $exception->getMessage());
    }
}

Now, if I use
 $stmt = $con->prepare($id)

I get an

ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;

but if I use the query straight into the prepare statement
  $stmt = $con->prepare("INSERT INTO orders (IDCliente, IDOrdine, DTOrdine) VALUES ('0569', 2593, '19-09-2018')");

in this way, works!
I have checked the double quote (added into the $id = '"'.$_GET['query'].'"';) and everything seems ok.I also tried the query into phpmyadmin and is correct
I'm trying to learn PDO, thanks for the patience.
Note: For all, I explain. This query with data comes ONLY from a business software. No user can use it, and there's no other way to interface it with the website.

A: first implement an api , not this spaggeti.
secound try this :
include_once('../config/database.php');
include_once('../config/core.php');

$id=isset($_GET['query']) ? $_GET['query'] : die('ERROR: Empty string');

try {

    $stmt = $con->prepare($id);

    if($stmt->execute()){

        header('Location: index.php');
    }else{
        die('Unable to delete record.');
    }

    }   catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: 2D arrays in Random Forest fitting and scoring I'm trying to fit a Random Forest regression model. This are the steps I've followed (pls see code below with comments):

*

*Before fitting the model, I've splitted into training and test

*I've converted the results into arrays

*I've reshaped them to 2D arrays as the regressor likes them to be using the reshape function

I'm getting the following error (it seems that there is a 1D array even though I've reshaped them at the beginning):
ValueError: Expected 2D array, got 1D array instead:
array=[183.  27. 520. ...  23.  28.  34.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or
array.reshape(1, -1) if it contains a single sample.

Here's the code I've used:
#train & test split
X = order_final.loc[:, ~order_final.columns.isin(['lag','observed'])]
y = order_final['lag']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

#convert X,y train and X test into arrays
X_train = X_train.to_numpy()
y_train = y_train.to_numpy()
X_test = X_test.to_numpy()

#make them 2D-arrays
X_train.reshape(-1,1)
y_train.reshape(-1,1)
X_test.reshape(-1,1)

# Fitting Random Forest Regression to the dataset
# import the regressor
from sklearn.ensemble import RandomForestRegressor

# create regressor object
RF = RandomForestRegressor(n_estimators = 100, random_state = 0)

# fit the regressor with x and y data
RF.fit(X_train, y_train)

#Prediction of test set
y_pred = RF.predict(X_test)

# View accuracy score
RF.score(y_test, y_pred)

And here is the shape of my arrays (which look goods to me but...):
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
print(y_pred.shape)

(7326, 10)
(7326,)
(1832, 10)
(1832,)
(1832,)
Can Someone pls help me out and point me where the error is? Thanks in advance!
Stefano

A: RF.score() needs the inputs to be reshaped:
RF.score(y_test.reshape(-1,1), y_pred.reshape(-1,1))

A: You need to pass the inputs used for making your predictions to the score() method instead, like so:
RF.score(X_test, y_test)


text:
Q: How to find Select Option text start with I have a select box like below,
<select id="fruit">
    <option value="0">--select--</option>
    <option value="1">apple</option>
    <option value="2">pineapple</option>
    <option value="3">orange</option>
<select>

I need to check any of its text start with "p" something like this
 if(jQuery('#fruit option[text^="p"]').length){
  //  something to do
    }

I know if its value we can get something like,
if(jQuery('#fruit option[value^="p"]').length){
      //  something to do
        }

But for text its not working. Im not getting what I missed here also checked through out the forum not find any thing close to this.
Thanks in advance..

A: You can use  filter() for that
$("#fruit option").filter(function() { return $(this).text().indexOf("p") === 0; })

Fiddle Demo
Edit
Updated demo with case sensitive filtering


text:
Q: Branched manifolds and bounding tori for chaotic attractors In $3$-dimensions, chaotic attractors can be classified by there bounding torus (1) or there branched manifold (2).
Assuming that the chaotic attractor is generated by a dynamical system:
$\dot{\mathbf{x}}=F(\mathbf{x})$
My question is the following: Given the bounding torus/branched manifold of a chaotic attractor, is there a way to deduce the functional form of the vector field $F$ or at least restrict it? Or are there counterexamples showing that something like this is not possible?
(E.g., I am looking for results of the form: Given the branched manifold of the attractor has form ..., the nonlinearities of $F$ can only be to degree 2,3,4,... .)


text:
Q: What should the voltage of a fully charged lead acid battery be? I don't have a proper lead acid battery charger...  But I own a small Yuasa 7Ah battery.  I am using a 13volt 1.5A wall wart to charge it.  And I have a volt-meter to check the voltage.
At what voltage should I take the battery off the charger?

A: See my stack exchange answer to "Lead Acid Battery Charger Design Factors" which relates, and follow the link there to the Battery University site which will tell you far more than you knew there was to know about lead acid (and other) batteries.
From the above answer note the quotes from the above website. Especially in this context

*

*The correct setting of the charge voltage is critical and
ranges from 2.30 to 2.45V per cell.
Setting the voltage threshold is a compromise, and battery experts refer to this as "dancing on the head of a needle."
On one hand, the battery wants to be fully charged to get maximum capacity and avoid sulfation on the negative plate; on the other hand, an over-saturated condition causes grid corrosion on the positive plate and induces gassing.
To make "dancing on the head of a needle" more difficult, the battery voltage shifts with temperature. Warmer surroundings require slightly lower voltage thresholds and a cold ambient prefers a higher level.
2.30 x 6 = 13.8V
2.45 x 6 = 14.7V
13.8V is the nominal voltage that many automobile systems operate at.
 14.7V is higher than you'd usually meet but around 14.4V is common for "topping" mode charging which is used to equalise charge in series connected cells. See the Battery University site for MUCH more information.
If you charge to only 12.6V as several people have recommended your battery will not ever be at full capacity and will have a shortened life.
See also Safe operating area for different types of battery chemistry?
And also Can I charge a 12v sealed lead acid with an old wall-wart (not made for charging)?
And also Charging lead-acid batteries?

A: Deep Cycle Batteries charge on 3 stages: bulk charge, topping and float charge. During the bulk charge,  the current density (A/cm² or A/dm²) is very important. If the current is smaller than  needed for the surface of electrodes, crystalline structure will appear. Sponge material is reversible, but crystalline material is irreversible and this is very important  for PbSO₄ too.
After the battery gets charged to 80%,  then the current decreases and during float charge is less than 1 Ampere.
The best choice is using a Smart Charger. The way a battery is  used and maintained can  change the battery life from  6 months to 7 years.  Never let a discharged battery rest uncharged;  discharging the battery at 50% before recharging can prolong the battery life by 2 to 3 times.

A: When in the armed forces, and frequently abroad for between 2 weeks and 6 months, which ruined car batteries, I purchased a variable voltage transformer (5 amp). Ensured battery fully charged (negligible charge indicated on ammeter when running engine)Connected trickle charger and voltmeter to battery, plugged charger into output from variable transformer. Then wound transformer voltage down until voltmeter indicated approx. 12.6/12.9 volts( I.E. slightly lower than ideal?). Was away nearly 5 months. Quick check: power still on and voltage not changed; electrolyte level appeared unchanged. Unplugged everything, hand pumped fuel up to the carbs. Engine started , battery seemed not to have aged and ammeter was very quickly showing normal fully charged indication while engine was running. May not be theoretically sound or perfect but proved very effective. Never had a problem using that system: it paid for the transformer, and my car was always ready to go (after I had checked tyre pressures).


text:
Q: Size-of struct with uneven 8bit members is not uneven Good evening!
'Got the following problem: I have an input stream of multi- and single-byte datatypes and just want to lay it over a struct. Unfortunately, if I put an uneven amount of 8bit members in a struct together with 16bit members, the sizeof() function will give me the round up to an even length.
Following example:
Datatypes:
struct uuu { // should contain 5 bytes
    uint8_t a[1];
    uint8_t b[1];
    uint16_t c;
    char d[1];
};
struct ccc { // should contain 5 bytes
    char a;
    char b;
    char c;
    uint16_t d;
};
struct bbb { // should contain 3 bytes
    char a;
    char b;
    char c;
};

Snippet:
printf("char_bit: %d\n", CHAR_BIT);
printf("%d | %d | %d", sizeof(uuu), sizeof(ccc), sizeof(bbb));

Result:
char_bit: 8
6 | 6 | 3

The point is, I need an exact order of 8bit member to parse the stream into the predefined struct. Is there a way to force this? Working on a 64bit machine, tried already compiling with the -m32 gcc flag.
I know it has to do with paddings of struct etc. But is there a workaround to still achieve the fixed structure sizes?
Thanks in advance!

A: If you use the packed attribute, your structs will not contain padding.
struct __attribute__((packed)) uuu { // will now contain 5 bytes


text:
Q: How to return the view from controller in laravel in this case My question is how should I connect the things to return the view?
All of the time got an error like this:
MethodNotAllowedHttpException in RouteCollection.php line 251
Below you can check where I am:
web.php
Route::post('registered', 'AuthController@store_view')->name('registration.registered');

AuthController.php
public function store_view(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required|min:5'
    ]);

    $name = $request->input('name');
    $email = $request->input('email');
    $password = $request->input('password');

    $user = new User([
        'name' => $name,
        'email' => $email,
        'password' => bcrypt($password)
    ]);

    if ($user->save()) {
        $user->signin = [
            'href' => 'api/v1/user/signin',
            'method' => 'POST',
            'params' => 'email, password'
        ];
        $response = [
            'msg' => 'User created',
            'user' => $user
        ];
        return view('registration.registered')->with('response',$response);
    }

    $response = [
        'msg' => 'An error occurred'
    ];

    return view('registration.registered')->with('response',$response);
}

register.blade.php

                     Register to continue!

                    <form role="form" action="{{-- {{ url('/api/v1/user') }} --}}" method="POST">
                    {{ csrf_field() }}
                        <fieldset>

                                            <input class="form-control" placeholder="Username" name="name" type="text" autofocus>

                                            <input class="form-control" placeholder="E-mail" name="email" type="text">

                                            <input class="form-control" placeholder="Password" name="password" type="password">

                                        <input type="submit" class="btn btn-lg btn-primary btn-block" value="Register">

                        </fieldset>
                    </form>

                    Already have an account?  Sign In Here!

A: In your form use this, the form action attribute must be the name of you route:
<form role="form" action="{{route('registration.registered')}}"


text:
Q: Unable to locate package google-drive-ocamlfuse , suddenly stopped working I have been using colab lately and till now I used google-drive-ocamlfuse to link my project to my drive but not it is unable to load package.
!apt-get update -qq 2>&1 > /dev/null
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!add-apt-repository ppa:alessandro-strada/google-drive-ocamlfuse-beta
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

got referenced form here
https://medium.com/@burakteke/tutorial-on-using-google-colab-for-kaggle-competition-620393c22821
till yesterday it was working like a charm but today it suddenly stopped working.

A: This should work fine as per https://github.com/astrada/google-drive-ocamlfuse/issues/493#issuecomment-422380636
Change the build between amd64, arm64, armhf, i386 from https://launchpad.net/~alessandro-strada/+archive/ubuntu/ppa/+packages
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!wget https://launchpad.net/~alessandro-strada/+archive/ubuntu/google-drive-ocamlfuse-beta/+build/15331130/+files/google-drive-ocamlfuse_0.7.0-0ubuntu1_amd64.deb
!dpkg -i google-drive-ocamlfuse_0.7.0-0ubuntu1_amd64.deb
!apt-get install -f
!apt-get -y install -qq fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

A: An even simpler fix is to use the built-in Drive FUSE client:
from google.colab import drive
drive.mount('/content/gdrive')

More details:
https://colab.research.google.com/notebooks/io.ipynb#scrollTo=u22w3BFiOveA


text:
Q: Find all degree solutions in the interval $0^\circ \leq \theta < 360^\circ$. Find all degree solutions in the interval $0^\circ \leq \theta < 360^\circ$. If rounding is necessary, round to the nearest tenth of a degree.
$$5\sin^2 \theta − 6\cos2θ= 0$$
My work: http://i.imgur.com/p5Go7G3.jpg

A: Note that $\cos(2\theta) = 1 - 2\sin^2(\theta)$
You might find this useful.

A: Picking up from were you left off, we have
$$\cos^2\theta=\frac{11}{17}$$
Hence
$$\cos\theta=\pm\sqrt{\frac{11}{17}}$$
Noting that $\left|\pm\sqrt{\frac{11}{17}}\right|<1$, we know that there are $2$ solutions for $\cos\theta=\sqrt{\frac{11}{17}}$ and $2$ solutions for $\cos\theta=-\sqrt{\frac{11}{17}}$ in the interval $[0^\circ,360^\circ)$. Recalling that $\cos\theta=\cos(360^\circ-\theta)$ and that the $\cos^{-1}$ function has range $[0,180^\circ]$, we have that our $4$ solutions are:
$$\cos^{-1}\left(\sqrt{\frac{11}{17}}\right),\hspace{5mm}\cos^{-1}\left(-\sqrt{\frac{11}{17}}\right),\hspace{5mm}360^\circ-\cos^{-1}\left(\sqrt{\frac{11}{17}}\right),\hspace{5mm}360^\circ-\cos^{-1}\left(-\sqrt{\frac{11}{17}}\right)$$


text:
Q: What made people think the Anti-Kaiju Wall would work? What are the in-universe reasons for the initial faith in the Anti-Kaiju Wall?
This question has bothered me ever since I saw the film many months ago.  I realise that it's a spectacle / monster-mecha slash, and I am usually very quick to gloss over holes, but this one really stuck with me for my complete inability to comprehend it.
If I understand correctly, support for the wall rested on these items:

*

*No Kaiju would attack a wall bordering the coastline.[1]  The film doesn't seem to give an explanation for why this is considered a viable assumption.  While there may be some merit in observing that wild creatures don't attack walls, it feels too flimsy to build a population's survival on.

*Building and maintaining the wall would cost less than maintaining a fleet of Jaeger.  Building a Jaeger is costly, in the order of a hundred billion dollars[2], but I hesitate to think of the cost of a wall that shields off, at a minimum, every mile of populated coast bordering the Pacific.

*The Jaegers wouldn't last forever.[3]  Recent setbacks/losses among the Jaeger led people to think of an alternative for the long term.

However, the drawbacks seem grave enough to sink the plan immediately:

*

*What happens when the wall is breached?  Is there a contingency plan?

*It's hard to overstate just how much coast borders the Pacific; tens of thousands of kilometers.

*Seeing the wall in the film left me intensely skeptical that it would stop creatures of the size mentioned.  Kaiju could probably have just climbed over.[4]

*I recall turrets being mounted on the wall, but pre-Jaeger history taught that kaiju required up to several nuclear strikes to kill.  What are we going to load into those turrets?

Obviously, with the benefit of hindsight, it didn't work out.  What I'm curious about is what made the Pacific Alliance sign off on the idea as a replacement for the Jaeger?  What did they realistically expect the wall to accomplish?  Are there in-universe reasons or benefits that I have overlooked or am unaware of?
Note: I've only seen the film, not read any novels, but any canon, in-universe reasons will do.

*

*Anti-Kaiju Wall — Wiki Pacific Rim:
"The assumption that no Kaiju would attack a wall bordering the coastline was the primary backing for the idea behind supporting the wall over the Jaeger Program."

*Jaeger — Wiki Pacific Rim:
"Unfortunately, the development of the Jaeger program has not come cheaply. The cost of building the Mark-5 Jaeger Striker Eureka, for example, was reputed to be over a hundred billion dollars, more than ten times the cost of a nuclear aircraft carrier."

*Anti-Kaiju Wall — Wiki Pacific Rim:
"The belief that the Jaeger Program would benefit the world in the long run was thought to be a hypothesis without a strong basis."

*Film snippet: "Breaking News: [...] Alliance in support of the Wall of Life program clearly stated that the constructions would withstand [...] highest category [...]"

A: The logic behind seems to be pure propaganda, as it fails to meet the most basic of examinations.
Based on the novelization, the idea that the Kaiju would not attack the walls seems to hinge solely on the fact that until the events of the movie, they have not. It seems, however, that the real driving force behind the propaganda for the wall are financial.
From a press release in the novelization:

17 April 2020
For Immediate Release
United Nations to Sunset Jaeger Program; Pan-Pacific Defense Priorities Shift To Coastal Defense, Resettlement
Effective immediately, the United Nations Subcommittee on Kaiju Defense and Security, Pan-Pacific Breach Working Group, is reassigning funding from the Jaeger Program.
The costs of the Jaeger Program have proven unsustainable in view of the limited returns the program offers. In the last three years we have spent trillions on Jaegers. A number of those Jaegers have been destroyed and losses to life and property are devastating.
It could be argued, and has ably been argued by Marshal Pentecost, that our situation would be much worse were it not for the Jaegers. Perhaps so. Yet this is a hypothetical argument, and we are faced with the real-world problem of bankrupting the economies of the developed nations to continue a program whose successes -- however notable -- no longer justify an outlay.
We will sunset the Jaeger program in an manner that continues to prioritize  the safety and security of the people of the Pacific Rim nations. While we do this, we will redirect funding toward the following initiatives:
Coastal Barriers

*

*No kaiju has attacked a currently standing Wall. The building of these fortifications is the simplest and most cost-effective tool humanity to combat the kaiju threat.
Evacuation and Resettlement Programs

*

*Citizens of Pacific coastal cities will be receiving further information as new housing is constructed farther inland, prioritized according to progress on the Wall.

  Completion of Undersea Barriers In The South Pacific

*

*The kaiju must be contained at all costs, and under no circumstances will they be allowed to break out of the Pacific and threaten Europe, India, or the East Coast of the Americas.

*The working Group's members wish to thank Marshal Pentecost, his rangers, and the entire staff of the Jaeger program for their courageous service.


text:
Q: How can I pass table data into a function using a PostgresSQL composite type? I am tying to pass data into a function using a composite type. However, I can't see how to call the function. Consider the following code:
drop table if exists ids cascade;
create table ids
(
    id bigint primary key
);

drop table if exists data;
create table data
(
    id   bigint generated always as identity primary key references ids(id) deferrable initially deferred,
    name text
);

drop type if exists raw_type cascade;
create type raw_type as (name text);
create table raw2 of raw_type;

insert into raw2(name)
values ('test1'),
       ('test2'),
       ('test3'),
       ('test4'),
       ('test5'),
       ('test6'),
       ('test7')
;

create or replace function special_insert(data_to_insert raw_type) returns void as
    $func$
    begin
    with x as (insert into data(name) select name from data_to_insert returning id)
    insert into ids(id)
    select id from x;
    end;
$func$ language plpgsql;

Running this:
begin transaction ;
select special_insert(raw2);
commit ;

I get the following error:
ERROR: column "raw2" does not exist

Running this:
begin transaction ;
select special_insert(name::raw_type) from raw2;
commit ;

I get
[2019-04-10 15:41:18] [22P02] ERROR: malformed record literal: "test1"
[2019-04-10 15:41:18] Detail: Missing left parenthesis.

What am I doing wrong?

A: The second function call is correct, however there is a bug in your function definition.
You make the mistake of treating data_to_insert as a table, but it is a single value. Use the following notation to get an individual field from a composite type:
INSERT INTO data (name)
VALUES (data_to_insert.name)
RETURNING id


text:
Q: relational PostgreSQL database from tab delimited Trying to create a relational database from a healthcare related tsv in PostgreSQL. I created a database and created the 3 tables I need and that worked, so now I have three tables that I need to import the relevant data into.
I primarily work in Python, so I'm not great at SQL. I tried importing the entire text file just to see if it worked. It said it completed but when I use SELECT * FROM on any of the tables they're all blank.
So I then tried breaking up the tsv into the relevant columns of each table and saving them as csvs and importing them that way. That also didn't work.
I've tried googling around but have had no luck. I am on a mac if it matters.
Any help is greatly appreciated!


text:
Q: Java Tomcat Project in eclipse We can create a Java Tomcat Project in eclipse. As per my knowledge its a Java project with a WAR structure. I have searched a lot on web but did not get any satisfactory answer.
I want to know what is the need of Tomcat Project when Dynamic Web Project is there?
Are they different in project hierarchy only or there is any other difference?
Is it specific to Apache Tomcat i.e. can't be deployed on any other server like JBoss?
Thanks.


text:
Q: Tooltips not showing on mouse move and mouse over I am using the below code to create a multi line chart with tool tips and have customized it a little bit to make the x axis ordinal and I have also har coded the data. Everything else seems to be working fine except for the tool tips.
https://bl.ocks.org/larsenmtl/e3b8b7c2ca4787f77d78f58d41c3da91
The tool tips dont show up when I hover over the data points and I am also trying to make the x axis discrete meaning I wish to  see the tool tips for the data I have in the data variable and not for the x values in between.
could someone please advise ?
Below is my code:

    <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
      <style>
        body {
          font: 10px sans-serif;
        }

        .axis path,
        .axis line {
          fill: none;
          stroke: #000;
          shape-rendering: crispEdges;
        }

        .line {
          fill: none;
          stroke: steelblue;
          stroke-width: 1.5px;
        }
      </style>
    </head>

    <body>
      <script>

        var margin = {
            top: 20,
            right: 80,
            bottom: 30,
            left: 50
          },
          width = 900 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

    //    var parseDate = d3.time.format("%Y%m%d").parse;

    //    var x = d3.scale.linear()
    //      .range([0, width]);
        var x  = d3.scale.ordinal()
        .domain(["20170101","20170108","20170115","20170122","20170128"])
        .rangePoints([0, width],0.5);

        var y = d3.scale.linear()
          .range([height, 0]);

        var color = d3.scale.category10();

        var xAxis = d3.svg.axis()
          .scale(x)
    //      .ticks(5)
          .orient("bottom")
    //      .tickValues(["2017-01-01", "2017-01-08", "2017-01-15", "2017-01-22", "2017-01-28"]);

        var yAxis = d3.svg.axis()
          .scale(y)
          .orient("left");

        var line = d3.svg.line()
          .interpolate("linear")
          .x(function(d) {
            return x(d.week);
          })
          .y(function(d) {
            return y(d.avg_test_drives);
          });

        var svg = d3.select("body").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    //    var data = d3.tsv.parse(myData);
    //      console.log(data[0]);
    //      alert (JSON.stringify(data));

        var data =  [{"week": "20170101", "dealer": "68", "peers": "73","all dealers":"123"},
                     {"week": "20170108", "dealer": "121","peers":"112","all dealers":"131"},
                     {"week": "20170115", "dealer": "104","peers":"101","all dealers":"106"},
                     {"week": "20170122", "dealer": "123","peers":"131","all dealers":"122"},
                     {"week": "20170128", "dealer": "106","peers":"107","all dealers":"122"}]
    //    alert (JSON.stringify(data));

        color.domain(d3.keys(data[0]).filter(function(key) {
          return key !== "week";
        }));

        data.forEach(function(d) {
          d.week = d.week;
        });

        var testdrives = color.domain().map(function(name) {
          return {
            name: name,
            values: data.map(function(d) {
              return {
                week: d.week,
                avg_test_drives: +d[name]
              };
            })
          };
        });

    //    x.domain(d3.extent(data, function(d) {
    //      return d.week;
    //    }));

        y.domain([
          d3.min(testdrives, function(c) {
            return d3.min(c.values, function(v) {
              return v.avg_test_drives;
            });
          }),
          d3.max(testdrives, function(c) {
            return d3.max(c.values, function(v) {
              return v.avg_test_drives;
            });
          })
        ]);

        var legend = svg.selectAll('g')
          .data(testdrives)
          .enter()
          .append('g')
          .attr('class', 'legend');

        legend.append('rect')
          .attr('x', width - 20)
          .attr('y', function(d, i) {
            return i * 20;
          })
          .attr('width', 10)
          .attr('height', 10)
          .style('fill', function(d) {
            return color(d.name);
          });

        legend.append('text')
          .attr('x', width - 8)
          .attr('y', function(d, i) {
            return (i * 20) + 9;
          })
          .text(function(d) {
            return d.name;
          });

        svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis)
    //      .ticks(5);

        svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
          .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Test Drives");

        var entity = svg.selectAll(".entity")
          .data(testdrives)
          .enter().append("g")
          .attr("class", "entity");
    //    alert (JSON.stringify(entity));

        entity.append("path")
          .attr("class", "line")
          .attr("d", function(d) {
            return line(d.values);
          })
          .style("stroke", function(d) {
            return color(d.name);
          });

        entity.append("text")
          .datum(function(d) {
            return {
              name: d.week,
              value: d.values[d.values.length - 1]
            };
          })
          .attr("transform", function(d) {
            return "translate(" + x(d.value.week) + "," + y(d.value.avg_test_drives) + ")";
          })
          .attr("x", 3)
          .attr("dy", ".35em")
          .text(function(d) {
            return d.week;
          });

        var mouseG = svg.append("g")
          .attr("class", "mouse-over-effects");

        mouseG.append("path") // this is the black vertical line to follow mouse
          .attr("class", "mouse-line")
          .style("stroke", "black")
          .style("stroke-width", "1px")
          .style("opacity", "0");

        var lines = document.getElementsByClassName('line');

        var mousePerLine = mouseG.selectAll('.mouse-per-line')
          .data(testdrives)
          .enter()
          .append("g")
          .attr("class", "mouse-per-line");

        mousePerLine.append("circle")
          .attr("r", 7)
          .style("stroke", function(d) {
            return color(d.week);
          })
          .style("fill", "none")
          .style("stroke-width", "1px")
          .style("opacity", "0");

        mousePerLine.append("text")
          .attr("transform", "translate(10,3)");

        mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
          .attr('width', width) // can't catch mouse events on a g element
          .attr('height', height)
          .attr('fill', 'none')
          .attr('pointer-events', 'all')
          .on('mouseout', function() { // on mouse out hide line, circles and text
            d3.select(".mouse-line")
              .style("opacity", "0");
            d3.selectAll(".mouse-per-line circle")
              .style("opacity", "0");
            d3.selectAll(".mouse-per-line text")
              .style("opacity", "0");
          })

          .on('mouseover', function() { // on mouse in show line, circles and text
            d3.select(".mouse-line")
              .style("opacity", "1");
            d3.selectAll(".mouse-per-line circle")
              .style("opacity", "1");
            d3.selectAll(".mouse-per-line text")
              .style("opacity", "1");
          })

          .on('mousemove', function() { // mouse moving over canvas
            var mouse = d3.mouse(this);
            d3.select(".mouse-line")
              .attr("d", function() {
                var d = "M" + mouse[0] + "," + height;
                d += " " + mouse[0] + "," + 0;
                return d;

              });

           d3.selectAll(".mouse-per-line")
              .attr("transform", function(d, i) {
                console.log(width/mouse[0])
                var xDate = x.invert(mouse[0]),
                    bisect = d3.bisector(function(d) { return d.week; }).right;
                    idx = bisect(d.values, xDate);

                var beginning = 0,
                    end = lines[i].getTotalLength(),
                    target = null;

                while (true){
                  target = Math.floor((beginning + end) / 2);
                  pos = lines[i].getPointAtLength(target);
                  if ((target === end || target === beginning) && pos.x !== mouse[0]) {
                      break;
                  }
                  if (pos.x > mouse[0])      end = target;
                  else if (pos.x < mouse[0]) beginning = target;
                  else break; //position found
                }

                d3.select(this).select('text')
                  .text(y.invert(pos.y).toFixed(2));

                return "translate(" + mouse[0] + "," + pos.y +")";
              });
          });

      </script>
    </body>

A: You was trying to access function invert() of x, however since it is not linear() but ordinal() now, it is not possible to invert it, and function invert() is missing for x  = d3.scale.ordinal(), thus trying to call this function was causing an error and blocking the execution of the next lines of code, so just comment out:
 var xDate = x.invert(mouse[0]),
                    bisect = d3.bisector(function(d) { return d.week; }).right;
                    idx = bisect(d.values, xDate);

in  d3.selectAll(".mouse-per-line") and here you go, tooltip is working again:

    <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>

      <style>
        body {
          font: 10px sans-serif;
        }

        .axis path,
        .axis line {
          fill: none;
          stroke: #000;
          shape-rendering: crispEdges;
        }

        .line {
          fill: none;
          stroke: steelblue;
          stroke-width: 1.5px;
        }
      </style>
    </head>

    <body>
      <script>

        var margin = {
            top: 20,
            right: 80,
            bottom: 30,
            left: 50
          },
          width = 900 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

    //    var parseDate = d3.time.format("%Y%m%d").parse;

    //    var x = d3.scale.linear()
    //      .range([0, width]);
        var x  = d3.scale.ordinal()
        .domain(["20170101","20170108","20170115","20170122","20170128"])
        .rangePoints([0, width],0.5);

        var y = d3.scale.linear()
          .range([height, 0]);

        var color = d3.scale.category10();

        var xAxis = d3.svg.axis()
          .scale(x)
    //      .ticks(5)
          .orient("bottom")
    //      .tickValues(["2017-01-01", "2017-01-08", "2017-01-15", "2017-01-22", "2017-01-28"]);

        var yAxis = d3.svg.axis()
          .scale(y)
          .orient("left");

        var line = d3.svg.line()
          .interpolate("linear")
          .x(function(d) {
            return x(d.week);
          })
          .y(function(d) {
            return y(d.avg_test_drives);
          });

        var svg = d3.select("body").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    //    var data = d3.tsv.parse(myData);
    //      console.log(data[0]);
    //      alert (JSON.stringify(data));

        var data =  [{"week": "20170101", "dealer": "68", "peers": "73","all dealers":"123"},
                     {"week": "20170108", "dealer": "121","peers":"112","all dealers":"131"},
                     {"week": "20170115", "dealer": "104","peers":"101","all dealers":"106"},
                     {"week": "20170122", "dealer": "123","peers":"131","all dealers":"122"},
                     {"week": "20170128", "dealer": "106","peers":"107","all dealers":"122"}]
    //    alert (JSON.stringify(data));

        color.domain(d3.keys(data[0]).filter(function(key) {
          return key !== "week";
        }));

        data.forEach(function(d) {
          d.week = d.week;
        });

        var testdrives = color.domain().map(function(name) {
          return {
            name: name,
            values: data.map(function(d) {
              return {
                week: d.week,
                avg_test_drives: +d[name]
              };
            })
          };
        });

    //    x.domain(d3.extent(data, function(d) {
    //      return d.week;
    //    }));

        y.domain([
          d3.min(testdrives, function(c) {
            return d3.min(c.values, function(v) {
              return v.avg_test_drives;
            });
          }),
          d3.max(testdrives, function(c) {
            return d3.max(c.values, function(v) {
              return v.avg_test_drives;
            });
          })
        ]);

        var legend = svg.selectAll('g')
          .data(testdrives)
          .enter()
          .append('g')
          .attr('class', 'legend');

        legend.append('rect')
          .attr('x', width - 20)
          .attr('y', function(d, i) {
            return i * 20;
          })
          .attr('width', 10)
          .attr('height', 10)
          .style('fill', function(d) {
            return color(d.name);
          });

        legend.append('text')
          .attr('x', width - 8)
          .attr('y', function(d, i) {
            return (i * 20) + 9;
          })
          .text(function(d) {
            return d.name;
          });

        svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis)
    //      .ticks(5);

        svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
          .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Test Drives");

        var entity = svg.selectAll(".entity")
          .data(testdrives)
          .enter().append("g")
          .attr("class", "entity");
    //    alert (JSON.stringify(entity));

        entity.append("path")
          .attr("class", "line")
          .attr("d", function(d) {
            return line(d.values);
          })
          .style("stroke", function(d) {
            return color(d.name);
          });

        entity.append("text")
          .datum(function(d) {
            return {
              name: d.week,
              value: d.values[d.values.length - 1]
            };
          })
          .attr("transform", function(d) {
            return "translate(" + x(d.value.week) + "," + y(d.value.avg_test_drives) + ")";
          })
          .attr("x", 3)
          .attr("dy", ".35em")
          .text(function(d) {
            return d.week;
          });

        var mouseG = svg.append("g")
          .attr("class", "mouse-over-effects");

        mouseG.append("path") // this is the black vertical line to follow mouse
          .attr("class", "mouse-line")
          .style("stroke", "black")
          .style("stroke-width", "1px")
          .style("opacity", "0");

        var lines = document.getElementsByClassName('line');

        var mousePerLine = mouseG.selectAll('.mouse-per-line')
          .data(testdrives)
          .enter()
          .append("g")
          .attr("class", "mouse-per-line");

        mousePerLine.append("circle")
          .attr("r", 7)
          .style("stroke", function(d) {
            return color(d.week);
          })
          .style("fill", "none")
          .style("stroke-width", "1px")
          .style("opacity", "0");

        mousePerLine.append("text")
          .attr("transform", "translate(10,3)");

        mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
          .attr('width', width) // can't catch mouse events on a g element
          .attr('height', height)
          .attr('fill', 'none')
          .attr('pointer-events', 'all')
          .on('mouseout', function() { // on mouse out hide line, circles and text
            d3.select(".mouse-line")
              .style("opacity", "0");
            d3.selectAll(".mouse-per-line circle")
              .style("opacity", "0");
            d3.selectAll(".mouse-per-line text")
              .style("opacity", "0");
          })

          .on('mouseover', function() { // on mouse in show line, circles and text
            d3.select(".mouse-line")
              .style("opacity", "1");
            d3.selectAll(".mouse-per-line circle")
              .style("opacity", "1");
            d3.selectAll(".mouse-per-line text")
              .style("opacity", "1");
          })

          .on('mousemove', function() { // mouse moving over canvas
            var mouse = d3.mouse(this);
            d3.select(".mouse-line")
              .attr("d", function() {
                var d = "M" + mouse[0] + "," + height;
                d += " " + mouse[0] + "," + 0;
                return d;

              });

           d3.selectAll(".mouse-per-line")
              .attr("transform", function(d, i) {
                console.log(width/mouse[0])
               /* var xDate = x.invert(mouse[0]),
                    bisect = d3.bisector(function(d) { return d.week; }).right;
                    idx = bisect(d.values, xDate);
                */
                var beginning = 0,
                    end = lines[i].getTotalLength(),
                    target = null;

                while (true){
                  target = Math.floor((beginning + end) / 2);
                  pos = lines[i].getPointAtLength(target);
                  if ((target === end || target === beginning) && pos.x !== mouse[0]) {
                      break;
                  }
                  if (pos.x > mouse[0])      end = target;
                  else if (pos.x < mouse[0]) beginning = target;
                  else break; //position found
                }

                d3.select(this).select('text')
                  .text(y.invert(pos.y).toFixed(2));

                return "translate(" + mouse[0] + "," + pos.y +")";
              });
          });

      </script>
    </body>


text:
Q: saving changes in fedora live usb I recently installed Fedora 12 on my USB drive. But I am not able to save the changes I do in a live session.  I created 2 users and put some icons in desktop... But after I restarted Fedora from the live usb, the changes could not be seen.
Can anybody suggest what to do to save the changes?

A:
I recently installed fedora 12 on my
  USB drive

Did you install or copy the Live CD ISO onto the flash disk ? Seems like you copied the live CD ISO onto the flash disk than installed it.
You need to create a Live USB with persistence mode, have a look at this article for instructions on how to do so.


text: Q: Similar to beta regression for Generalized Additive Models and Generalized Linear Models My thesis is based on GAM and GLM. But my dependent variable is a proportion, meaning that $y \in (0,1)$ then I thought a better fit for this was the beta regression but this one is not considered in the GLM. What other distribution can I use for this dependent variable? I used the normal with the link function identity and log but I need another one to make a comparison.


text:
Q: R object name to string using shortcut reference I would like a function that can take an object name and convert it to a string in R.
but I would like to be able to call the object name using shorthand typing or other shortcuts like in for loops etc.
the purpose is so I can automatically assign graph and figure names from the objects that create them
I've tryed deparse(substitute()) but it dosnt seem to work when i use the shortcut list method to refer to a object.
this is how id like the function to operate
>all_mydata<-list(i_want_this_text_to_return_as_string=c(1,2,3,4),second_list=c("a","b","c"))
>object_name_as_string<-function(all_mydata[[1]])
>object_name_as_string
i_want_this_text_to_return_as_string

A: The function I was looking for was names
> names(all_mydata)[1]
[1] "i_want_this_text_to_return_as_string"


text:
Q: Can not refactor in Visual Studio 2012 I can not access the refactoring menu, my code compiles and runs, and I can't use the shortcut; it says that the refactoring  extract method is not available at this time and I do not have the right click option nor the top menu.
Any thoughts?


text:
Q: Using "for" loop in r with a table I have the following database
library(data.table)
dt <- data.table(prod= c("AAAA","BBBB","CCCC"),
                 version= c(4,3,5))

And I want to obtain this
AAAA1
AAAA2
AAAA3
AAAA4
BBBB1
BBBB2
BBBB3
CCCC1
CCCC2
CCCC3
CCCC4
CCCC5

Now I have the following code, but it only works for the AAAA but not for the rest
list <- c()

for(i in 1:dt$version){

  list[[i]] <- paste0(dt$prod,i)

}

A: A base R option using rep + sequence + paste0
> with(dt,paste0(rep(prod,version),sequence(version)))
 [1] "AAAA1" "AAAA2" "AAAA3" "AAAA4" "BBBB1" "BBBB2" "BBBB3" "CCCC1" "CCCC2"
[10] "CCCC3" "CCCC4" "CCCC5"

or mapply + paste0 + seq
> with(dt, unlist(mapply(function(x,y) paste0(x,seq(y)), prod,version)))
  AAAA1   AAAA2   AAAA3   AAAA4   BBBB1   BBBB2   BBBB3   CCCC1   CCCC2   CCCC3
"AAAA1" "AAAA2" "AAAA3" "AAAA4" "BBBB1" "BBBB2" "BBBB3" "CCCC1" "CCCC2" "CCCC3"
  CCCC4   CCCC5
"CCCC4" "CCCC5"

A: Using uncount
library(dplyr)
library(tidyr)
library(stringr)
dt %>%
   uncount(version) %>%
   mutate(prod = str_c(prod, rowid(prod)))

-output
#    prod
# 1: AAAA1
# 2: AAAA2
# 3: AAAA3
# 4: AAAA4
# 5: BBBB1
# 6: BBBB2
# 7: BBBB3
# 8: CCCC1
# 9: CCCC2
#10: CCCC3
#11: CCCC4
#12: CCCC5

Or with rep
dt[rep(seq_len(.N), version)][, prod := paste0(prod, rowid(prod))][]

A: Another way to do it is by using the Map and sprintf functions (from base) as follows
library(data.table)

dt <- data.table(prod = c("AAAA","BBBB","CCCC"),
                 version = c(4,3,5))

dt[, .(result = unlist(
         Map(f = function(x, y) sprintf("%s%d", x, seq(from = 1, to = y)),
             prod, version)
       ))]
#     result
#  1:  AAAA1
#  2:  AAAA2
#  3:  AAAA3
#  4:  AAAA4
#  5:  BBBB1
#  6:  BBBB2
#  7:  BBBB3
#  8:  CCCC1
#  9:  CCCC2
# 10:  CCCC3
# 11:  CCCC4
# 12:  CCCC5

Alternatively
with(dt, c(
         Map(f = function(x, y) sprintf("%s%d", x, seq(from = 1, to = y)),
             prod, version),
         recursive = TRUE, use.names = FALSE
       ))
#  [1] "AAAA1" "AAAA2" "AAAA3" "AAAA4" "BBBB1" "BBBB2" "BBBB3" "CCCC1" "CCCC2"
# [10] "CCCC3" "CCCC4" "CCCC5"

A: A dplyr option :
library(dplyr)

dt %>%
  slice(rep(row_number(), version)) %>%
  group_by(prod) %>%
  mutate(prod = paste0(prod, row_number())) %>%
  select(-version)

#   prod
#   <chr>
# 1 AAAA1
# 2 AAAA2
# 3 AAAA3
# 4 AAAA4
# 5 BBBB1
# 6 BBBB2
# 7 BBBB3
# 8 CCCC1
# 9 CCCC2
#10 CCCC3
#11 CCCC4
#12 CCCC5


text:
Q: Laptop freezes with power when trying to suspend or hibernate (Ubuntu 18.04) I am a Linux newbie, I researched my issue quite a bit in the last few weeks but have not managed to solve it.
When I try to suspend my laptop, either by pressing the power button or closing the lid, most of the times it will freeze:

*

*Power led remains on

*Screen off.

*Nothing happens when typing or clicking mouse buttons.

The only option in this state is hard shutdown (long press power button).
This happens most of the times I tried to suspend.
I discovered that when clicking the "pause" icon in the lock screen, suspend mode does work as expected, but not always (sometimes it freezes).
I also ran pm-suspend. It, too, results in the same freeze state, but it produces a crash report in /var/crash. The file is quite long so I'm not copying it into the question. From what I can tell, the file doesn't indicate any specific issues that I can focus on. pm-hibernate also crashes, in the same way.
The only piece of nonstandard hardware on this laptop is a cellular modem, which doesn't ship in the standard version.
Any help would be appreciated.

*

*Laptop: Dell Latitude 5590

*Processor: Intel(R) Core i7-8650U

*Graphics: Intel(R) UHD Graphics 620 (Kabylake GT2)

*Kernel: 5.4.5-050405-generic (upgraded by me using UKUU)

A: This was a hardware issue. After replacing the motherboard (under warranty) the issue is gone. Hopefully this might help someone with similar issues - sometimes the OS and bundled software is not at fault.


text:
Q: Clustering based on euclidean distance in mysql I have a big innodb table with arrays of data (saved as binary). The table is indexed only by timestamp.
I do query in batches (mysql ss cursor), and for every batch I convert arrays to floats and calculate euclidean distance like this:
numpy.linalg.norm(y-x, axis=1)
Where y is the array that I'm using to find closest to.
And x is list of arrays from mysql.
It works fine except it's slow for long queires. So I'm asking some advice how can I select only arrays which are closest to the target array and cut very different from the query. I suppose I should compute some value for each array in parsing time and save it along with the array, so then my query should look like:
SELECT row_id, array WHERE array_value BETWEEN N AND F; (indexed by array_value)
I suppose the query should give me similar (but not preciesly) arrays and after that I can compute exact distance as I did before with numpy.linalg.norm
Thanks for any advice.

A: Is your "array" 3 elements long?  Namely (x,y,z)?  Let's call that a "POINT".
Is "closest" measured by Euclidean distance?
The simplest algorithm is to check the distance to every Point.  This is time-consuming.  The next best is to build a "bounding box" around the target Point.  That is, see if there are any points that match this, and if so, which is the closest:
xi - eps < x < xi + eps AND
yi - eps < y < yi + eps AND
zi - eps < z < zi + eps

If you find no Points, increase eps and try again.  (So, it is best to pick eps so that you are likely to find an answer on the first try, but not so big that you don't save much time relative to scanning all Points.)
Given that that is a restatement of your problem, but closer to what MySQL understands, then...
CREATE TABLE points (
    id ...,
    ts TIMESTAMP ...,   -- since you mentioned this
    x INT ...,   -- Or maybe FLOAT?
    y ...,
    z ...,
    PRIMARY KEY(id),
    INDEX(timestamp),
    INDEX(x,y,z)
) ENGINE=InnoDB;

Then the query is something like
SET @x = 11, @y = 22, @z = 33;  -- the target "point"
SET @eps = 5;
SELECT  *,
        SQRT( (x - @x) * (x - @x) +
              (y - @y) * (y - @y)
              (z - @z) * (z - @z) ) AS distance
    FROM points
    WHERE  x BETWEEN @x - @eps AND @x + @eps
      AND  y BETWEEN @y - @eps AND @y + @eps
      AND  z BETWEEN @z - @eps AND @z + @eps
ORDER BY distance
LIMIT 1   -- assuming you want only the closest.

More discussion here .
Not useful
While what I said above is useful in some contexts, it does not scale beyond 2 or 3 dimensions.  I would expect it to be essentially useless for 128 dimensions.


text:
Q: Deepdive installation, PostgreSQL error Does anyone have any experience working with DeepDive? It involves installing Java, Python 2.x, PostgreSQL, and SBT, then the DeepDive package. I'm not very familiar with PostgreSQL, but I'm intending to learn these simultaneously.
I'm working on Ubuntu 12.04 and PostgreSQL 9.1. I made a superuser for PostgreSQL using the command in the shell createuser tom. It's worth noting that my Ubuntu username is also tom. I then changed the password for tom with the following:
$su - postgres
$psql
--> ALTER USER tom WITH password 'pa$$w0RD';

DeepDive comes with a test script, which gives me the following error (I'm not including all the other text, which doesn't include errors).
[info] LogisticRegressionApp:
[info] - should work *** FAILED ***
[info]   org.postgresql.util.PSQLException: FATAL: password authentication failed for user "tom"
[info]   at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:398)
[info]   at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:173)
[info]   at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
[info]   at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:136)
[info]   at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
[info]   at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
[info]   at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
[info]   at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
[info]   at org.postgresql.Driver.makeConnection(Driver.java:393)
[info]   at org.postgresql.Driver.connect(Driver.java:267)
[info]   ...

Then at the end:
[info] Tests: succeeded 68, failed 2, canceled 0, ignored 0, pending 3
[info] *** 2 TESTS FAILED ***
[error] Failed tests:
[error]     org.deepdive.test.integration.LogisticRegressionApp
[error]     org.deepdive.test.unit.InferenceManagerSpec
[error] Error during tests:
[error]     org.deepdive.test.unit.PostgresInferenceDataStoreSpec
[error]     org.deepdive.test.unit.PostgresExtractionDataStoreSpec
[error] (test:test) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 10 s, completed Mar 17, 2014 8:51:47 PM

If anyone can point me in some direction, I'd appreciate it.

OK, I fixed part of the problem, but this led to a different problem. Here's what I did. test.sh contains the following lines:
export PGUSER=${PGUSER:-`whoami`}
export PGPASSWORD=${PGPASSWORD:-}

which I changed to
export PGUSER=tom
export PGPASSWORD=pa$$w0rd

Now the test proceeds farther, and gets to the point where it prints the following:
06:49:40.953 [default-dispatcher-7][$a][LocalActorRef] INFO  Message [org.deepdive.calibration.CalibrationDataWriter$WriteCalibrationData] from Actor[akka://deepdive/temp/$a] to Actor[akka://deepdive/user/inferenceManager/$a#-1669803870] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
06:49:40.955 [default-dispatcher-7][$a][LocalActorRef] INFO  Message [akka.actor.PoisonPill$] from Actor[akka://deepdive/user/inferenceManager#-354953956] to Actor[akka://deepdive/user/inferenceManager/$a#-1669803870] was not delivered. [2] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
06:49:40.957 [default-dispatcher-5][inferenceManager][InferenceManager$PostgresInferenceManager] INFO  Starting
06:49:40.958 [default-dispatcher-6][factorGraphBuilder][FactorGraphBuilder$PostgresFactorGraphBuilder] INFO  Starting
06:50:06.679 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$d][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:06.699 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$e][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:06.709 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$f][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:06.738 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$g][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:06.759 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$h][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:06.780 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$i][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:06.799 [TaskManagerSpec-scheduler-1][akka://TaskManagerSpec/user/$$j][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)
06:50:07.396 [default-dispatcher-5][taskManager][TaskManager] INFO  Memory usage: 233/982MB (max: 982MB)

And this continues ad infinitum. The key seems to be the first line, about the message not being delivered between the two Actors.
As I noted in a comment below, I checked out the postgresql.conf file, and uncommented the following line
listen_addresses = 'localhost'
listen on;

It resolved one of the original errors, but not the second error.
In item 2 of Patrick's response, here are the parameters from the pg_hba.conf file:
# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

Doesn't the part local  all  all support all local connections?

A: The error you mention can have multiple causes:

*

*Have you modified postgresql.conf to accept incoming TCP/IP connections? Check the listen_addresses parameter.

*Have you modified pg_hba.conf? Here you need setup an authentication method for DeepDive and/or the jdbc driver definition.

*Lastly, can DeepDive connect to the database it intends to connect to with the credentials you have supplied it (or the jdbc driver definition)?
Both of the configuration files are in your $PGDATA directory, typically /etc/postgresql/9.3/main.
Note that psql logs on using the unix sockets by default (unless you specify -h host_ip) and jdbc uses a TCP/IP connection. Try psql over TCP/IP to see if that works. If not, work on 1, then 2. If it does, work on 2, then 3.


text:
Q: How to create typing indicator with tkinter? I have made a real live chatroom in Python with tkinter.
I want to know how to create a typing indicator without using firebase. What I mean by this is that say, one of of the user's name is bob, and if bob is typing a message I want it to say to the other users that bob is typing... and I want it, if possible, to appear over the type message box.
Edit:
I added this in:
def var_changed(self):
   self.label.config(text=msg+"is typing")

my_msg = tkinter.StringVar()
my_msg.trace = ("w", var_changed)
entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.pack()

but it all it is doing is copying what i'm writing instead of saying user typing a message
Server.py
import socket, threading

host = socket.gethostname()
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
clients = {}
addresses = {}
print(host)
print("Server is ready...")
serverRunning = True

def handle_client(conn):
    try:
        data = conn.recv(1024).decode('utf8')
        welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % data
        conn.send(bytes(welcome, "utf8"))
        msg = "%s has joined the chat" % data
        broadcast(bytes(msg, "utf8"))
        clients[conn] = data
        while True:
            found = False
            response = 'Number of People Online\n'
            msg1 = conn.recv(1024)

            if msg1 != bytes("{quit}", "utf8"):
                broadcast(msg1, data+": ")
            else:
                conn.send(bytes("{quit}", "utf8"))
                conn.close()
                del clients[conn]
                broadcast(bytes("%s has left the chat." % data, "utf8"))
                break
    except:
        print("%s has left the chat." % data)

def broadcast(msg, prefix=""):
    for sock in clients:
        sock.send(bytes(prefix, "utf8")+msg)

while True:
    conn,addr = s.accept()
    conn.send("Enter username: ".encode("utf8"))
    print("%s:%s has connected." % addr)
    addresses[conn] = addr
    threading.Thread(target = handle_client, args = (conn,)).start()

Client.py
import socket,threading,tkinter

host = input("Enter server name: ")
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host,port)

def echo_data(sock):
   while True:
      try:
         msg = sock.recv(1024).decode('utf8')
         msg_list.insert(tkinter.END, msg)
      except OSError:
         break

def send(event=None):
   msg = my_msg.get()
   my_msg.set("")
   s.send(bytes(msg, "utf8"))
   if msg == "{quit}":
      s.close()
      top.quit()

def on_closing(event=None):
    my_msg.set("{quit}")
    send()

top = tkinter.Tk()
top.title("Chat Room")

messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=15, width=100, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()

entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()

top.protocol("WM_DELETE_WINDOW", on_closing)

address = (host,port)
s.connect(address)

threading.Thread(target=echo_data, args = (s,)).start()

tkinter.mainloop()

A:
Question: create typing indicator for tkinter.Entry widget

*

*Define Application class inherited from tk.Tk, for demonstration only.
import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()

*Init a Flag .is_typing, to know typing was detected
        self.is_typing = False

*Create a Entry as common
        self.my_msg = tk.StringVar()
        entry_field = tk.Entry(self, textvariable=self.my_msg)
        entry_field.grid(row=0, column=0)

*Bind a '<KeyRelease>' event to the Entry instance which for every key release event calls the function self.typing(...
        entry_field.bind('<KeyRelease>', self.typing)

*Create a Label and Button for demonstration purpose only
        self.label = tk.Label(self)
        self.label.grid(row=1, column=0)

        btn = tk.Button(self, text='Send', command=self.send_msg)
        btn.grid(row=2, column=0)

*Reset the flag .is_typing and clear the Label text on sending the message, for demonstration only.
    def send_msg(self):
        self.is_typing = False
        self.label.config(text="")

*The function def typing(... which get called on every key release event.
Return without further action if the flag .is_typing are set.
If the flag is not set, this is the first call:

*

*Set the flag

*Do the action, her only set the Label text to "is typing".
def typing(self, *args):
    if self.is_typing:
        return

    self.is_typing = True
    self.label.config(text="is typing")

*Run the demonstration app
if __name__ == "__main__":
    App().mainloop()

Tested with Python: 3.5


text:
Q: Audio booster for pc Is there any software which can be used to boost the audio output from the PC. Mostly I want it to work on browser, for eg. to watch videos on youtube with boosted sound.
I am using Windows XP SP3

A: Check out the program called SX Fidelity Amplifier.
SX Fidelity Amplifier is suitable for everyone who wants enhanced audio from a digital source. Use SX Fidelity Amplifier for:

*

*PC applications.

*Music Services.

*Streaming Internet Radio.

If not buying, just reinstall after the trying period expired.
Good luck.

A: Unfortunately, Windows XP is a lot more limited than Vista/7 which can do this out the box quite easily.
You can try to see if your driver software came with any advanced options such as artificial boost or loudness equalization... apart from this, your best bet is to simply turn your speakers up or buy more powerful/louder ones.


text:
Q: Can't connect to internet in Ubuntu 16.10 ping
me@home:~$ ping www.google.com
ping: www.google.com: Name or service not known

lspci
me@home:~$ sudo lspci

00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor DRAM Controller (rev 09)
00:01.0 PCI bridge: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor PCI Express Root Port (rev 09)
00:16.0 Communication controller: Intel Corporation 6 Series/C200 Series Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 6 Series/C200 Series Chipset Family USB Enhanced Host Controller #2 (rev 05)
00:1b.0 Audio device: Intel Corporation 6 Series/C200 Series Chipset Family High Definition Audio Controller (rev 05)
00:1c.0 PCI bridge: Intel Corporation 6 Series/C200 Series Chipset Family PCI Express Root Port 1 (rev b5)
00:1c.5 PCI bridge: Intel Corporation 6 Series/C200 Series Chipset Family PCI Express Root Port 6 (rev b5)
00:1d.0 USB controller: Intel Corporation 6 Series/C200 Series Chipset Family USB Enhanced Host Controller #1 (rev 05)
00:1f.0 ISA bridge: Intel Corporation H61 Express Chipset Family LPC Controller (rev 05)
00:1f.2 SATA controller: Intel Corporation 6 Series/C200 Series Chipset Family SATA AHCI Controller (rev 05)
00:1f.3 SMBus: Intel Corporation 6 Series/C200 Series Chipset Family SMBus Controller (rev 05)
01:00.0 VGA compatible controller: NVIDIA Corporation GT218 [GeForce 210] (rev a2)
01:00.1 Audio device: NVIDIA Corporation High Definition Audio Controller (rev a1)
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 09)

apt-get install
me@home:~$ sudo apt-get install lgraph

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package lgraph

ifconfig
me@home:~$ ifconfig

enp0s29u1u5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    inet 192.168.42.121  netmask 255.255.255.0  broadcast 192.168.42.255
    inet6 2405:205:818f:10b6:6d17:f005:a807:faba  prefixlen 64  scopeid 0x0<global>
    inet6 2405:205:818f:10b6:d4c3:6f9:d1a0:3898  prefixlen 64  scopeid 0x0<global>
    ether 02:14:0b:03:ff:31  txqueuelen 1000  (Ethernet)
    RX packets 15  bytes 1584 (1.5 KB)
    RX errors 65  dropped 0  overruns 0  frame 0
    TX packets 173  bytes 28069 (28.0 KB)
    TX errors 1  dropped 0 overruns 0  carrier 0  collisions 0

enp3s0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
    ether 78:24:af:bc:a8:a2  txqueuelen 1000  (Ethernet)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
    inet 127.0.0.1  netmask 255.0.0.0
    inet6 ::1  prefixlen 128  scopeid 0x10<host>
    loop  txqueuelen 1  (Local Loopback)
    RX packets 99790  bytes 6000434 (6.0 MB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 99790  bytes 6000434 (6.0 MB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

I use my android mobile to tether over USB.


text:
Q: Were there attempts to express derivatives of Delta function as polynomials of Delta function? Is seems to me that it makes sense to presume some relations between derivatives of Dirac delta functions and its powers. I wonder, whether someone proposed a similar theory?
Particularly, it could make sense that
$$\frac{\pi^3 \delta(0) ^3}{6}+\frac{\pi \delta(0) }{12}=-\pi \delta''(0)$$
In such formalism, the more "inner" peaks of the distribution (when we approximate it with a smooth function) would be represented by higher powers of $\pi\delta(0)$.
I wonder whether similar relations ever arised as a formal method or in any other form.
UPDATE
This paper seemingly makes an attempt, but their results are quite different. Particularly, following their paper
$$\delta''(t)=16\pi^2\delta^3(t)$$
which is different from the above expression. To my view, their approach has many weaknessess, particularly, in my view $\delta''(0)$ should have the opposite sign than $\delta^3(0)$ (which is the case if we approximate delta function with a smooth curve).

A: There is a serious difficulty with the notion of products for distributions ; as a matter of fact Laurent Schwartz, one of the creator of Distribution Theory, wrote an article expressing the impossibility of multiplying distributions http://sites.mathdoc.fr/OCLS/pdf/OCLS_1954__21__1_0.pdf
On the other hand some simple observations are in order: just think that you want to define $\delta_0^2$, the square of the Dirac mass at 0: a natural idea would be to approximate the Dirac mass by $\rho(\frac{x}\epsilon)\frac1{\epsilon}$ with $\rho$ smooth compactly supported with integral 1 and take a look at
$$
\rho(\frac{x}\epsilon)^2\frac1{\epsilon^2}.
$$
Considering now a test function $\phi$ say smooth and compactly supported, we may check
$$
\int\rho(\frac{x}\epsilon)^2\frac1{\epsilon^2}\phi(x) dx=
\int\rho(t)^2\frac1{\epsilon}\phi(\epsilon t) dt\sim\frac1{\epsilon} \phi(0)\int \rho(t)^2
dt$$
if $\phi(0)\not=0$. Nonetheless there is no finite limit if $\phi(0)\not=0$, but even the factor of $1/\epsilon$ depends on $\rho$, that is on the approximation process.
A more subtle remark is due to Lars Hörmander: you may define the so-called wave-front-set of a distribution and say that if $T_1, T_2$ are distributions such that
$$
(x,\xi_1)\in WF T_1,\quad (x,\xi_2)\in WF T_2\Longrightarrow \xi_1+\xi_2\not=0,
$$
then $T_1T_2$ makes sense. In particular you may consider
$$
\left(\frac{1}{x+i0}\right)^2, \quad \text{but not }\quad \delta_0^2,
$$
meaning that
$
\lim_{\epsilon\rightarrow 0_+}\int \frac{\phi(x)}{(x+i\epsilon)^2} dx
$
makes sense for any test function $\phi$.
Somehow the notion of wave-front-set is providing the mathematical obstruction to a general rule of multiplication for distributions.

A: For what it's worth, a formula relating derivatives and powers of Dirac delta functions was discussed in Products and compositions with the Dirac delta function:

The formula is credited to 1974 and 1977 papers by Fisher and Tewari in the journal "Mathematics Student", which I have not found accessible online.


text:
Q: JUnit 4: how do I create a suite of suites? Running the junit below raises an exception.
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import com.prosveta.backend.daoimpl.AllDaoImplTests;

/**
 * Short desc.
 *
 * Longer desc.
 *
 * @author Jean-Pierre Schnyder
 *
 */
@RunWith(Suite.class)
@SuiteClasses({AllDaoImplTests.class,AllServiceImplTests.class})
public class AllBackendTests {
}

Stack trace
java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
    at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:653)
    at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:460)
    at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:286)
    at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:222)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:69)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:52)
    at java.lang.Class.initAnnotationsIfNecessary(Class.java:3070)
    at java.lang.Class.getAnnotations(Class.java:3050)
    at org.junit.runner.Description.createSuiteDescription(Description.java:72)
    at org.junit.internal.runners.ErrorReportingRunner.getDescription(ErrorReportingRunner.java:25)
    at org.junit.runner.Runner.testCount(Runner.java:38)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.countTestCases(JUnit4TestClassReference.java:30)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.countTests(RemoteTestRunner.java:487)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:455)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Thanks for your answer !

A: I finally found a way of doing what I wanted to achieve with running a junit 4 suite of suites, i.e. running all the tests in all the modules of a multimodule project. To do that, use the Johannes Link ClassPathSuite tool.
Download the jar, install it in your maven repo, create a allTests project which depends on your other projects where your junits reside and create an AllTestClass. Here are some code and scn capture to illustrate the solution:
Install the jar into your maven repo

Create an allTests project

the pom ...
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.prosveta.backend</groupId>
<artifactId>alltests</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>com.prosveta.backend</groupId>
        <artifactId>serviceimpl</artifactId>
        <version>1.0-SNAPSHOT</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.prosveta.backend</groupId>
        <artifactId>daoimpl</artifactId>
        <version>1.0-SNAPSHOT</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.prosveta.backend</groupId>
        <artifactId>model</artifactId>
        <version>1.0-SNAPSHOT</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.extensions</groupId>
        <artifactId>cpsuite</artifactId>
        <version>1.2.5</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
</dependencies>

Add dependencies in Eclipse ...

and here is the all tests class
package com.prosveta.backend.serviceimpl;

import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
public class AllBackendTests {
}

which you just "run as JUnit".

A: If you use eclipse; Properties of Project (Right click on project) / Java Build Path / Project / ....Add your testing projects..and run again :)

A: This exception is usually raised when the test is using a class that is not in the classpath. Just make sure your classpath is correctly set.

A: I had the same problem when I was trying to execute some tests using spring framework.
If you are working on a Maven project, try to add this dependency:
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

This is my entire pom.xml
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.3.0.RELEASE</version>
        <scope>test</scope>
    </dependency>
</dependencies>

This configuration is working properly for me.


text:
Q: Python xarray xr.open_mfdataset error "ValueError: Could not find any dimension coordinates to use to order the datasets for concatenation" I am facing an issue using xarray xr.open_mfdataset. I assume it happens because my netcdf files do not have a time dimension (daily mean values; only one timestep each file). However; I do not understand how I could merge the files despite this? The files have the same lat and lon dimensions. Any suggestion? Many thanks for hints! Please find my code + netcdf file description + error message below.
CODE:
%matplotlib inline
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import os
import warnings
from shapely.geometry.polygon import LinearRing
from matplotlib import gridspec

MYPATH = os.path.join("C:\\","Users","Judith Marina","phd","Data","Satellite_data","NorthSea_Storms")
print(MYPATH)
input_root = os.path.join(MYPATH,"Xaver_AQUA_MODIS_L3_NSST")
print(input_root)

dir_list = os.listdir(input_root)
print("Files and directories in '", input_root, "' :")
#prints all files
print(dir_list)

ds = xr.open_mfdataset(dir_list)

ERROR MESSAGE:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\Users\JUDITH~2\AppData\Local\Temp/ipykernel_6028/798315470.py in <module>
----> 1 ds = xr.open_mfdataset(dir_list)

~\miniconda3\lib\site-packages\xarray\backends\api.py in open_mfdataset(paths, chunks, concat_dim, compat, preprocess, engine, data_vars, coords, combine, parallel, join, attrs_file, combine_attrs, **kwargs)
    934             # Redo ordering from coordinates, ignoring how they were ordered
    935             # previously
--> 936             combined = combine_by_coords(
    937                 datasets,
    938                 compat=compat,

~\miniconda3\lib\site-packages\xarray\core\combine.py in combine_by_coords(data_objects, compat, data_vars, coords, fill_value, join, combine_attrs, datasets)
    973         concatenated_grouped_by_data_vars = []
    974         for vars, datasets_with_same_vars in grouped_by_vars:
--> 975             concatenated = _combine_single_variable_hypercube(
    976                 list(datasets_with_same_vars),
    977                 fill_value=fill_value,

~\miniconda3\lib\site-packages\xarray\core\combine.py in _combine_single_variable_hypercube(datasets, fill_value, data_vars, coords, compat, join, combine_attrs)
    624         )
    625
--> 626     combined_ids, concat_dims = _infer_concat_order_from_coords(list(datasets))
    627
    628     if fill_value is None:

~\miniconda3\lib\site-packages\xarray\core\combine.py in _infer_concat_order_from_coords(datasets)
    142
    143     if len(datasets) > 1 and not concat_dims:
--> 144         raise ValueError(
    145             "Could not find any dimension coordinates to use to "
    146             "order the datasets for concatenation"

ValueError: Could not find any dimension coordinates to use to order the datasets for concatenation

NETCDF FILE CHARACTERISTICS
File.variables.keys()
KeysView(Frozen({'sst': <xarray.Variable (lat: 4320, lon: 8640)>
[37324800 values with dtype=float32]
Attributes:
    long_name:      Sea Surface Temperature
    units:          degree_C
    standard_name:  sea_surface_temperature
    valid_min:      [-1000]
    valid_max:      [10000]
    display_scale:  linear
    display_min:    [-2.]
    display_max:    [45.], 'qual_sst': <xarray.Variable (lat: 4320, lon: 8640)>
[37324800 values with dtype=float32]
Attributes:
    long_name:  Quality Levels, Sea Surface Temperature
    valid_min:  [0]
    valid_max:  [5], 'lat': <xarray.IndexVariable 'lat' (lat: 4320)>
array([ 89.979164,  89.9375  ,  89.89583 , ..., -89.895836, -89.93751 ,
       -89.97918 ], dtype=float32)
Attributes:
    long_name:      Latitude
    units:          degrees_north
    standard_name:  latitude
    valid_min:      [-90.]
    valid_max:      [90.], 'lon': <xarray.IndexVariable 'lon' (lon: 8640)>
array([-179.97917, -179.9375 , -179.89584, ...,  179.89583,  179.93752,
        179.97917], dtype=float32)
Attributes:
    long_name:      Longitude
    units:          degrees_east
    standard_name:  longitude
    valid_min:      [-180.]
    valid_max:      [180.], 'palette': <xarray.Variable (rgb: 3, eightbitcolor: 256)>
array([[ 91,  10, 118, ..., 238, 223,   8],
       [237, 216,   8, ...,   8, 224, 127],
       [  8, 224, 119, ...,   0,   0,   0]], dtype=uint8)}))


text:
Q: Flutter - Update parent state from child I'm not able to update the parent state from a child. The child widget has a callback named 'onDragEnd' which is called once the drag and drop operation on a grid cell is finished. At this time the parent (the grid) should rebuild UI according to the items new sort, but nothing happens. If I set a breakpoint before the 'setState()' the 'elems' property contains the correct items with right sorting. Even if I replace the entire list, UI is not updating. Any suggestions? What am I missing?
class _CustomGridState extends State<CustomGrid> {

    List<Pack> elems;

    _CustomGridState(this.elems);

    @override
    Widget build(BuildContext context) {
         return GridView.count(
                crossAxisCount: 3,
                children: this
                  .elems
                  .map((pack) => PackFingernail(pack: pack,

                       onDragEnd: (Pack source, Pack target) {

                            var sourceIndex = this.elems.indexWhere((p) => p.id == source.id);
                            var targetIndex = this.elems.indexWhere((p) => p.id == target.id);

                            this.elems.removeAt(sourceIndex);
                            this.elems.insert(targetIndex, source);

                            setState(() {}); // Not working <-----
                       })

                   ).toList()
               );
   }
 }

A: Try to add a key for your PackFingernail
// constructor
PackFingernail(..., {Key key}): super(key:key)

// in gridview
.map((pack) => PackFingernail(pack: pack,
 onDragEnd: (Pack source, Pack target) {
    ...
 },
 key: Key(pack.id.toString()))
).toList()

Key can help to rebuild the GridView


text:
Q: PHP add query with GET method I making site with products where I can sort my products by price. So, first I search product and display result:
    <form action="" method="GET">
        <input type="text" name="search" id="search"/>
        <select name="category" id="category_search">
            <option value="default">Pretraži po kategorijama</option>
            <option value="torbe">Torbe</option>
            <option value="tv">Tv</option>
            <option value="udzbenici">Udžbenici</option>
            <option value="vrtna_garnitura">Vrtna garnitura</option>
            <option value="vrtna_oprema">Vrtna oprema</option>
            <option value="zemljiste">Zemljište</option>
            <option value="zvucnici/slusalice">Zvučnici/slušalice</option>
        </select>
        <input class="myButton" type="submit" value="pretraži"/>
    </form>

    if(isset($_GET['search'])){
        $search = sanitize($_GET['search']);
        $cat = sanitize($_GET['category']);

        if(!empty($search)){
           $search_query = mysql_query("SELECT * FROM products WHERE `product_name` LIKE '%$search%' OR `category` LIKE '%$cat%'".$sql_price.' '.$sql);

            while ($results_row = mysql_fetch_assoc($search_query)){
                echo '

'.$results_row['product_name'].'
Cijena: '.$results_row['price'].'kn
';
            }
        }
    }

Then I made two options of sorting products first:
<?php echo 'Niža prema višoj';?>
<?php echo 'Viša prema nižoj';?>
$sql = '';
if(isset($_GET['sort'])){
    if ($_GET['sort'] == 'asc'){
        $sql = " ORDER BY price ASC";
    }elseif ($_GET['sort'] == 'desc'){
        $sql = " ORDER BY price DESC";
    }
}

And second:
<form method="get" id="price_form">
            Od <input type="number" class="price_input" name="min_price" id="min_price" placeholder="kn"/> do
            <input type="number" class="price_input" name="max_price" id="max_price" placeholder="kn"/>
            <button name="price_submit" id="price_submit">Kreni</button>
   </form>

$sql_price = '';
   if(isset($_GET['price_submit'])){
     $min_price = sanitize($_GET['min_price']);
     $min_price = (int)$min_price;

     $max_price = sanitize($_GET['max_price']);
     $max_price = (int)$max_price;

     if($min_price == ''){
        $errors[] = 'Minimalna cijena mora biti ispunjena';
     }elseif($max_price == ''){
        $errors[] = 'Maksimalna cijena mora biti ispunjena';
     }elseif($min_price < 0){
        $errors[]= 'Minimalna cijena ne smije biti manja od 0kn';
     }elseif($max_price < 0){
        $errors[] = 'Maksimalna cijena ne smije biti manja od 0kn';
     }elseif($min_price > $max_price){
        $errors[] = 'Minimalna cijena ne smije biti veća od maksimalne';
     }

    if(empty($errors)){
        $sql_price = 'BETWEEN '.$min_price.' AND '.$max_price;
    }else{
        echo output_errors($errors);
    }
}

Second one don't work, I tried to make sort, when I press buttont to sort product by price from min price what user inputted to max price what user inputted, so I should get something like this:

but I get:

Thanks

A: I have updated old code. please try this code
You no need to a tag because you can give an action in form tag to redirect the other page.

   <form action="search_site.php" method="get" id="testing_form">
<input type="text" name="search" id="search"/>
<select name="category" id="category_search">
 <option value="default">Pretraži po kategorijama</option>
 <option value="torbe">Torbe</option>
 <option value="tv">Tv</option>
 <option value="udzbenici">Udžbenici</option>
 <option value="vrtna_garnitura">Vrtna garnitura</option>
 <option value="vrtna_oprema">Vrtna oprema</option>
 <option value="zemljiste">Zemljište</option>
 <option value="zvucnici/slusalice">Zvučnici/slušalice</option>
</select>
Od <input type="number" class="price_input" name="min_price" id="min_price" placeholder="kn"/> do
<input type="number" class="price_input" name="max_price" id="max_price" placeholder="kn"/>
<button name="price_submit" id="price_submit">Kreni</button>
</form>

<?php
error_reporting(0);
$sql_price = '';
if(isset($_GET['price_submit'])){

    $min_price = sanitize($_GET['min_price']);
    $min_price = (int)$min_price;
    $max_price = sanitize($_GET['max_price']);
    $max_price = (int)$max_price;

    if($min_price == ''){

        $errors[] = 'Minimalna cijena mora biti ispunjena';
    }elseif($max_price == ''){

        $errors[] = 'Maksimalna cijena mora biti ispunjena';
    }elseif($min_price < 0){

        $errors[]= 'Minimalna cijena ne smije biti manja od 0kn';
    }elseif($max_price < 0){

        $errors[] = 'Maksimalna cijena ne smije biti manja od 0kn';
    }elseif($min_price > $max_price){

        $errors[] = 'Minimalna cijena ne smije biti veća od maksimalne';
    }
    if(empty($errors)){

        $sql_price = 'BETWEEN '.$min_price.' AND '.$max_price;
    }else{

        echo output_errors($errors);
    }
    $search = $_GET['search'];
    $category = $_GET['category'];
}
$sql = '';
if(isset($_GET['sort'])){

    if ($_GET['sort'] == 'asc'){

        $sql = " ORDER BY price ASC";
    }elseif ($_GET['sort'] == 'desc'){

        $sql = " ORDER BY price DESC";
    }
}


text:
Q: OKHttp3 post method keeps return 404 error I want to do POST with OKHttp3, but it keeps returning 404. Is there anything wrong with my code? The server side keeps telling me that the url and json are correct.
I have tried another post url and json, it works, return code 200.
package com.epsfamily.www.kaipostb;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.IOException;
import java.util.logging.Logger;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    OkHttpClient client = new OkHttpClient();

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    String url;

    // test data
    String bowlingJson(String player1, String player2) {
        return "{ \"deviceId\": \"1abcd\", \"buildingId\": 2, \"isRoutingOptimized\": false, \"isFromCurrentLocation\": true, \"startPoint\": 1, \"destinations\": [ 3, 4 ], \"createdAt\": \"2016-02-19T20:08:45.308Z\" } ";
    }

    String doPostRequest(String url, String json) throws IOException {
        com.orhanobut.logger.Logger.json(json);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        com.orhanobut.logger.Logger.v("code: " + response.code());

        return response.body().string();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        url = "http://54.86.18.109:5080/Routing";

        new PostAsync().execute();
    }

    public class PostAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String json = bowlingJson("Jesse", "Jake");
            String postResponse = null;
            try {
                postResponse = doPostRequest(url, json);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("res: " + postResponse);

            return postResponse;
        }
    }

}

A: Go here: http://54.86.18.109:5080/Routing
What you get? It's 404. Check again url.
EDIT: ok, it's POST, but i still get 404 with POST request.

A: Finally, found that server gave me the wrong url. it should be "http://54.86.18.109:5080/api/Routing".
Thank you guys for trying...


text:
Q: QueryBuilder lastInsertId() I would like to have the last UID of the entry. For mysql, it is "insertId()". How does that work at Extbase?
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder
   ->insert($table)
   ->values([
       'test_id'          => 1,
       'test2_id'         => 2,
   ]);

$queryBuilder->execute();

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table2);
$queryBuilder
   ->insert($table2)
   ->values([
       'uid_local'         => ?, // uid from $table
       'uid_foreign'       => 1
   ]);
$queryBuilder->execute();

A: You can get the last insert id with $queryBuilder->getConnection()->lastInsertId();
So that would make it:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder
   ->insert($table)
   ->values([
       'test_id'          => 1,
       'test2_id'         => 2,
   ]);

$queryBuilder->execute();
$tableUid = $queryBuilder->getConnection()->lastInsertId();

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table2);
$queryBuilder
   ->insert($table2)
   ->values([
       'uid_local'         => $tableUid,
       'uid_foreign'       => 1
   ]);
$queryBuilder->execute();

A: I'm a bit unsure if it's available when using the QueryBuilder for inserting new records, but the migration guide in TYPO3 Docs explain how you migrate the sql_insert_id() method in the new Doctrine Database Layer
https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Database/Migration/Index.html#sql-insert-id
Hint:
(int)$databaseConnectionForPages->lastInsertId('pages');