Method (Inheritance) and overriding in Rust

Question: use crate::size::Size;

pub struct Car {
    pub name: String,
    pub color: (u32, u32, u32),
    pub size: Size,
    pub model: u32,
    pub private: i32,
}

impl Car {
    pub fn new() -> Self {
        Car {
            name: String::from("Default Template"),
            color: (1, 0, 1),
            size: Size::NORMAL,
            model: 2019,
            private: 2,
        }
    }
}
pub trait CommontMethods {
    fn change_name_and_model(&mut self, private: i32);
}

pub trait PrintChanges {
    fn print_changes(&self);
}

impl CommontMethods for Car {
    fn change_name_and_model(&mut self, private: i32) {
        println!("{}", self.name);
        self.model = 2000;
        self.private = private;
        self.print_changes();
    }
}

impl PrintChanges for Car {
    fn print_changes(&self) {
        println!("Model :{} , private : {}", self.model, self.private);
    }
}

This is the Car struct it has the a _name_and_model() function that calls print_changes(). The Honda struct that has a field car : Car {...}
When calling honda.change_name_and_model(), I want it to actually call the print_changes() function that is implemented in Honda not Car.
use crate::car::*;
use crate::size::Size;

pub struct Honda {
    pub car: Car,
    lights_on: bool,
}

impl Honda {
    pub fn new() -> Self {
        Honda {
            car: Car {
                name: String::from("Honda"),
                color: (1, 1, 1),
                size: Size::BIG,
                model: 2002,
                private: 3,
            },
            lights_on: true,
        }
    }
}

impl PrintChanges for Honda {
    fn print_changes(&self) {
        self.car.print_changes();
        println!("this is usefull !");
    }
}

So when i want to use this like this:
fn main() {
    let mut honda = Honda::new();

    honda.car.change_name_and_model(0);
}

The change_name_and_model() function calls the car implementation of print_changes(), but I want it to call Honda one instead.
Is that even possible ?
Comment: Rust isn't Java. Don't try to emulate Java.
Comment: Do what exactly? Your real goal is to build features, not to model a domain's data according to an OO hierarchy of objects. Because Rust isn't an OO language. I honestly don't see exactly what would be the best lead. Maybe start with simple programs and try to form a vision on how to design a complex program ?
Comment: @DenysSéguret OP's question is about polymorphism rather than inheritance.
Comment: Honda and Honda::car are two different entities. Honda contains a Car but is not a Car. There is no "is a" relationship between structs in Rust, only between traits. The simplest way to do what you want is to combine changing and printing changes in a single trait, and implement that trait for both Car and Honda. You don't have to duplicate the code. You may have to call a Car implementation from a Honda implementation. If you want to keep two separate traits, you will need two separate trait objects, one for CommonMethods and one for PrintChanges.
Comment: I see on a lot of comments on Rust posts people asserting things to the effect, "why are you trying to do OO? Rust isn't OO." This is false. Rust is multi-paradigm and if you prefer an OO approach to software development, have at it. You can apply your OO skills you gained with Java or other languages with Rust. Any of the popular OO design patterns are possible with Rust. Iterators in fact are an OO abstraction which Rust uses heavily.
Comment: yes but how i do this in rust without duplicated code ?
Comment: @DenysSéguret rust has everything an OO language needs, namely encapsulation and polymorphism. It doesn't use inheritance but that's hardly a defining feature of an OO language.
Comment: @n.1.8e9-where's-my-sharem. OP's question is precisely about inheritance.
Comment: Regarding inheritance, Rust does have it - just not in the same way you expect from Java or C++. Traits can inherit from other traits, data can't be inherited, but methods can. The methods can in fact have default implementations too. And if you needed a base trait to have state, there are some tricks that can make it possible.
Answer: Pardon my bit of OO redesign here. I'm going to make Car my base "class" - or trait, that Honda and Chevrolet inherit from.
If you're coming from Java, think of traits as interfaces - or abstract classes. Since traits can contain default implementations for methods, they're more like abstract classes - except they can't have data members.
Let's say that Car inherits from another trait, PrintsUpdate. Which means Honda and Chevrolet also have to implement it (or if PrintsUpdate has a default implementation, overriding it is optional).
If we do everything right, we can get the polymorphic behavior we want. For instance we can write functions that take a pointer to the Car trait and invoke their methods, and observe that the correct overriding implementation gets called.
pub fn polymorphism_test()
{
    let mut honda = Honda::new("Civic", "Foolton", "Blue");
    let mut chevy = Chevrolet::new("Corvette", "Barbie", "Red");

    update_car(&mut honda, "Bazner", "Green");
    update_car(&mut chevy, "Quxner", "Orange");
}

pub fn update_car(car: &mut dyn Car, owner: &str, color: &str) {
    println!("Updating a {}...", car.make());
    car.update(owner, color);
}

output:
Updating a Honda...
Printing changes for Bazner's Green Honda Civic
Updating a Chevrolet...
Printing changes for Quxner's Orange Chevrolet Corvette

Here are our base traits. I have Car inheriting from PrintsUpdate:
pub trait Car: PrintsUpdate {
    fn make(&self) -> &str;
    fn set_owner(&mut self, name: &str);
    fn set_color(&mut self, name: &str);
    fn update(&mut self, owner: &str, color: &str)
    {
        self.set_owner(owner);
        self.set_color(color);
        self.print_changes();
    }
    //fn print_changes(&self);
}

pub trait PrintsUpdate {
    fn print_changes(&self) {
        println!("Default implementation for PrintsUpdate...");
    }
}

Note that in Car::update() methods are being invoked that aren't implemented yet. This is fine. Chevrolet and Honda will have to implement them if they inherit Car.
Here's our Honda "class":
pub struct Honda {
    make: String,
    model: String,
    owner: String,
    color: String,
}
impl Honda {
    pub fn new(model: &str, owner: &str, color: &str) -> Self {
        Honda {
            make : "Honda".into(), model: model.into(),
            owner: owner.into(),   color: color.into()
        }
    }
}

impl Car for Honda {
    fn make(&self) -> &str {
        &self.make
    }
    fn set_owner(&mut self, name: &str) {
        self.owner = name.into();
    }
    fn set_color(&mut self, color: &str) {
        self.color = color.into();
    }
}
impl PrintsUpdate for Honda {
    fn print_changes(&self) {
        println!("Printing changes for {}'s {} Honda {}",
                 self.owner, self.color, self.model);
    }
}

And Chevrolet:
pub struct Chevrolet {
    make: String,
    model: String,
    owner: String,
    color: String,
}
impl Chevrolet {
    pub fn new(model: &str, owner: &str, color: &str) -> Self {
        Chevrolet {
            make : "Chevrolet".into(), model: model.into(),
            owner: owner.into(),       color: color.into()
        }
    }
}
impl Car for Chevrolet {
    fn make(&self) -> &str {
        &self.make
    }
    fn set_owner(&mut self, name: &str) {
        self.owner = name.into();
    }
    fn set_color(&mut self, color: &str) {
        self.color = color.into();
    }
}
impl PrintsUpdate for Chevrolet {
    //fn print_changes(&self) {
    //    println!("Printing changes for {}'s {} Chevrolet {}",
    //             self.owner, self.color, self.model);
    //}
}

If Chevrolet chooses not to override PrintsUpdate::print_changes() that's fine because there's a default implementation for it. The output at the top is what it looks like if Chevrolet::prints_changes() isn't commented out. Below is with it commented out.
Running the polymorphism_test() function again, we get:
Updating a Honda...
Printing changes for Bazner's Green Honda Civic
Updating a Chevrolet...
Default implementation for PrintsUpdate...


How to search by hierarchical taxonomy in views?

Question: I have a view with a Global: Combine fields filter with some fields, one of theese fields is a hiererchical select field of a taxonomy terms. But it doesn't work.
How can I set a search box to search by text in a hiererchical select field (and other fields)?
Answer: You can use Chosen Module and it supports for hiererchical select

By default the module will automatically apply itself to any select
  elements that have more than 20 options, which is a reasonable default
  for which having Chosen will be useful. To change or disable this
  automatic enhancement, you can change the selectors (or remove all
  selectors) from the Apply Chosen to the following elements field on
  the Chosen administration page.


3d distance calculations with GeoDjango

Question: I am using

python 2.7.12
django 1.10.6
postgreSQL 9.5.6
postGIS 2.2.2

First question
I need to use GeoDjango to calculate distance between two points. When I checked the  documentation it says that GeoQuerySet.distance() is deprecated and instead use Distance() from django.contrib.gis.db.models.functions.
The following code works OK:
from django.contrib.gis.db.models.functions import Distance

p1 = Instrument.objects.get(pk=151071000).coordinates
p2 = Instrument.objects.filter(pk=151071008)

for i in p2.annotate(distance=Distance('coordinates', p1)):
    print i.distance
    print i.distance.__class__

Output:
461.10913945 m
<class 'django.contrib.gis.measure.Distance'>

My model:
class Instrument(models.Model):
    ...
    coordinates = gis_models.PointField(null=True, blank=True, dim=3)

But I have only two points so when I try to use Distance() without annotate() it returns instance of class django.contrib.gis.db.models.functions.Distance() rathen than django.contrib.gis.measure.Distance():
p1 = Instrument.objects.get(pk=151071000).coordinates
p2 = Instrument.objects.get(pk=151071008).coordinates
print Distance(p1, p2)

Output:
Distance(Value(SRID=4326;POINT Z (-76.48623600000001 44.260223 0)), GeomValue(SRID=4326;POINT Z (-76.490923 44.262658 0)))

How do I receive the same result as with using annotate()?
Second question
I have to calculate 3d distance that is taking into account depth/elevation. But when I try to do it I receive the same result as with 2d. Below I changed elevation to 200 in the first object:
p1 = Instrument.objects.get(pk=151071000)
p1.coordinates = 'SRID=4326;POINT Z (-76.48623600000001 44.260223 200)'
p2 = Instrument.objects.filter(pk=151071008)

for i in p2.annotate(distance=Distance('coordinates', p1.coordinates)):
    print i.distance

Output:
461.10913945 m

Answer: Let's break the problem down:

In the Distance class documentation, we can read the following:

Accepts two geographic fields or expressions and returns the distance between them, as a Distance object.

So the Distance(p1, p2) returns a Distance object.
If you do:
p1 = Instrument.objects.get(pk=151071000).coordinates
p2 = Instrument.objects.get(pk=151071008).coordinates
d = Distance(m=p1.distance(p2))
print d.m

You will get the measurement in meters.
I would stick with the annotate solution, which seems more solid! (opinionated response)

Distance calculates the 2D distance between two points. In order to get a 3D calculation, you need to create one yourself.
You can have a look at my method from this question: Calculating distance between two points using latitude longitude and altitude (elevation)
EDIT 2019: Since the initial answer I have composed a Q&A style example here: How to calculate 3D distance (including altitude) between two points in GeoDjango that uses a far better (and less calculation error-prone) distance calculation between 2 points with altitude.
In sort:
We need to calculate the 2D great-circle distance between 2 points using either the Haversine formula or the Vicenty formula and then we can combine it with the difference (delta) in altitude between the 2 points to calculate the Euclidean distance between them as follows:
dist = sqrt(great_circle((lat_1, lon_1), (lat-2, lon_2).m**2, (alt_1 - alt_2)**2)

The solution assumes that the altitude is in meters and thus converts the great_circle's result into meters as well.

Leaving this here for comment continuation purposes.
 2. Distance calculates the 2D distance between two points. In order to get a 3D calculation, you need to create one yourself.
You can have a look at my method from this question: Calculating distance between two points using latitude longitude and altitude (elevation)

Let polar_point_1 = (long_1, lat_1, alt_1) and polar_point_2 =
  (long_2, lat_2, alt_2)
Translate each point to it's Cartesian equivalent by utilizing this
  formula:
x = alt * cos(lat) * sin(long)
y = alt * sin(lat)
z = alt * cos(lat) * cos(long)

and you will have p_1 = (x_1, y_1, z_1) and p_2 = (x_2, y_2, z_2) points respectively.
Finally use the Euclidean formula:
dist = sqrt((x_2-x_1)**2 + (y_2-y_1)**2 + (z_2-z_1)**2)

Comment: the first piece of code gives me an error *AttributeError: 'Distance' object has no attribute 'm'* because variable *d* is not *django.contrib.gis.measure.Distance* object.
Comment: @Nargiza Because the initial answer didn't work as expected by the docs, I have made this post: http://stackoverflow.com/questions/43864292/djangos-distance-function-not-returning-a-distance-object in order to investigate it further!
Comment: Yes, I'm also curious about that!
Answer: ** python 3.7, Django 2.2.10
some useful functions ive written to help me with lat/lon coordinates in applications
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import Distance

def get_point(lat, lon):
    try:
        lat = float(lat)
        lon = float(lon)
        if lat and lon:
            return Point(x=float(round(lon, 6)), y=float(round(lat, 6)), srid=4326)
        else:
            return None
    except Exception:
        return None

def get_point_to_point_distance(point_one, point_two, measurement_unit="mile"):
    return Distance(**{measurement_unit: point_one.distance(point_two)})

where measurement_unit can be any of the following:
    STANDARD_UNIT = "m"
    UNITS = {
        'chain': 20.1168,
        'chain_benoit': 20.116782,
        'chain_sears': 20.1167645,
        'british_chain_benoit': 20.1167824944,
        'british_chain_sears': 20.1167651216,
        'british_chain_sears_truncated': 20.116756,
        'cm': 0.01,
        'british_ft': 0.304799471539,
        'british_yd': 0.914398414616,
        'clarke_ft': 0.3047972654,
        'clarke_link': 0.201166195164,
        'fathom': 1.8288,
        'ft': 0.3048,
        'german_m': 1.0000135965,
        'gold_coast_ft': 0.304799710181508,
        'indian_yd': 0.914398530744,
        'inch': 0.0254,
        'km': 1000.0,
        'link': 0.201168,
        'link_benoit': 0.20116782,
        'link_sears': 0.20116765,
        'm': 1.0,
        'mi': 1609.344,
        'mm': 0.001,
        'nm': 1852.0,
        'nm_uk': 1853.184,
        'rod': 5.0292,
        'sears_yd': 0.91439841,
        'survey_ft': 0.304800609601,
        'um': 0.000001,
        'yd': 0.9144,
    }

    # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT.
    ALIAS = {
        'centimeter': 'cm',
        'foot': 'ft',
        'inches': 'inch',
        'kilometer': 'km',
        'kilometre': 'km',
        'meter': 'm',
        'metre': 'm',
        'micrometer': 'um',
        'micrometre': 'um',
        'millimeter': 'mm',
        'millimetre': 'mm',
        'mile': 'mi',
        'yard': 'yd',
        'British chain (Benoit 1895 B)': 'british_chain_benoit',
        'British chain (Sears 1922)': 'british_chain_sears',
        'British chain (Sears 1922 truncated)': 'british_chain_sears_truncated',
        'British foot (Sears 1922)': 'british_ft',
        'British foot': 'british_ft',
        'British yard (Sears 1922)': 'british_yd',
        'British yard': 'british_yd',
        "Clarke's Foot": 'clarke_ft',
        "Clarke's link": 'clarke_link',
        'Chain (Benoit)': 'chain_benoit',
        'Chain (Sears)': 'chain_sears',
        'Foot (International)': 'ft',
        'German legal metre': 'german_m',
        'Gold Coast foot': 'gold_coast_ft',
        'Indian yard': 'indian_yd',
        'Link (Benoit)': 'link_benoit',
        'Link (Sears)': 'link_sears',
        'Nautical Mile': 'nm',
        'Nautical Mile (UK)': 'nm_uk',
        'US survey foot': 'survey_ft',
        'U.S. Foot': 'survey_ft',
        'Yard (Indian)': 'indian_yd',
        'Yard (Sears)': 'sears_yd'
    }

3d distance calculations with GeoDjango


Problemas com rotas no laravel

Question: Estou trabalhando com group routes no laravel 5.2 e estou tendo problema com a parte do create.store  a rota que salva meu objeto.
Meu arquivos estão estruturados da seguinte maneira:
ClienteController.php
<?php

namespace App\Http\Controllers;

use Request;
use App\Http\Requests\CategoriaRequest;
use App\Categoria;

class CategoriaController extends Controller
{
public function index(){
    $categorias =  Categoria::all();

    if(Request::wantsJson()){
        return $categorias;
    }else{
        return view('Categoria.listCategoria', compact('categorias'));
    }
}

public function create(){
    $categoria = new Categoria();
    return view('Categoria.cadCategoria', compact('categoria'));
}

public function store(CategoriaRequest $resquest){
    dd($resquest);
    $categoria = Categoria::create($resquest->all());

    if(Request::wantsJson()){
        return $categoria;
    }else{
        return view('Categoria.listCategoria', compact('categoria'));
    }
}

public function show(Categoria $categoria){
    if(Request::wantsJson()){
        return $categoria;
    }else{
        return view('Categoria.showCategoria', compact('categoria'));
    }
}

public function edit(Categoria $categoria){
    return view('Categoria.editCategoria', compact('categoria'));
}

public function update(CategoriaRequest $request, Categoria $categoria){
    $categoria->update($request->all());
    if(Request::wantsJson()){
        return $categoria;
    }else{
        return view('Categoria.listCategoria');
    }
}

public function destroy(Categoria $categoria){
    $deleted = $categoria->delete();

    if(Request::wantsJson()){
        return (string) $deleted;
    }else{
        return view('Categoria.listCategoria');
    }
}
}

CategoriaRequest.php
class CategoriaRequest extends Request
{
/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'NmCategoria' => 'required|min:5',
        'DscCategoria' => 'required|min:5'
    ];
}
}

Meu model Categoria
class Categoria extends Model
{
protected $fillable = ['NmCategoria', 'DscCategoria'];

}

E minha rota esta assim:
Route::group(['middleware' => ['web']], function (){
  Route::resource('categorias', 'CategoriaController');
});

Meu primeiro problema é quando estou clicando em editar, a minha query fica id, sendo que meu campo está CdCategoria, assim dando erro na query:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from categorias where id = 1 limit 1)

O que poderia ser ?
Comment: Posta a parte da view também, não precisa ser tudo, apenas a parte que mostra como o valor esta sendo passado e a rota setá sendo chamada.
Answer: O Laravel assume que o nome da sua chave primaria seja id caso seja outra coisa tipo categoria_id você precisa especificar isso no model.
class Categoria extends Model{
    protected $fillable = ['NmCategoria', 'DscCategoria'];
    $primaryKey = 'CdCategoria';
}

Isso e mais algumas coisa você pode encontrar na documentação do eloquent
Comment: e se tiver 2 key ?
Comment: @RenanRodrigues não me recordo bem, mas acredito que o laravel não suporta chave primaria composta.
Comment: @RenanRodrigues quando precisar de uma chave composta seria um array no `$primarykey = ['chave1', 'chave2'];` e quando utilizar assim tem que desabilitar o auto_increment assim: `public $incrementing = false;`

Problemas com rotas no laravel


How to store/view GPS tracks from Android/iOS app on server

Question: I am looking for a way to store GPS tracks without having to export them to GPX. The GPS tracks will only be used within an iOS/Android app.
App:
The app lets users record GPS tracks and sync these to a server. Users can add information and notes to each recorded track. Each GPS point also has a timestamp so the track can be "played" in real-time (hence using GPX). After a GPS track is synced, other user can browse uploaded tracks by querying a MongoDB track collection. When users view the details they see the Mongo document content and also a Google Map with the GPX track drawn out.
Current solution:
My current solution is to export the recorded GPS track to a GPX file and store it on Amazon S3 using Cloudfront. A MongoDB document in the tracks collection contains user id, notes, date/time, comments, and links to the GPX track and a photo.
Is there a better way to store these GPS tracks rather than exporting/importing them to GPX? It's a cumbersome process and not necessary since users will never interact with the tracks outside the app. GPX files also take up a lot of space. However, I can't come up with a way to store the track data since the app is cross platform.
I use Amazon EC2 with php, Apache & MongoDB for back-end.
Answer: PHP + SQL
In the app send a request to the server sending the data either via POST, GET, or by uploading a file. In the processing PHP script open a connection to an SQL Database, and store your information there.
Comment: Thanks for the answer Matt. Another thing to consider is of course cost, where storing files on S3 is much cheaper than on EC2. I have received another recommendation of using SQLite on device and CSV on S3 for compatibility. This might be cheaper than going the database route and using EBS.


Multiple domains and subdomains on a single Pyramid instance

Question: I'm looking to have multiple domains and subdomains on a single Pyramid instance. However, I can't seem to find any documentation on it. The last question referred to a glossary with very little information and no examples. Do any of you have any examples or can direct me to better documentation?
Comment: This is a fairly old question, but I've use Paste#urlmap to do this with Pyramid: http://pythonpaste.org/modules/urlmap.html
Answer: Pyramid is just a WSGI application. This means it's dependent on the HTTP_HOST environ key (set by the Host header) to determine the host of the application. It's all relative. Point-being that Pyramid has no restrictions on what it can accept, thus the world is your oyster and you can set it up to limit content to various domains however you'd like. This of course starts with what hosts your webserver is configured to feed to your application.
Assuming you're using URL dispatch, you might want to design some custom route predicates that check the request.host value for whatever you'd like. Returning False from that predicate will prevent that route from ever matching a request to that host.
This is a large topic, so it might help if you give some more specifics. For example, since Pyramid is relative, any URL you may want to generate from 'example.com' to redirect someone to 'sub.example.com' will need to be done via a pregenerator.
def pregen(request, elements, kw):
    kw['_app_url'] = 'http://sub.example.com'
    return elements, kw

def req_sub(info, request):
    return request.host.startswith('sub')

config.add_route('sub_only', '/',
                 custom_predicates=(req_sub,),
                 pregenerator=pregen)
config.add_route('foo', '/foo')
config.add_view(view, route_name-'foo')

def view(request):
    # redirect the user to "http://sub.example.com", regardless of whether
    # request.host is "example.com" or "sub.example.com"
    return HTTPFound(request.route_url('sub_only'))

Comment: For this particular setup I'm not aware of too many examples. Typically different subdomains would represent different WSGI apps and they'd each have their own settings, with probably some shared. There's the Pyramid Cookbook of various examples, but I'm not aware of any regarding this.
Comment: My biggest obstacle with learning how this works is that I can't find any examples like this. Do you know where I can find more examples? Thank you!
Answer: If you have control over your hosting environment, I would strongly suggest keeping the domain stuff out of pyramid and handling it with a proxy server such as apache mod proxy, routing to subdomains in pyramid. Then you can easily switch any of the domain name to view routing without having anything fragile (like domain names) in your pyramid code. Your app code will be much cleaner this way, and far easier to change later.
Here's an Apache example of two domains going to one pyramid app, assuming we are serving the pyramid app somehow or another on port 5001 (gunicorn or whatever you want).
<VirtualHost *:80>
    ServerName domain_2.com

    ProxyPreserveHost On

    # send all request to our app at /app1/*
    ProxyPass / http://127.0.0.1:5001/app_1/
    ProxyPassReverse / http://127.0.0.1:5001/app_1/

</VirtualHost>

<VirtualHost *:80>
    ServerName domain_2.com

    ProxyPreserveHost On

    # send all request to our app at /app2/*
    ProxyPass / http://127.0.0.1:5001/app_2/
    ProxyPassReverse / http://127.0.0.1:5001/app_2/

</VirtualHost>

And here's an example of one domain going to several pyramid instances:
<VirtualHost *:80>
    ServerName mydomain.com

    ProxyPreserveHost On

    # admin go to manager app on 5001
    ProxyPass /media/manager/ http://127.0.0.1:5001/ retry=5
    ProxyPassReverse /media/manager/ http://127.0.0.1:5001/

    # downloads from server app on 5002
    ProxyPass /media/server/ http://127.0.0.1:5002/ retry=5
    ProxyPassReverse /media/server/ http://127.0.0.1:5002/

</VirtualHost>


Confusion about location invariance property

Question: The author of Introduction To The Theory Of Statistics by ALEXANDER M. MOOD, FRANKLIN A. GRAYBILL, DUANE C. BOSE stated that an estimator $ t(x_{1},x_{2},x_{3},.x_{n})$ is said to be location invariant if $t(x_{1}+c, x_{2}+c, x_{3}+c,., x_{n}+c) = t(x_{1},x_{2},x_{3},.x_{n})+c$. Which means estimator should be invariant of simple shift. If a constant value is added to all observation then estimator should shifted by the same constant value. Author then showed that sample variance is not a location invariant estimator since we cannot write $s^2$ as $t(x_{1}+c, x_{2}+c, x_{3}+c,., x_{n}+c) = t(x_{1},x_{2},x_{3},.x_{n})+c$. This seems right since if we add a constant value to all the observation then it just shifts the location parameter but the variability of the data remains same.
But the author of Introduction to Mathematical Statistics by ROBERT V. HOGG and ALLEN T. CRAIG defined location invariant estimator as $t(x_{1}+c, x_{2}+c, x_{3}+c,., x_{n}+c) = t(x_{1},x_{2},x_{3},.x_{n})$. Then said that sample variance $s^2$ is a location invariant statistics since it doesnt depends on location parameter.
At least I understand that these authors are talking two different things. One saying that location parameter should not depend on shift and other saying statistics should not depends on location parameter. But giving the same name location invariant for two different properties doesnt feel right.
So what is location invariant statistics?
Answer: This is one of many areas in statistics that uses abysmal terminology. According to most of the rest of the world, an invariant function's values do not change at all when acted on by a group. The first definition you cite decidedly is not invariance in this sense: physicists would call it "covariant." The lesson here is to pay attention (as you are) to the definitions and go on from there, rather than assuming a word always means what you think it does.


The precision recall AUCs calculated by two different packages are different?

Question: I used the dataset cars as an example
library("MLmetrics")
library("PRROC")
data(cars)
logreg <- glm(formula = vs ~ hp + wt,
              family = binomial(link = "logit"), data = mtcars)

The prauc returned by PRAUC is 0.861
PRAUC(y_pred = logreg$fitted.values, y_true = mtcars$vs)

However, the prauc returned by pr.curve is 0.932
pr.curve(scores.class0 = logreg$fitted.values, weights.class0 = mtcars$vs)

Is there anything wrong?
Answer: The correct one is pr.curve. If you return the curve from it (via curve=T option) and plot at the values (see below), the area over the region contains approximately $53$ squares of area $(1/28)^2$, which has area approximately $0.067$, which means under it the area is nearly $0.93$.

Sometimes, when the dataset is small, area calculation method matters, which is probably poorly implemented in MLmetrics.


Is it possible to prevent more than one device from syncing to Google Drive at a time?

Question: I think the question itself covers my issue.
I am using the Changes object to detect when there are modifications to files on a given user's Drive account. My goal is to prevent conflicts by making sure that if a user is logged into my app on more than one device, there is no simultaneous syncing, and therefore, there will be no conflicts.
Answer: The best way for you to detect when the user is logged into your application. Would be to well log it some place in the database.    When ever a user logs in or does anything in your application save the time and the device name.
My issue will be how do you decide when the user is done.   If i am using your application on my phone then swap over to my desk top because i am done with my phone how are you going to know that and not just refuse me access on my desktop because i was just on my phone.
No Google does not offer anyway of you doing this from their end.
Comment: Yeah, the issue is pretty complicated. Clearly Google Drive is not perfect for the job, but it is free (I don't have to pay for resources) and easy to implement overall. The database idea sounds like a good idea, though. But I will not waste my time implementing it until I have all of the kinks figured out, such as the one you just described. Thanks.


Event after click element in Vue

Question: This is my first post about VUE. I try use VUE in Laravel. I have this code:
index.blade.php:
@extends('front._layout.main')

@section('content')

Płyty

Sortowanie:

                xxxxx

                <product-list></product-list>

@endsection

ProductList.vue:
    <template>
        <form>

                    <select>
                        <option>Typ</option>
                    </select>

                        <input type="checkbox" id="one"/>First checkbox

                        <input type="checkbox" id="two"/>Second checkbox

                        <input type="checkbox" id="three"/>Third checkbox

        </form>

    </template>

multiselect.js:
var expanded = false;

function showMultiselect() {
    var checkboxes = document.getElementsByClassName("checkboxes");
    if (!expanded) {
        checkboxes.style.display = "block";
        expanded = true;
    } else {
        checkboxes.style.display = "none";
        expanded = false;
    }
}

app.js:
try {
    window._ = require('lodash');
    window.axios = require('axios');
    window.route = require('@/common/route');

    require('./libs/swal.js');
    require('./vue');
    require('./libs/multiselect.js');

    window.Vue = require('vue');

    Vue.component('product-list', require('./components/ProductList.vue').default);

    const app = new Vue({
        el: '#vue-rendered',
    })
} catch (e) {
    console.log(e);
}

My problem is no action after click after click #selectBox.
I want show alert and run function showMultiselect.
Htom, laravel show correct html code.
How can I repair it?
Please help me. I am beginner in Vue
Answer: Looking at the Vue file, you can handle click events using the v-on:click (or @click for shorthand) - see Vue Docs - Event Handling for more info. You can also handle conditional rendering of the checkboxes with the v-if directive - see Vue Docs - Conditional Rendering for more info.
The end result in the .vue file, using your previous code, would be something like this.
ProductList.vue:

  <template>
        <form>

                    <select>
                        <option>Typ</option>
                    </select>

                        <input type="checkbox" id="one"/>First checkbox

                        <input type="checkbox" id="two"/>Second checkbox

                        <input type="checkbox" id="three"/>Third checkbox

        </form>

    </template>

Comment: Thank you. It's working, but I have small error: app.js?id=188beef1eb4f28163bb9:23617 [Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

(found in )
Comment: Often is related to the order of imports, or can be browser cache. Try refreshing browser cash (ctrl + f5) - [src](https://laracasts.com/discuss/channels/laravel/laravel-vuejs-vue-warn-unknown-custom-element-vue-lessons-did-you-register-the-component-correctly-for-recursive-components-make-sure-to-provide-the-name-option-found-in-root)

Alternatively double check docs regarding registration, ensuring your code replicates the correct pattern - [src](https://vuejs.org/v2/guide/components-registration.html#Global-Registration)

Event after click element in Vue


How to read floating point data from a table in EF6

Question: I try to read data from database
  db.Table1.Load();

and get exception
Specified cast is not valid.

StackTrace:
   в System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ)
   в System.Data.SQLite.SQLiteDataReader.GetDouble(Int32 i)
   в System.Data.Entity.Core.Objects.Internal.ShapedBufferedDataRecord.ReadDoubl
e(DbDataReader reader, Int32 ordinal)
   в System.Data.Entity.Core.Objects.Internal.ShapedBufferedDataRecord.Initializ
e(DbDataReader reader, DbSpatialDataReader spatialDataReader, Type[] columnTypes
, Boolean[] nullableColumns)
   в System.Data.Entity.Core.Objects.Internal.ShapedBufferedDataRecord.Initializ
e(String providerManifestToken, DbProviderServices providerServices, DbDataReade
r reader, Type[] columnTypes, Boolean[] nullableColumns)
   в System.Data.Entity.Core.Objects.Internal.BufferedDataReader.Initialize(Stri
ng providerManifestToken, DbProviderServices providerServices, Type[] columnType
s, Boolean[] nullableColumns)
   в System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[T
ResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   в System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResult
s>b__a()
   в System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`
1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, B
oolean releaseConnectionOnSuccess)
   в System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResult
s>b__9()
   в System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult]
(Func`1 operation)
   в System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMerg
eOption)
   в System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.I
Enumerable<T>.GetEnumerator>b__0()
   в System.Lazy`1.CreateValue()
   в System.Lazy`1.LazyInitValue()
   в System.Lazy`1.get_Value()
   в System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   в System.Data.Entity.QueryableExtensions.Load(IQueryable source)

other tables are loaded normally.
like
 db.Table2.Load(); // works just fine, all columns has type string

Table1 has columns with the typedouble but the standard delimiter character in my culture is a comma.
I thought that this should help but does not work either
            System.Threading.Thread.CurrentThread.CurrentCulture =
                System.Globalization.CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture =
                System.Globalization.CultureInfo.InvariantCulture;

I still getting the exception
or am I looking for the error is not where I need it?
Comment: why are you downvoting me?
Comment: Any time you say you "get exception" you have to include the [entire expection](http://idownvotedbecau.se/noexceptiondetails/), not just a word or two you picked out, and include [the code that throws the exception](http://idownvotedbecau.se/nocode/). Also, "does not work" tells us nothing; what does it do? What did you expect it to do?
Comment: @DourHighArch thank you for feedback. That's a full exception message, I would provide more if I could. I wrote line which raise exception. Does not work mean that I still getting exception
Answer: I fixed it. I go to github and saw that VerifyType method is independent of current culture:
case TypeAffinity.Double:
          if (typ == DbType.Single) return affinity;
          if (typ == DbType.Double) return affinity;
          if (typ == DbType.Decimal) return affinity;
          if (typ == DbType.DateTime) return affinity;
break;

I checked the type of columns in database (it wasn't created by me) and it was text. I fixed by setting types to numeric.
I hope it help someone too.


Model selection and comparison in GAMM using R (mgcv)

Question: I'm fitting a GAMM with correlation structure, using a non-Gaussian family. Here's an example of my global model:
M0 <- gamm(response ~ var1*var2 + var3 + s(var4) + s(var5) + s(var6,var7), random=list(placeID= ~1), correlation= corAR1(form= ~ year | placeID), data=data, family=quasipoisson)
I'd like to do term selection on the global model to drop any nonrelevant variables, but I'm not sure how it should be done. Based on the help text of gam.selection - and hoping it applies to GAMM as well! - I've used backward stepwise selection so far. The text says "It is perfectly possible to perform backwards selection using p-values in the usual way". Thus, I've started from the smoothers (removing smoothers from any linear and/or nonsignificant variable) and then moved on to linear variables. I would be interested to hear, whether you think this method is useful in GAMM or not. Please, also tell if you have something else to suggest (e.g. GCV mentioned below).
I would've also liked to compare models that differ in their structure regarding coordinates (smoothed or not, interaction included or not). I suspect that s(latitude,longitude) might be overfitting, and I would like to check this somehow. Since the model uses PQL, I gather that AIC is not recommended (although included in lme part).
The gam.selection text mentions different scores:
"In general the most logically consistent method to use for deciding which terms to include in the model is to compare GCV/UBRE/ML scores for models with and without the term." Is this method only for comparing models that differ by a single variable? If so, do you have any suggestions on how to compare models such as:

M1 <- gamm(response ~ var1*var2 + s(lat,long)+ s(var5), random=list(placeID= ~1), correlation= corAR1(form= ~ year | placeID), data=data, family=quasipoisson)
M2 <- gamm(response ~ var1*var2 + lat + s(var5), random=list(placeID= ~1), correlation= corAR1(form= ~ year | placeID), data=data, family=quasipoisson)

I had been under the impression that my global GAMM-model M0 uses GCV (the default), but when I call gam.check(M0$gam), I only get the four plots and no GCV score or other text output. Is there a way to acquire a GCV score of a GAMM object?
Answer: You are not fitting a GAM but a GAMM. If you look at ?gamm you'll see that there are two options for model fitting an AMM and only one when fitting a GAMM:
  method: Which of '"ML"' or '"REML"' to use in the Gaussian additive
          mixed model case when 'lme' is called directly. Ignored in
          the generalized case (or if the model has an offset), in
          which case 'gammPQL' is used.

As you are fitting with a quasipoisson family, the model fitting hierarchy is:
gamm() ---> MASS::glmmPQL() ---> nlme::lme()

and the likelihood that is optimised is a penalised quasi-likelihood (PQL). As the splines are treated as part fixed and part random effects in this formulation of the GAMM, smoothness selection boils down to using PQL and I am not aware of results that can advise on how well PQL performs in that regard (unlike REML selection with regular GAMs).
If you only need simple random effects, it might be possible to work in the GAM side of things:

In ?magic there is an example of fitting the GAM with correlated data (but in the Gaussian case.
In ?bam there is an option to specify an AR(1) parameter, but again, in the Gaussian case.

You would need to use bs = "re" in an s() term for the random effect.
Comment: If you fit using `gamm()` then yes, that model will be fitted via `glmmPQL()` and use PQL. If you fit using `gamm4::gamm4()` then ML will be used for this model.
Comment: I had not properly acknowledged the differences in the underlying fitting methods of GAM vs GAMM. I infer from your reply, that `gam.selection` and `gam.check` are for GAM alone, not GAMM. From `?gamm`, I now see that only `predict`, `summary`, `print` & `vis.gam` are available for `gammobject$gam`, ie. there's no information on GCV model selection. Hope I got it right now.

So, from my original questions, it remains to be unclear whether the stepwise p-value-based selection is OK for GAMM. I do wish to include a correlation structure, which makes GAM with the bs-option not an ideal solution.
Comment: Does glmmPQL/gammPQL always optimise penalised quasi-likelihood? I am using a gamm with gamma family and I would like know the likelihood that is optimised in that case.


Value of lim $\lim_{n\to\infty}\frac xn \ln\left(\frac{x}{n} \right)$

Question: How can I calculate this limit?
$$\lim_{n\to\infty}\frac xn \ln\left(\frac{x}{n} \right)$$
I think it is a $0 \cdot \infty$ case, but I have no other ideas. I looked again at the properties of $\ln$, thinking that it might help me, but I still didn't figure it out.
Thanks.
Comment: Apply L'Hopital's Rule to $\\lim_{t \to 0}\frac {\ln t} {1/t}$.
Answer: Since $\displaystyle\lim_{x\to0}x\ln(x)=0$, $\displaystyle\lim_{n\to\infty}\frac xn\ln\left(\frac xn\right)=0$.
Answer: Substitute $t:= \frac{n}{x}$, then the limit becomes
$$\lim_{t\to \infty}\frac{\ln\left(\frac{1}{t}\right)}{t} = -\lim_{t\to\infty}\frac{\ln(t)}{t}$$
Now, since $\ln(x) < x$, we have
$$0 \le \frac{\ln(t)}{t} = \frac{2\color{red}{\ln\left(\sqrt t\right)}}{\sqrt t \color{red}{\sqrt t}}\le \frac{2}{\sqrt t}\cdot\color{red}1$$ Therefore,$$
0 \le \frac{\ln(t)}{t} \le \frac{2}{\sqrt t}$$
Finally, by squeeze theorem, we have
$$\lim_{t\to\infty}\frac{\ln(t)}{t} = 0$$
which also means that
$$\lim_{n\to\infty}\frac xn \ln\left(\frac{x}{n} \right)= 0$$
Comment: Actually, $\frac xn\ln\left(\frac xn\right)<0$ if $n>x$.
Comment: @JoséCarlosSantos Thank you. I hope it is correct now $\ddot\smile$
Comment: Thanks for your complete answer. :)


Form in a block with results is the same block

Question: I have a custom module that uses a form in a block that will be displayed on a node page. This form is used to retrieve datas from a custom table.
What I want to achieve is :

The user arrives on the page : the form is displayed and the 10 lasts items retrieved from the database are also displayed
The user selects a data via the form
The user submits the form
The node page containing the block is refresehed with the 10 new items retrieved from database. I also need the form to be displayed on top of the block with previously selected values selected

I've been able to create a form class extending the FormBase class. Then I've created a block extending BlockBase class. In the build method I  get the form using the Drupal::formBuilder()->getForm() method
public function build(){

$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\my_form');

  return array(
      '#theme' => 'my_theme',
      '#form' => $form,
    );
}

At that step, my node page + the block containing the form is correctly displayed, but I've not been able to render the default 10 last items. I've no idea on how to achieve this since the buildForm method of the form class is supposed to return an array to render the form. I've tried to implement it in the build method of my block :
return array(
      '#theme' => 'my_theme',
      '#items' => $items,
      '#form' => $form,
    );

It works, but after form submission, those first 10 default items are always displayed because the block build them on every refresh. Is there a way to know if the included form has been submitted ?
Concerning the form validation, redirection is definitly not the way I should go since a need the results of the database query to be displayed in the same page / block.
Based on this topic, I feel the $form_state->setRebuild() / $form_state->isRebuilding() methods are the way to go. Do you confirm ?
I've been able to refresh the item list after form submission doing so :
  if ($form_state->isRebuilding()) {
  $myfield_value = $form_state->getValue('myfield ');

  $model = Drupal::service('my_module.model');
  $items = $model->getLastItems(10, $myfield_value );

  return array(
    '#theme' => 'my_theme',
    '#form' => $form,
    '#items' => $items,
  );

}
This works, but only half of the time the form is submitted. The second time it's like it never passes in the if($form_state->isRebuilding()) {} statement. Moreover, the results are nested in the form markup. Maybe it's not the proper way to inject the form...
For information here is an example of my twig markup :
{{ form }}

    {% for track in tracks %}
        {# print stuff...#}
    {% endfor %}

To be able to inject the form in the if($form_state->isRebuilding()) statement of the buildForm of the form class, I must wait the form array is completly defined in code... Doing so, I'm unable to set fields values to the ones the user has submitted.
In brief, my questions are :

How can I populate the default items list before the form is submitted ?
How can I properly inject the form from the if($form_state->isRebuilding() statement, so that everything works
How can I set the fields selected values after form submission.

Sorry for this long post, but I'm quite new to the drupal ecosystem, so any help would be greatly appreciated !...
Cheers
PS : I've also read about the BlockBase::blockForm and BlockBase::blockSubmit methods, but as far as I understand, it's more about block configuration froms. Does somebody confirm that ?
Comment: It' difficult to answer, because the fact that the form is in a block is not connected to how to rebuild a form. Better test the form class in a form route and when this works put it in a block. This example might help to understand how forms rebuild: http://drupal.stackexchange.com/questions/223780/how-to-show-a-string-once-you-submit-a-form-in-a-page-reloading-the-page
Answer: Thanks 4k4, the main point I was missing here is that a form is just a specific form of render array... I though it was only possible to define form elements to be rendered. But as you pointed me out, it's possible to define anything one wants to render, like... form result... Since what I need to render is a bit more complicated than simple markup, I've created a new template in my .module file :
function my_module_theme() {
return array(
'my_module_form' => array(
  'variables' => array(
    'form' => array(),
  ),
'template' => 'my-module-form',
),
 'my_module_results' => array(
  'variables' => array(
    'tracks' => array(),
  ),
 }

And then, my buildForm method looks approximately that way :
public function buildForm(array $form, FormStateInterface $form_state) {
// define default values...
$defaultValue = 3;

// define form fied + submit button...
 $form['my_field'] = array(
  '#type' => 'select',
  '#required' => true,
  '#default_value' => $defaultValue,
  '#options' => array(1 => 1, 2 => 2, 3 => 3)
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Go'
);

// define field default value that will be overwritten whe  form is submitted
$my_field_value = 1;

//get submitted value
if ($form_state->isRebuilding()){
    $my_field_value =  $form_state->getValue('my_field');
}

//get datas from database
$results = $model->getResultFromDb($my_field);

 $form['result'] = array(
    '#theme' => 'my_module_results',
    '#results' => $results,
    );

return $form;
}

Then is the "my_module_results" you can use the $results var as in any other template :

  {% for result in results %}

 {{ result.title }}

  {% endfor %}

For the results not to be nested in the "form" markup, I had to build manually the form in its own template and call the result var where I needed the result template to be inserted :

    <form method="{{ form['#method'] }}">
        {{ form.form_build_id }}
        {{ form.form_token }}
        {{ form.form_id }}
        {{ form.my_field }}
        {{ form.submit }}
    </form>

    {{ form.result }}

Not sure it wes the only way to do that, but it works like a charm...
Hope this would help somebody...


Homestead Laravel problema com Drive Postgres

Question: Alguem aqui já teve esse com Homestead e postgreSql? A minha aplicação está dando esse erro.
PDOException
could not find driver
Já procurei em alguns locais mas nada...
Agradeço a ajuda!
Comment: Tentou ativar pelo php.ini? no windows ou linux?
Comment: Já habilitou o driver? em `php.ini`: extension=php_pgsql.dll retire o ";" para habilitar e reinicie o serviço.
Comment: @Edyonil `/etc/php5/apache2/php.ini`. Procure a partir desta pasta. Se estiver utilizando php5-fpm estará dentro da pasta fpm.
Comment: Sou novo com Nginx do Homestead. Onde fica o arquivo php.ini?
Comment: Estou usando o Homestead do jeito que veio. O Meu é Mac OS
Comment: Obrigado juniorb2ss. Descobrir que o problema estava relacionado ao HHVM. Como sou novo com nginx, hhvm e vagrant, estou me mordendo um pouco. Obrigado
Answer: Este erro ocorre pois a extensão não foi encontrada ou esta desativa.
Para ativá-la vá até:
/etc/php5/fpm/

Abra o arquivo php.ini, com editor que preferir.
Procure pela linha: extension=php_pdo_pgsql.dll, caso esteja comentada, ou seja, com ";" no começo, remova-o e reinicie o serviço:
service php5-fpm restart

Caso esteja utilizando apache efetue os mesmo passos, porém, na pasta:
/etc/php5/apache2

Caso não tenha a biblioteca, execute o comando:
apt-get install php5-pgsql

Reinicie o serviço.
Comment: Quando for assim, @Edyonil, você deve postar a solução como resposta da sua própria pergunta. Assim, você evita que a pergunta fique "aberta" (e alguém pense que você não solucionou o problema) e mostra uma solução para quem possa ter o mesmo problema :D
Comment: Ola amigo, já está instalado. Aparentemente é algo com o HHVM, pois reconfigurei Homestead.yaml, removendo o HHVM. Ai funcionou.


Loewner ordering of matrix products

Question: Let $B \geq A \geq 0$ and $M \geq 0$ be real symmetric matrices. Is it true that
$B M B \geq A M A$, i.e., $B M B - A M A \geq 0$?
Answer: No. It is known, for instance, that $B\ge A\ge0$ does not imply $B^2\ge A^2$. Now pick such a pair of matrices $A$ and $B$ and set $M=I$.

Loewner ordering of matrix products


Is there a particular characterization of $Aut(\mathbb{Q}^3)$?

Question: I was considering the group of automorphisms on a vector space $\mathbb{Q}^3$ with the binary operation of addition. Is there a general description of the elements of this group? At first, it seemed to be that it would consist of bijective linear transformations, but I'm not sure how informative that is. Is there a specific category that this automorphism group would fall under?
Comment: @xdfm: it's not clear to me what kind of information you're looking for.  Could you be more specific?  "Bijective linear transformations" is already a pretty good description given how much we know about linear algebra.
Comment: I guess my main concern is, do isomorphisms also have to respect scalar multiplication? I know that they would have to respect addition by definition.
Comment: @xdfm: that was very confusing.  It sounded from your question as if you had already realized this; instead of "I'm not sure how informative that is" shouldn't you have said "I'm not sure how true that is"?
Answer: The distinction between preserving addition and also preserving scalar multiplication is illusory in this case, because any vector can be divided by $n$.
The distinction resurfaces, however, for the same problem with $Q$ replaced by (almost) any other field, such as the real numbers.  There preserving scalar multiplication is an additional property that does not follow from addition being conserved.
Comment: @yunone: multiply everything by the denominator from the start. If a = (p/n)x  then nT(a)=T(na)=T(px)=pT(x).
Comment: Can you explain what you mean by illusory? So if $T$ is an isomorphism, $\alpha$ a scalar, and $v$ a vector, how does $T(\alpha v)=\alpha T(v)$ follow from addition being preserved? As in we could apply $T$ to $(1/\alpha) v$? Why does this fail in the reals? Why can't one divide by any vector by nonzero $r$, as one could do with $n$ in $\mathbb{Q}$?
Comment: Illusory means that the apparent distinction collapses in this case.  Scalar multiplication of x by p/q is expressible in terms of sums of (x/q).  But this is true only for Q.
Comment: Ah, I see what you mean. You would add p terms of (x/q). Thank you.
Comment: Just curious, if $T((p/q)x)=T(\sum_{i=1}^p x/q)=pT(x/q)$, how does the denominator $q$ move outside the operator without assuming scalar multiplication is preserved?
Answer: A vector space over $\mathbb{Q}$ is the same as a torsionfree divisible abelian group. The product $p/q * v$ is the unique vector so that $q * p/q v = p v$. In particular, every group homomorphism between vector spaces over $\mathbb{Q}$ is automatically $\mathbb{Q}$-linear. Thus, for example, the group automorphisms of $\mathbb{Q}^n$ may be described by $GL_n(\mathbb{Q})$.


Tracing Code in Python

Question: def f(x,b):
    global a
    print(x,a-b)
    a = 3
def g(a,b):
    f(b,a)
    print(a,b)
a = 1
b = 2
g(2,a)
print(a,b)

Hey guys so I am fairly new to Python and I have an exam soon. Our teacher requires us to trace code and he said that if we could trace this successfully we would be able to trace anything on the exam as this should be the highest level of difficulty. Can someone please tell me what this function will print and explain how you got there ok? Thank you.
Comment: Just pretend you are a Python interpreter, and execute it on a piece of paper one line at a time, keeping track of all variables and function calls.
Answer: Comments are labeled with their order of exeuction, read them in order of the number in the left
def f(x,b): #4. We get called with (1,2)
    global a #5. Any changes to a will be reflected globally
    print(x,a-b) #6. prints: 1, -1  (1-2)=-1
    a = 3 #change a=3 globally
def g(a,b): #2. this gets called once with g(2,1)
    f(b,a)  #3. so we call f with (1,2)
    print(a,b) #7. prints:(2,1)
a = 1
b = 2
g(2,a) #1. Go to g(a,b)
print(a,b) #8. A was changed to 3 in f(x,b), prints(3,2)

#final output in order:
#1,-1  (from #6)
#2,1   (from #7)
#3,2   (from #8)

Tracing Code in Python


Example of a specific type of infinite group

Question: Give example (if exists) of an infinite non-cyclic group  such that every non-trivial subgroup  of it has  finite index ; off-course the group must be non-abelian ; motivated form $G/H$ is a finite group so $G\cong\mathbb Z$
Comment: @Denis: How is it a duplicate ?? then provide me with the group
Comment: It doesn't @Denis: that answer's examples are of infinite groups with subgroups of obvious infinite index. the OP here wants example(s) of infinite non-cyclic groups all of which proper non-trivial subgroups have finite index.
Comment: duplicate: http://math.stackexchange.com/questions/513700/infinite-group-must-have-infinite-subgroups
Comment: @Denis: Sorry , but there cannot be any abelian examples because if it is abelian , then it is cyclic , but I want non-cyclic
Comment: @SouvikDey. I didn't get your last remark: how do you know that if an infinite *abelian* group has all its proper non-trivial subgroups of finite index then it *must* be cyclic? Writing "...because if it is abelian then it is cyclic" sounds pretty dangerous.
Comment: I don't get why the answer does not fit your requirements. For instance dyadics in $\mathbb Q/{\mathbb Z}$.
Comment: @ Timbuc : The very question I linked shows that "if an infinite abelian group has all its proper non-trivial subgroups of finite index then it must be cyclic"
Answer: I think there is no such group.  First, $G$ is a torsion-free and virtually cyclic.  For, if $g$ is a non-trivial element of $G$, then $\langle g\rangle$ has finite index in $G$, so $G$ is virtually cyclic.  And, since $G$ is infinite, the element $g$ must have infinite order. As $g$ was arbitrary, $G$ is torsion-free.  Also, note that $G$ is finitely generated. (See below.)
Now, if $G = \langle x_1,\ldots, x_n\rangle$, then $C_G(x_i)$ is non-trivial, so it has finite index  in $G$.  Therefore, $Z(G) = \bigcap_{i=1}^n C_G(x_i)$ has finite index in $G$, so the derived subgroup $[G,G]$ of $G$ is finite, by Schur's Theorem.  Since $G$ is torsion-free, it follows that $G$ is abelian.  Now $G$ must be infinite cyclic.
ADDED
Here is the requested proof that $G$ is finitely generated.  We have that $\langle g\rangle$ is a subgroup of finite index in $G$, where $g$ is any non-trivial element of $G$. Therefore, we can write $G$ as the disjoint union of cosets:
$$G = y_1\langle g\rangle\cup y_2\langle g\rangle\cup\cdots\cup y_m\langle g\rangle,$$
for suitable elements $y_1, y_2,\ldots, y_m\in G$, where $m$ is the index of $\langle g\rangle$ in $G$. (We could take, for example, $y_1 = 1\in\langle g\rangle$, but it's not important here.)  This means that an arbitrary element $u$ in $G$ belongs to (exactly) one of those cosets, say, $u\in y_i\langle g\rangle$.  Therefore, $u = y_ig^s$, for some integer $s$.  This shows that every element of $G$ can be written as a product of powers of elements of the set $\{ y_1, y_2,\ldots, y_m, g\}$, so $G$ is generated by this finite set.
(Exercise. Show that a group is finitely generated if it has a finitely generated subgroup of finite index.)
Comment: It is already because $C_G(x_i)$ is a nontrivial subgroup (contains $x_i$!) that it has finite index in $G$.
Comment: @HagenvonEitzen, Indeed! Thanks!
Comment: I think this is an excellent, well written answer. +1
Comment: @James: Could you please just explain why $G$ is finitely generated ? I understand all the other parts except that ; it is really good written
Comment: @SouvikDey. Okay, I've added a proof of this step.  When you get time, you should try the proposed exercise for yourself.  It's very similar; just a bit more complicated.


Is there a way to delete an entire row and shift the cells up in xlwings?

Question: If I wanted to delete an entire row and shift the cells up is there a way to do that? Below is a snippet of my loop which is iterating through the column and clearing the contents of the cell if it doesn't match my parameters. Is there a way rather than clearing just the cell in column A I could delete the whole row and shift up?
<code>    for i in range(lastRow):
        i = i + 1
        if sheet.range('A' + str(i)).value != 'DLQ' or 'DLR':
            xw.Range('A' + str(i)).clear()
            continue
        else:
            continue
</code>
Comment: BigBen - if you're back to edit my post, numpy and pandas reaches a larger audience of people who also use xlwings since using numpy or pandas solely is incredibly unlikely, please leave my tags alone
Answer: Use delete() and specify the rows number(s) you want to delete in range():
<code>import xlwings as xw

wb = xw.Book(r"test.xlsx")

wb.sheets[0].range("2:2").delete()
</code>
This would delete row number 2.
Comment: For those who want to know how to shift up, the line of code @mouwsy provided would end up looking like ```wb.sheets[0].range('2:2').delete(shift='up')```
Comment: That's what I was looking for, thank you, @mouwsy!


Custom alert Sweet Alert

Question: I have this alert made with JavaScript. It is a simple alert which show a box: Sure to Delete ID no = ..  and show a button ok or cancel
I want to convert this alert into a sweet alert. How I can do that?
CODE :
<code>$(document).ready(function(){
$(".delete-link").click(function()
{
    var id = $(this).attr("id");
    var del_id = id;
    var parent = $(this).parent("td").parent("tr");
    if(confirm('Sure to Delete ID no = ' +del_id))
    {
        $.post('delete.php', {'del_id':del_id}, function(data)
        {
            parent.fadeOut('slow');
        });
    }
    return false;
});
});
</code>
Comment: http://google.it ! you have to show at least some efforts...
Answer: <code>         swal({
        title: "Are you sure?",
        text: "Text here.",
        icon: "warning",
        buttons: [
            "No, don't do that!",
            'Yes, do that'
        ],
        dangerMode: true,
    }).then(function (isConfirm) {
        if (isConfirm) {

        swal({
            title: 'Done',
            text: 'Your task has been done!',
            icon: 'success'
        })

        } else {
            swal("Not done", "your task has not been done", "error");
        }
</code>
Answer: Try with following:
<code>$(document).ready(function(){
$(".delete-link").click(function(e))
{
    e.preventDefault();
    var id = $(this).attr("id");
    var del_id = id;
    var parent = $(this).parent("td").parent("tr");
    swal({
      title: "Are you sure?",
      text: "Sure to Delete ID no = " + del_id,
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, delete it!",
      closeOnConfirm: false
    },
    function(){
      $.post('delete.php', {'del_id':del_id}, function(data)
        {
            parent.fadeOut('slow');
        });
    });
});
});
</code>
Ref: http://t4t5.github.io/sweetalert/

Custom alert Sweet Alert


Plotly chart using Javascript curve issue

Question: I want to make step chart has curved line using plotly.js.
The difference between the connecting parts is felt differently depending on the size of the currently different numerical value.
The thickness of the curve path is also different.
And want to hide Xaxis and Yaxis divide lines.
I want to make the whole chart look perfect while making it the same.
Like this image.
enter image description here

<!DOCTYPE html>

Comment: Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: Yup. I solved the issue myself.
Plotly.js had solutions.

<!DOCTYPE html>


I'm learning R. I was wondering how I could make a barplot with a data set I've made?

Question: Here is the data I've made:
    structure(list(Resort = c("Park City", "Powder Mountain", "Snowbird",
    "Alta", "Snow Basin", "Deer Valley"), `Named Runs` = c(348, 154,
    140, 116, 107, 103)), row.names = c(NA, -6L), class = c("tbl_df",

"tbl", "data.frame"))
Here is my code. I'm trying to get a bar graph, with resorts on the x-axis and named runs on the y-axis. Unfortunately, my graph is only showing resorts. How can I fix this? Thanks.
    library(readxl)
    Utah_ski_resort_data_ <- read_excel("Desktop/Utah ski resort data..xlsx")
    View(Utah_ski_resort_data_)
    table(Utah_ski_resort_data_$Resort)
    table(Utah_ski_resort_data_$`Named Runs`)
    barplot(table(Utah_ski_resort_data_$Resort)

Comment: It's hard to tell what is wrong when we can't see your data or the errors you are getting, but generally `:` is a special character and isn't allowed in standard column names, so any time you use `$Resort:` that will be a syntax error. I'd suggest cleaning the column names so you can use standard R syntax with them. You can do that with `names(Utah_ski_resort_data_) <- make.names(names(Utah_ski_resort_data_))`.
Comment: If you need more help than that, please post a little sample data, e.g., `dput(Utah_ski_resort_data_[1:10, ])` for the first 10 rows, and also post the first error you get.
Answer: barplot with formula:
barplot(`Named Runs` ~ Resort, Utah_ski_resort_data_)

And this is a ggplot2 barplot:
library(ggplot2)
library(dplyr)
Utah_ski_resort_data_ %>%
  ggplot(aes(x = Resort, y = `Named Runs`)) +
  geom_bar(stat = "identity")


Drupal 8: Template suggestion for form-element in a views exposed filter is not working

Question: In Drupal 8 I am trying to add in a suggestion via hook_theme_suggestions_alter() like so:
function ua_sc_theme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  print '';
  if (in_array($hook, ['input', 'form_element']) && $variables['element']['#attributes']['id'] == 'edit-keys') {
    $suggestions[] = $hook . '__custom';
  }
}

...and then I give my template a name of form-element__custom.html.twig and put it in my theme it doesn't get used an instead the default form-element.html.twig template is used. Any thoughts on what is going on?
Answer: Ok, looks like I was too tired. The problem was that the template should be called form-element--custom.html.twig.
Notice the '--' (double dash) instead of the __ (double underscore).
I also ended up using the more specific hook alter:
hook_theme_suggestions_HOOK_alter

...where HOOK for me was form_element.
Answer: In your form add '#theme' => 'input__custom' to the input element. The 'input' is the theme implementation and '__custom' is the suggestion.
This hook is for global suggestions.
Comment: I am trying to theme an exposed view filter form element - so I would need to do that in an alter. Is there no other way?
Comment: There is nothing wrong with using hook_form_alter or hook_form_FORM_ID_alter in this case.


Python if/elif statement not working correctly

Question: Please help understand what is wrong with the code below. The code works fine if I pass values up to 34. Once I pass 35 or higher, the output is incorrect.
tuk=0
if tuk <= 24:
    print ('The text is very easy to read.')
elif tuk >= 25 & tuk <= 34:
    print('The text is easy to read.')
elif tuk >= 35 & tuk <= 44:
    print('The text is moderately difficult to read.')
elif tuk >= 45 & tuk <= 54:
    print('The text is difficult to read')
elif tuk >= 55:
    print('The text is very difficult to read')
else:
    print('This is beyond')

Comment: `&` is the bitwise operator. You want `and` - the logical operator
Answer: Your code is correct, but changing the "&" to "and" because "&" is a bitwise logical operator, not a logical one.
For example:

z = 0 := 0b000
a = 1 := 0b001
b = 2 := 0b010
c = 3 := 0b011
d = 4 := 0b100

now the result of the expression (a & c) is 0b001 or 1
but in logical expression (a and c) the result will be true, which I suppose you are interested in.


Kubernetes cronjob run multiple processes at the same time without creating multiple jobs

Question: I have a Python process that I want to fire up every n minutes in a Kubernetes cronjob and read a number of messages (say 5) from a queue, and then process/convert some files and run analysis on results based on these queue messages. If the process is still running after n minutes, I don't want to start a new process. In total, I would like a number of these (say 3) of these to be able to run at the same time, however, there can never be more than 3 processes running at the same time. To try and implement this, I tried the following (simplified):
apiVersion: batch/v1
kind: CronJob
metadata:
  name: some-job
  namespace: some-namespace
spec:
  schedule: "*/5 * * * *"
  concurrencyPolicy: "Forbid"
  jobTemplate:
    spec:
      parallelism: 3
      template:
        spec:
          containers:
          - name: job
            image: myimage:tag
            imagePullPolicy: Always
            command: ['python', 'src/run_job.py']

Now what this amounts to is a maximum of three processes running at the same time due to 'parallelism' being 3, and concurrencyPolicy being "Forbid", even if the processes go over the 5 minute mark.
The problem I specifically have is that one pod (e.g. pod 1) can take longer than the other two to finish, which means that pod 2 and 3 might finish after a minute, while pod one only finishes after 10 minutes due to processing of larger files from the queue.
Where I thought that parallelism: 3 would cause pod 2 and 3 to be deleted and replaced after finishing (when new cron interval hits), they are not and have to wait for pod 1 to finish before starting three new pods when the cron interval hits again.
When I think about it, this functionality makes sense given the specification and meaning of what a cronjob is. However, I would like to know if it would be able to have these pods/processes not be dependent on one another for restart without having to define a duplicate cronjob, all running one process.
Otherwise, maybe I would like to know if it's possible to easily launch more duplicate cronjobs without copying them into multiple manifests.
Comment: Duplicate cronjobs seems to be the way to achieve what you are looking for. Produce 3 duplicates with single job at a time. You could template the job manifest and produce multiple as in the following example. The example is not in your problem context, but you can get the idea.https://kubernetes.io/docs/tasks/job/parallel-processing-expansion/
Comment: @gordanvij This seems to be exactly what I'm looking for. Thanks for the info
Comment: @ gordanvij, please post the provided comment as a solution for the greater visibility of the community.
Comment: Thank you @Srividya for reminding. Tim, please mark as answered if you are good with it.
Answer: Duplicate cronjobs seems to be the way to achieve what you are looking for. Produce 3 duplicates with single job at a time. You could template the job manifest and produce multiple as in the following example. The example is not in your problem context, but you can get the idea.
http://kubernetes.io/docs/tasks/job/parallel-processing-expansion


Let window grow based on one control's size but not the other's

Question: I've got a window containign a textblock with variable text and a stackpanel which contains a variable amount of buttons.

How can I let the window grow in width (horizontally), when the stackpanel grows in width but let the text always adapt to the available width (not grow the window in width when the text gets longer).
I've tried some combinations with and without Width="Auto" / VerticalAlign="Stretch" / TextWrapping etc. but I only get the window to grow if either one (text length / stackpanel children) grow in width.
I want the text to wrap based on the width of the window which shall be based on the width of the stackpanel. XAML only would be nice.
Edit
As requested some stripped-down markup to reproduce the issue:
<Window
    Width="500"
    Height="225"
    MinWidth="500"
    MinHeight="225"
    HorizontalAlignment="Stretch"
    SizeToContent="WidthAndHeight"
    ResizeMode="NoResize">

    <Grid HorizontalAlignment="Stretch" Width="Auto">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="35"/>
        </Grid.RowDefinitions>

        <ScrollViewer Grid.Row="0" Margin="15" VerticalScrollBarVisibility="Auto">
            <TextBlock TextWrapping="Wrap" Height="Auto">...Some Binding...</TextBlock>
        </ScrollViewer>

        <StackPanel x:Name="ButtonStackPanel" Grid.Row="1" FlowDirection="RightToLeft" Orientation="Horizontal" Width="Auto">
            ...Some Buttons...
        </StackPanel>
    </Grid>
</Window>

Edit 2
The window is supposed to have a MinWidth of 500, if there's only one button in the stackpanel, it should still stretch full width (500px).
Edit 3 - Some more pictures
Correct - Text is short, only one button -> MinWidth 500

Wrong - Text is long and should wrap at the MinWidth of 500 because only the Stackpanel should be allowed to grow the window in width

Correct - Short text but stack panel grows the window
Comment: Please post some XAML markup that can be used to reproduce your issue. How wide is the TextBlock supposed to be?
Comment: @mm8 as I wrote in the second and fourth paragraph, as wide as it can be. But it should not grow the window. Only the stackpanel should grow the window's width.
Comment: @mm8 markup added
Comment: You can bind `MaximumWidth` of one control to `ActualWidth` of another.
Answer: You have to bind the Width of the Window to the outer Grid's Width (as Mighty Badaboom suggested) and the Width of the ScrollViewer to the ActualWidth of your StackPanel.
Here is how you can achieve it:
<Window SizeChanged="MainWindow_OnSizeChanged" Height="225" SizeToContent="Width" ResizeMode="NoResize">
<Grid Name="OuterGrid" MinWidth="500">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="35"/>
    </Grid.RowDefinitions>

    <ScrollViewer Grid.Row="0" Margin="15" VerticalScrollBarVisibility="Auto">
        <TextBlock TextWrapping="Wrap" Height="Auto">...Some Binding...</TextBlock>
    </ScrollViewer>

    <StackPanel Grid.Row="1" HorizontalAlignment="Stretch" Background="Blue">
        <StackPanel x:Name="ButtonStackPanel" HorizontalAlignment="Center" Grid.Row="1" FlowDirection="RightToLeft" Orientation="Horizontal" Width="Auto">
            ...Some Buttons...
        </StackPanel>
    </StackPanel>
</Grid>
</Window>

And code behind:
private void MainWindow_OnSizeChanged(object sender, SizeChangedEventArgs e)
{
    if (e.WidthChanged)
        OuterGrid.Width = Panel.ActualWidth;
}

EDIT: Added an outer StackPanel to support Stretching & blue Background requirement.

EDIT 2: It seems that you can't achieve the behavior you're describing with only XAML. Although the fix is a few lines of code away.
Comment: Good idea but I would suggest binding the window width to the outer `Grid` instead of the `StackPanel`because you could get in trouble when adding margins.
Comment: Hmm, what the blue background has to do with the stretching? can you update your question with an example please?
Comment: @SlapY You can use an outer StackPanel for that purpose. I updated my answer.
Comment: @SlapY It seems that you can't achieve that exact behavior without some code behind. I updated my answer.
Comment: Like most of the `outer.Width = inner.ActualWidth` approaches, this will work for growing data, but the size will not shrink if a button is removed, unless some different size change is triggering the event. So as long as the layout is not dynamically shrinking, this will work fine, otherwise be more careful regarding the event source for `SizeChanged`.
Comment: I need the stack panel to have HorizontalAlignment=Stretch and this somehow leads to infinite width :D
Comment: @SlapY Yep, this leads to infinite width. Why you need it?
Comment: @GeorgeChond It's basically a message box and the lower part should have a blue background. It therefore needs to stretch.
Comment: @GeorgeChond Actually the original window is a bit more complex. I need the bottom row (StackPanel in this example) to be full width of the window and feature a blue background. Your suggestion does not stretch the whole width.
Comment: @GeorgeChond Thanks, I'm trying it. Meanwhile I added some more pictures above to clarify. There's actually already a border with blue background around the stack panel
Comment: Yep! That's it, thanks. I just had to factor in the MinWidth: OuterGrid.Width = Math.Max(this.MinWidth, ButtonStackPanel.ActualWidth);
Answer: You could write your own custom control and override measure/arrange in a way that width and height is dominated by different child elements. Note I'm cheating a bit here by just using the first two children of a panel and giving them a different meaning based on your question, without even checking for valid child indices first etc.:
public class SizeAwareControl : Panel
{
    private UIElement HeightDeterminingContent
    {
        get { return InternalChildren[0]; }
    }
    private UIElement WidthDeterminingContent
    {
        get { return InternalChildren[1]; }
    }

    protected override Size MeasureOverride(Size constraint)
    {
        Size result = new Size(double.PositiveInfinity, double.PositiveInfinity);

        WidthDeterminingContent.Measure(result);

        result.Width = WidthDeterminingContent.DesiredSize.Width;

        HeightDeterminingContent.Measure(result);

        result.Height = WidthDeterminingContent.DesiredSize.Height + HeightDeterminingContent.DesiredSize.Height;

        return result;
    }
    protected override Size ArrangeOverride(Size arrangeBounds)
    {
        HeightDeterminingContent.Arrange(new Rect(0, 0, WidthDeterminingContent.DesiredSize.Width, HeightDeterminingContent.DesiredSize.Height));
        WidthDeterminingContent.Arrange(new Rect(0, HeightDeterminingContent.DesiredSize.Height, WidthDeterminingContent.DesiredSize.Width, WidthDeterminingContent.DesiredSize.Height));
        return new Size(WidthDeterminingContent.DesiredSize.Width, WidthDeterminingContent.DesiredSize.Height + HeightDeterminingContent.DesiredSize.Height);
    }
}

Usage
<local:SizeAwareControl>

    <ScrollViewer Margin="15" VerticalScrollBarVisibility="Auto" MaxHeight="600">
        <TextBlock TextWrapping="Wrap" Height="Auto">...Some Binding...</TextBlock>
    </ScrollViewer>

    <StackPanel x:Name="ButtonStackPanel" Orientation="Horizontal" MinWidth="500">
        <Button Width="100" Content="..." Click="MenuItem_Click"/>
        <Button Width="100" Content="..."/>
        <Button Width="100" Content="..."/>
    </StackPanel>
</local:SizeAwareControl>

This is just a starting point - you may need some more detailed logic to determine good width and height values. The MaxHeight on the first child enables scrolling for long text (instead of growing a very tall window) and the MinWidth on the second child ensures width for a low amount of buttons.


Why can't I import pybacktest package?

Question: I checked the method of importing this package on the Internet, and I also entered the pip command in cmd, but it still cannot be imported. May I ask why?
Answer: Probably because the kernel of your jupyterhub has not the right environment.
Try to reinstall the package using the terminal of jupyter hub (see new drop box) it will do the trick once you have installed the package and refreshed the kernel.
Answer: Try this on your Jupyter cell:
pip install git+https://github.com/ematvey/pybacktest.git

Link to github  https://github.com/ematvey/pybacktest
Edit for your comment:
run the below command on your Jupyter cell.
pip install pandas_datareader

Comment: Hello, I tried to enter the command you said, but another error message popped up, how can I debug ?

ImportError: No module named 'pandas_datareader'
Comment: what is the message?
Comment: @JeffHung now check if `data_reader` works for you?
Comment: @TalhaTayyab, please don't recommend using an exclamation point with `pip` or `conda` any longer. Always suggest using the magic indicator in front of pip, so `%pip install ...`. Your advice is outdated if you are suggesting the exclamation point. Magics were added recently so that installations from within a notebook get installed to **the correct** environment backing the notebook. Exclamation point was causing all sorts of problems. See [here](https://discourse.jupyter.org/t/why-users-can-install-modules-from-pip-but-not-from-conda/10722/4?u=fomightez) about these modern magic commands.
Comment: @TalhaTayyab , often no symbol is also better in front of `pip` or `conda` than an exclamation point these days inside a cell in a notebook because automagics are usually on by default in modern installations these days. And so without any symbol, the modern magic command gets used by default.

Why can't I import pybacktest package?


Factorization of polynomial over R

Question:
Here is my question related to the factorization of polynomials over R. I have 2 questions regarding my highlighting text.
1)The first highlight: I don't understand why if we can prove $q(x)$ has real coefficients, then it will have as much $(x-\overline{\lambda})$ as $(x-\lambda)$.
2)The second highlight: Why $x$ can be in $R$ only ? What if $x\in C$ ?
Comment: The second highlight means $q(x)$ is real if $x$ is real. It does not mean $x$ can be in $\mathbb R$ only.
Comment: I mean $q(x)=1+x$ has real coefficients even if $x$ can be complex. That is, the coefficients of a polynomial do not depend on the variable.
Comment: According to what you mention, as from my understanding, he is stating the statement
"If $x\in R,$ then $q(x)$ has real coefficients." What if the case if $x\in C?$, Will $q(x)$ has real coefficients? Does this affect the proof that q(x) has real coefficients?
Comment: Is the coefficient of a polynomial dependent on its variable?
Comment: yes. every polynomial has unique coefficients.
Comment: Let me clarify one thing with you in order to make sure I fully understand it.
Does that mean the author just selects $x\in R$ and hence he get $q(x)$ has real coefficients of the form $q(x)=a_0+\cdots+a_{m-2}x^{m-2}$ where $a_j\in R$. Then from here, even if we have $x\in C$, this polynomial is still valid right? ( as this polynomial is unique, it can't have different coefficients with different $x$ )
Comment: Yes, that is what I think the author is saying.
Comment: Thanks for the clarification.
Answer: There are as many $(x-\overline{\lambda})$ as $(x-\lambda)$ because $(x-\overline{\lambda})(x-\lambda)$ will have only real coefficients.
Let $\lambda:=a+bi$, then $\overline{\lambda}=a-bi$, so:
$$(x-\overline{\lambda})(x-\lambda)=x^2-\lambda x-\overline{\lambda}x+\overline{\lambda}\lambda=x^2-x(\lambda+\overline{\lambda})+\overline{\lambda}\lambda$$
Now, $\lambda+\overline{\lambda}=2a \in \mathbb{R}$, and $\overline{\lambda}\lambda=a^2+b^2 \in \mathbb{R}$
So if there is no $(x-\overline{\lambda})$ for a $(x-\lambda)$, then the polynom will look like this: $Q(x)=(x-\lambda)P(x)$, where $P(x)$ has only real coefficients. $Q(x)=(x-\lambda)P(x)=(x-a-bi)P(x)=xP(x)-aP(x)-ibP(x)$. Now, $xP(x)$ and $aP(x)$ has real coefficients only, but the $-ibP(x)$ has only imaginary, so $Q(x)$'s coefficients are not real.
Comment: I don't really get what you mean. What I asked is, why $q(x)$ has real coefficients implies that there are as many $(x-\overline{\lambda})$ as $(x-\lambda)$?
Comment: @LingMinHao Did you read the whole answer?
Comment: @LingMinHao Multiplying a polynom with real coefficients by $(x-\lambda)=(x-a-bi)$ will result a polynom with complex coefficients. The only way you can make it real again is to multiply it by $(x-\overline{\lambda})$, because that will make the $(x-\lambda)(x-\overline{\lambda})$ real.
Comment: @LingMinHao Why can only $(x-\overline{\lambda})$ make $(x-\lambda)$ real? Because $(x-z_1)(x-z_2)=x^2-x(z_1+z_2)+z_1z_2$ and we want both $z_1+z_2$ and $z_1z_2$ to be real. From the first: $a_1+b_1i+a_2+b_2i=(a_1+a_2)+i(b_1+b_2)$. The only way for it to be real is the $b_1+b_2=0$. For the second condition: $a_1a_2+a_1b_2i+a_2b_1i-b_1b_2$, we can see that $a_1b_2+a_2b_1$ must be zero. but $b_1=-b_2$, so $-a_1b_1+a_2b_1$ must be zero, so $a_1=a_2$. So it's only possible with $z_1=a_1+b_1i$ and $z_2=a_1-b_1i=\overline{z_1}$.
Comment: Thanks for the explanation. It is clearer for me now.

Factorization of polynomial over R


Exercício URI 1012 - Wrong answer 20%

Question: Fiz o exercício, quase todas as saídas estão saindo como o output do URI estão pedindo, porém a primeira exigência não está como pede no programa. Usei o setprecision, mas estou na dúvida o porque o primeiro resultado não arredonda 3 casas decimais depois da vírgula.
a 3.0
b 4.0
c 5.2

TRIANGULO: 7.800
CIRCULO: 84.949
TRAPEZIO: 18.200
QUADRADO: 16.000
RETANGULO: 12.000

a minha primeira saída TRIANGULO sai apenas 7.8 e as demais saem perfeitamente.
#include <iostream>
#include <iomanip>
#include <math.h>

int main(int argc, char** argv)
{
    double pi = 3.14159;
    double a, b, c;
    double area_triangulo, area_circulo, area_trapezio,
    area_quadrado,area_retangulo;

    std::cin >> a >> b >> c;

    area_triangulo = a * c / 2;
    area_circulo = pi * pow(c, 2);
    area_trapezio = ((a + b)* c)/2;
    area_quadrado = pow(b, 2);
    area_retangulo = a * b;

    std::cout << "TRIANGULO: " <<area_triangulo << std::setprecision(5)<<
    std::fixed << std::endl;
    std::cout << "CIRCULO: " <<area_circulo << std::setprecision(3)<<
    std::fixed << std::endl;
    std::cout << "TRAPEZIO: " <<area_trapezio << std::setprecision(3)<<
    std::fixed << std::endl;
    std::cout << "QUADRADO: " <<area_quadrado << std::setprecision(3)<<
    std::fixed << std::endl;
    std::cout << "RETANGULO: " <<area_retangulo << std::setprecision(3)<<
    std::fixed << std::endl;

    return 0;
}

Answer: O std::fixed indica que as escritas seguintes serão feitas com notação de ponto fixo. A quantidade de dígitos mostrados depois da virgula é definida com setprecision.
Se pretende mostrar 3 dígitos depois da virgula deve utilizar:
std::setprecision(3);

Deve utilizar std::fixed e set::setprecision antes de escrever qualquer saída numérica e apenas uma única vez:
std::cout << std::fixed << std::setprecision(3);
std::cout << "TRIANGULO: " <<area_triangulo << std::endl;
std::cout << "CIRCULO: " <<area_circulo << std::endl;
std::cout << "TRAPEZIO: " <<area_trapezio << std::endl;
std::cout << "QUADRADO: " <<area_quadrado << std::endl;
std::cout << "RETANGULO: " <<area_retangulo << std::endl;

Veja o resultado no Ideone
Comment: Obrigado Isac, em Python eu estava acostumado a fazer a formatação saída por saída. Agradecido irmão.

Exercício URI 1012 - Wrong answer 20%


Como alterar 2 ou mais colunas ao mesmo tempo no Sql Server 2014? (ALTER TABLE/ALTER COLUMN)

Question: Como faço para alterar 3 colunas ao mesmo tempo na tabela do SQL SERVER?
Quero alterar o COLLATION, mas poderia ser outra coisa.
Tentei:
ALTER TABLE dbo.SIX_POSTO
ALTER COLUMN VIS_DS VARCHAR(200) COLLATE Latin1_General_CI_AI NOT NULL,
ALTER COLUMN VIS_DS_OBSERVACAO VARCHAR(200) COLLATE Latin1_General_CI_AI
NULL,
ALTER COLUMN VIS_DS_ENDERECO VARCHAR(500) COLLATE Latin1_General_CI_AI
NULL

Tentei também:
ALTER TABLE dbo.SIX_POSTO
ALTER COLUMN VIS_DS VARCHAR(200) COLLATE Latin1_General_CI_AI NOT NULL,
COLUMN VIS_DS_OBSERVACAO VARCHAR(200) COLLATE Latin1_General_CI_AI NULL,
COLUMN VIS_DS_ENDERECO VARCHAR(500) COLLATE Latin1_General_CI_AI NULL

E também:
ALTER TABLE dbo.SIX_POSTO
ALTER COLUMN VIS_DS VARCHAR(200) COLLATE Latin1_General_CI_AI NOT NULL,
VIS_DS_OBSERVACAO VARCHAR(200) COLLATE Latin1_General_CI_AI NULL,
VIS_DS_ENDERECO VARCHAR(500) COLLATE Latin1_General_CI_AI NULL

Mas só funciona assim:
ALTER TABLE dbo.SIX_POSTO
ALTER COLUMN VIS_DS VARCHAR(200) COLLATE Latin1_General_CI_AI NOT NULL
ALTER TABLE dbo.SIX_POSTO
ALTER COLUMN VIS_DS_OBSERVACAO VARCHAR(200) COLLATE Latin1_General_CI_AI
NULL
ALTER TABLE dbo.SIX_POSTO
ALTER COLUMN VIS_DS_ENDERECO VARCHAR(500) COLLATE Latin1_General_CI_AI
NULL

Para cada ALTER TABLE só pode existir um ALTER COLUMN?
Answer: Você pode fazer mais de um comando para adicionar ADD ou remover DROP COLUMN, mas não pode para o ALTER COLUMN. O comando ALTER TABLE não permite que você faça mais de um ALTER COLUMN, ou seja, você precisará fazer um ALTER TABLE para cada alteração de coluna que tiver que ser feita.


How Can I Arrive at the Fee-Adjusted APR, Accounting for Balance Transfer Fee (But Not Inflation)?

Question: I'm trying to figure out the fee-adjusted interest rate paid when incurring a balance transfer fee on a loan, not accounting for inflation.
If the APR is 4%, the loan 5000, the transfer 2% and you pay it off in 200 days (54.8% of the year when rounded to 2 decimals), I see it this way:
(APR: 4%  Loan: 5,000  Transfer fee: 2%  Days: 200)
Present Value: 4,900  (Loan - transfer fee %)
Future Value: 5,109.589041095890411 (loan * ( APR * (200/365) ) )
Real Rate Over 200 Days: 4.2773273693039%  ( (FV - PV) / PV )
Real Rate Over 365 days: 7.806122448979618% ( ( (FV - PV) / PV ) * (365/200) )
Is there something missing and if so, what?
Comment: If *real* does not mean *adjusted for inflation*, does it just mean *including fee*? Also 200 is not 5.48% of the year.
Answer: I would expect the amount to be paid after 200 days to be $$5000 \times 1.04^{200/365} \approx 5108.617$$ so the effective interest rate including fees over 200 days to be $$\frac{5108.617}{5000\times 0.98}-1 \approx  4.2575\%$$ and the annualised effective interest rate including fees to be $$\left(\frac{5108.617}{5000\times 0.98}\right)^{365/200}-1 \approx 7.9060\%$$
and these numbers are close to but not the same as yours.


Application Settings outside of web.config

Question: I need to keep the production app settings section outside of Web.config; I don't want keys and other secret information to be kept inside source code repository. However, if I edit the app settings with IIS Mananger it changes the Web.config, which will be overwritten at the next deployment.
How can I keep those settings outside of the Web.config that comes with the application on deployment? For example, this is somehow done by Azure Web Sites - the app settings you configure in the portal are not stored in Web.config - that can be confirmed by downloading the file via FTP. How is it done?
Answer: For the appSettings and connectionStrings nodes in web.config you can move these into separate files outside of web.config.
In your web.config you would have:
<appSettings configSource="appsettings.config"></appSettings>

and then a new file appsettings.config:
 <?xml version="1.0"?>
 <appSettings>
     <add key="foo" value="bar" />
 </appSettings>

Then you have to make sure that you don't deploy these new files and keep them different on the production server and your dev environment.
All my web.config files are excluded from my deployment process, if I need to change them, I do that on the stage or production sites.
Answer: In addition to the web.config file(s) in your sites there are several global settings for IIS.
%systemroot%\System32\inetsrv\config\applicationHost.config

has all the global IIS settings, depending on your Feature Delegation settings these can be overwritten in your local web.config(s). But you can prevent this by setting a feature to 'Read Only' in Feature Delegation on the server level.
For dot.NET related settings there are two global files:
%systemroot%\Microsoft.NET\Framework??\v?.?.????\CONFIG\machine.config
%systemroot%\Microsoft.NET\Framework??\v?.?.????\CONFIG\web.config

There are several versions of these files, one for each framework version for each OS platform.
Any settings done in these files are inherited by your local web.config.
However I don't think there is a way that you can prevent a local web.config from overriding settings set in the global files.
Comment: Those will be global across all sites in IIS. What I need is a way to store per-site settings without having them overwritten when redeploying.


Deselect checkboxes based on dropdown select value in ProComponents React

Question: Resources for ProComponents that are being used in this demo.

ProForm same properties as ProModal
ProFormCheckBox.Group
ProFormSelect

I am trying to deselect all checkboxes every time I select a new item.
So for example if I select PCA from the dropdown and checked boxed 2.
Example 1
Then switched over to LSCA from the dropdown I want to deselect all checkboxes.
Example 2
Instead, what happens check box 2 is still selected.
Example 3
I have it set where each dropdown item has a different list of checkboxes set into it.
They are four different arrays. The more interesting parts are the three different useState. One controls the state of which dropdown item is selected. Another controls the state of which array of checkboxes should be displayed.  The last controls the state of which checkboxes should be marked. Notes of interest in the code are
  // Controls the state of the dropdown menu to be selected
  const [selected, setSelected] = useState('');
  // Controls the state of which array of checkboxes should be displayed
  const [checkBoxes, setCheckBoxes] = useState([]);
  // Controls the state of which checkboxes are checkmarked
  const [markedCheckBoxes, setMarkedCheckBoxes] = useState([]);

Next code of interest is the function changeSelectOptionHandler which is run onChange of the  ProFormSelect. This should run setMarkedCheckBoxes to set the state into an empty array so no boxes are selected.
  /** Function that will set different values to state variable
   * based on which dropdown is selected
   */
  const changeSelectOptionHandler = (event) => {
    // This should set the state of the setMarkedCheckBoxes to be empty
    setMarkedCheckBoxes([]);
    // Sets the state of which array of checkboxes should be displayed based on event
    checkBoxOptions(event);
    // Sets the state of which dropdown is selected based on the event
    setSelected(event);
  };

According to the docs I should set the value as what checkBoxes should be marked in ProFormCheckbox.Group
  <ProFormCheckbox.Group
    name="rows"
    label="Select Rows"
    options={checkBoxes}
    onChange={(e) => {
      console.log('state changes');
      setMarkedCheckBoxes(e);
    }}
    // This is where I set which checkboxes should be marked with value
    // initialValue={markedCheckBoxes}
    value={markedCheckBoxes}
  />

I was able to use the React Dev Tools and confirm values are updated for markedCheckBoxes based on when a new dropdown item is selected which should be an empty array. I also tested that when I cancel or submit the modalForm that markedCheckBoxes is an empty array and is correctly displayed with setting the value on the ProFormCheckbox.Group. So I am stumped on how to correctly display what is on the value in ProFormCheckbox.Group after updating the select menu. Below is the full code snippet of said RowModal component.
import { PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import { useState } from 'react';

import ProForm, { ModalForm, ProFormSelect, ProFormCheckbox } from '@ant-design/pro-form';
import { updateRule } from '@/services/ant-design-pro/api';

const RowModal = ({ orderId, actionRef }) => {

  /** Different arrays for different dropdowns */
  const eca = ['1', '2', '3', '4', '5'];
  const pca = ['1', '2'];
  const lsca = ['1', '2', '3', '4', '5', '6'];
  const mobility = ['1', '2', '3', '4'];

  // Controls the state of the dropdown menu to be selected
  const [selected, setSelected] = useState('');
  // Controls the state of which array of checkboxes should be displayed
  const [checkBoxes, setCheckBoxes] = useState([]);
  // Controls the state of which checkboxes are checkmarked
  const [markedCheckBoxes, setMarkedCheckBoxes] = useState([]);

  /** Function that will set different values to state variable
   * based on which dropdown is selected
   */
  const changeSelectOptionHandler = (event) => {
    // This should set the state of the setMarkedCheckBoxes to be empty
    setMarkedCheckBoxes([]);
    // Sets the state of which array of checkboxes should be displayed based on event
    checkBoxOptions(event);
    // Sets the state of which dropdown is selected based on the event
    setSelected(event);
  };

  /** This will be used to create set of checkboxes that user will see based on what they select in dropdown*/
  const checkBoxOptions = (event) => {
    /** Setting Type variable according to dropdown */
    if (event === 'ECA') setCheckBoxes(eca);
    else if (event === 'PCA') setCheckBoxes(pca);
    else if (event === 'LSCA') setCheckBoxes(lsca);
    else if (event === 'Mobility') setCheckBoxes(mobility);
    else setCheckBoxes([]);
  };

  return (
    <ModalForm
      title="Assign to Area and Row"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          Assign
        </Button>
      }
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setSelected('');
          setCheckBoxes([]);
          setMarkedCheckBoxes([]);
        },
      }}
      onFinish={async (values) => {
        const newValues = { ...values, order: orderId };
        const req = await updateRule('http://127.0.0.1:3000/api/v1/floorPlans', {
          data: newValues,
        });

        message.success('Success');
        setSelected('');
        setCheckBoxes([]);
        setMarkedCheckBoxes([]);
        actionRef.current?.reloadAndRest?.();
        return true;
      }}
      // initialValues={{ rows: ['A'] }}
    >
      <ProForm.Group>
        <ProFormSelect
          request={async () => [
            {
              value: 'PCA',
              label: 'PCA',
            },
            {
              value: 'ECA',
              label: 'ECA',
            },
            {
              value: 'LSCA',
              label: 'LSCA',
            },
            {
              value: 'Mobility',
              label: 'Mobility',
            },
          ]}
          // On change of dropdown, changeSelectOptionHandler will be called
          onChange={changeSelectOptionHandler}
          width="xs"
          name="area"
          label="Select Area"
          value={selected}
        />
      </ProForm.Group>
      <ProFormCheckbox.Group
        name="rows"
        label="Select Rows"
        options={checkBoxes}
        onChange={(e) => {
          console.log('state changes');
          setMarkedCheckBoxes(e);
        }}
        // This is where I set which checkboxes should be marked with value
        // initialValue={markedCheckBoxes}
        value={markedCheckBoxes}
      />
    </ModalForm>
  );
};

export default RowModal;

Thanks in advance!
Answer:
ProForm is a repackaging of antd Form

So you can use Form API for your purpose
import { useForm } from 'antd/lib/form/Form'

//...
const [form] = useForm();

// and then pass FormInstance in your component

<ModalForm
  form={form}
  //...
/>

// then in your handlers where you want to modify values use

form.setFieldsValue({
  "fieldName": value
})

Comment: Thank you for the answer fixed my problem.