text:
Q: Laravel Excel export not including float values of 0.00 I am exporting to excel using "maatwebsite/excel": "^3.1", but when I export, columns with values 0 or 0.0 are ignored and the cell is left empty.
sample code:
public function array(): array
{
    return $this->data;
}

public function columnFormats(): array
{
    return [
        'C' => NumberFormat::FORMAT_TEXT,
        'E' => '0.00',
        'F' => '0.00',
        'G' => '0.00'
    ];
}

public function map($rows): array
{
    return [
        $rows['employeeNumber'],
        $rows['basicSalary'],
        $rows['totalAllowance'],
        $rows['grossSalary']
    ];
}

when values for the columns are 0 or 0.00, nothing is inserted in the cell.

A: Kindly try with this
number_format((float)$value, 2, '.', '');

A: You can use WithStrictNullComparison
Ex. YourExportClass implements WithStrictNullComparison
https://docs.laravel-excel.com/3.1/exports/collection.html#strict-null-comparisons


text:
Q: Firebase Google auth in electron.js with create-react-app I am building a firebase google authentication in react app and it is working fine but whenever i have run build command in react and add this build's index.html file with my electron app nothing is showing.
The app is working fine with loadURL but i want to use loadFile to avoid waiting time.
Codes are given below, please check this:

electron-> main.js

const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')

const createWindow = () => {
 const mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  title: "Password Genrator",
  webPreferences: {
   preload: path.join(__dirname, 'preload.js')
  }
 })
 mainWindow.loadFile('src/build/index.html')
 mainWindow.setMenu(null)
}

app.whenReady().then(() => {
 createWindow()

app.on('activate', () => {
 if (BrowserWindow.getAllWindows().length === 0) createWindow()
 })
})

app.on('window-all-closed', () => {
 if (process.platform !== 'darwin') app.quit()
})

react.js-> App.js

import React from "react";
import "./App.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { Main } from "./components/Main";
import { Login } from "./components/Login";
import firebase from "./firebase";
import { Header } from "./components/Header";

function App() {
  const [user, setUser] = React.useState(null);

  React.useEffect(() => {
    firebase.auth().onAuthStateChanged((user) => {
      setUser(user);
      localStorage.setItem("user", user.uid);
    });
  }, []);
  return (
    <div className="App">
      <Router>
        {user ? <Header alt={user.displayName} src={user.photoURL} /> : ""}
        <Routes>
          {user ? (
            <Route exact path="/" element={<Main user={user} />} />
          ) : (
            <Route exact path="/" element={<Login />} />
          )}
        </Routes>
      </Router>
    </div>
  );
}

export default App;

react.js-> firebase.js

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/database";

const firebaseConfig = {
  apiKey: "**************************",
  authDomain: "*********.firebaseapp.com",
  databaseURL: "***************",
  projectId: "password-generator-b6da4",
  storageBucket: "**********.appspot.com",
  messagingSenderId: "*************",
  appId: "**************",
  measurementId: "**********",
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

export const auth = firebase.auth();

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: "select_account" });

export const signInWithGoogle = () => auth.signInWithPopup(provider);
export const database = firebase.database();
export default firebase;

Screenshot = electron app

Screenshot = react app

redpajama_set_name: RedPajamaStackExchange


text:
Q: Circular button to add items on ListView I´m looking to create the classic circular button on a ListView to add items. I´ve done that by using AbsoluteLayout just fine. But the problem I have is that I cannot make the Button to go with rounded border. No matter what I´ve set it just stays square. For what I´ve read it just seems that Xamarin overrrides the border behaviour. I cannot believe there is not a simple way to solve this.
Can anyone help me out with this?.
EDIT: I´ve tried https://github.com/wilsonvargas/ButtonCirclePlugin but I´m still getting the button with an erratic behaviour:

    <local:CircleButton
        Text="+"
        FontSize="Medium"
        FontAttributes="Bold"
        AbsoluteLayout.LayoutBounds="0.9,0.9,50,50"
        AbsoluteLayout.LayoutFlags="PositionProportional"
        HeightRequest="70"
        WidthRequest="70"/>

A: This is a problem only in Android 6.0 but it is solved by adding the BorderRadius property and assigning it the same value as the height of the button. something like this:
<local:CircleButton Icon="ic_directions_bike"
                        FontSize="30" TextColor="Black"
                        HeightRequest="70" WidthRequest="70"
                        BorderRadius="70" BackgroundColor="#DCDCDC"/>
    <!--This button is not exactly circular-->
    <local:CircleButton FontSize="30" TextColor="Black"
                        HeightRequest="70" WidthRequest="200"
                        BorderRadius="20" BackgroundColor="#DCDCDC"/>

This property allows you to create buttons that are not exactly circular, as seen in the image.

A:
I can get the background button using Xamarin.Forms. If you are writing Xamarin.Forms you can try.
<StackLayout Orientation="Horizontal">
            <Image Margin="10,10" HeightRequest="50" WidthRequest="50" Source="backButton.png">
                <Image.GestureRecognizers>
                    <TapGestureRecognizer Tapped="btnSetting_Clicked"/>
                </Image.GestureRecognizers>
            </Image>
            <Image HorizontalOptions="EndAndExpand" Margin="0,0,10,10" HeightRequest="50" WidthRequest="50" Source="settingsButton.png">
                <Image.GestureRecognizers>
                    <TapGestureRecognizer Tapped="btnSetting_Clicked"/>
                </Image.GestureRecognizers>
            </Image>
        </StackLayout>


text:
Q: How to get Unique Column from database in c# I am trying to get all unique column that is in a SQL Server table using c#.
For ex. I have table named "Emp" with the following columns:
Id (PK), Name, Address, SSN (Unique)

How can I retrieve columns that are only unique in C#?

A: Like this.
WITH i_unique AS (
    SELECT i.object_id, i.index_id
    FROM sys.indexes AS i
        INNER JOIN sys.index_columns AS ic
            ON ic.object_id = i.object_id
                AND ic.index_id = i.index_id
    WHERE i.is_unique = 1/*true*/
    GROUP BY i.object_id, i.index_id
    HAVING COUNT(ic.column_id) = 1
)
SELECT
    c.name AS 'column_name',
    i.name AS 'index_name'
FROM sys.objects AS o
    INNER JOIN sys.indexes AS i
        INNER JOIN i_unique
            ON i_unique.object_id = i.object_id
                AND i_unique.index_id = i.index_id
        INNER JOIN sys.index_columns AS ic
            INNER JOIN sys.columns AS c
                ON c.object_id = ic.object_id
                    AND c.column_id = ic.column_id
            ON ic.object_id = i.object_id
                AND ic.index_id = i.index_id
        ON i.object_id = o.object_id
WHERE o.object_id = OBJECT_ID('Emp');

Update:
Keep in mind this returns a column when its the only column that its unique index contains. So, those on composite indexes are left out (since they're not unique on their own).


text:
Q: Can ActiveRecord create tables outside of a migration? I am working on a non Rails web app, so no migrations script by default.
The Sequel ORM lets me create tables easily in a script:
#!/usr/bin/env ruby

require 'rubygems'
require 'sequel'

## Connect to the database
DB = Sequel.sqlite('./ex1.db')

unless DB.table_exists? :posts
  DB.create_table :posts do
    primary_key :id
    varchar :title
    text :body
  end
end

Is there a way todo this with ActiveRecord outside of migrations?

A: My current understanding is no, all modifications data or schema have to be done through a migration. I have a complete rakefile on github which can be used to perform the migrations outside of Rails.
Alternatively if it is just an initialisation script the following could be used.
ActiveRecord::Base.establish_connection(
   :adapter   => 'sqlite3',
   :database  => './lesson1_AR.db'
)

ActiveRecord::Migration.class_eval do
  create_table :posts do |t|
        t.string  :title
        t.text :body
   end

   create_table :people do |t|
      t.string :first_name
      t.string :last_name
      t.string :short_name
   end

   create_table :tags do |t|
      t.string :tags
   end
end

A: In Rails 4 at least (possibly earlier?), you can call create table directly on an ActiveRecord::ConnectionAdapters instance, using the same syntax as the migration.
You can get a connection for your database (assuming you have only one database) by calling ActiveRecord::Base.connection. So, the Ruby for your example would look like:
unless ActiveRecord::Base.connection.table_exists?(:posts)
  ActiveRecord::Base.connection.create_table :posts do |t|
    # :id is created automatically
    t.string :title
    t.text :body
  end
end

Note: If you already have a model defined, and it uses the same database as the one in which you want to create the table, you can grab a connection object from there instead. For one-off table creation in the console, I'll call User.connection.create_table simply because it's less typing.


text:
Q: If f and g are monotone functions, such that f is continuous and f(x)=g(x) for rationals x, then g is also continuous Let f and g be monotone functions on R such that f is continuous and g(x) = f(x) for all rational numbers x, then g is also continuous on R.
My idea is a such:
Without loss of generality, we assume that f is monotone increasing.
Since g = f for all rational numbers, g is monotone increasing for all rational numbers as well.
Suppose g is not continuous, then the limit of these two sequence are different.
By the density of real numbers, we can find a sequence of rational numbers that tend to c and a sequence of irrational numbers that tend to the same c.
Since the limit of these two sequences are different, they must differ by an amount say M.
However, again by the density of real numbers, there exists rational numbers and irrational numbers within this interval M. Hence, contradiction.

A: Let $c\in\mathbb{R}$.
Since $\mathbb Q$ is dense we can construct a sequences
$\left(x_{n}\right)$ and $\left(y_{n}\right)$ in $\mathbb Q$ both converging
to $c$ and with $x_{n}<c<y_{n}$.
Then $f\left(x_{n}\right)=g\left(x_{n}\right)\leq g\left(c\right)\leq g\left(y_{n}\right)=f\left(y_{n}\right)$
or $f\left(x_{n}\right)=g\left(x_{n}\right)\geq g\left(c\right)\geq g\left(y_{n}\right)=f\left(y_{n}\right)$
because $g$ is monotone.
This combined with $f\left(x_{n}\right)\rightarrow f\left(c\right)$
and $f\left(y_{n}\right)\rightarrow f\left(c\right)$ leads to $f\left(c\right)=g\left(c\right)$.
Proved is now that $f$ and $g$ coincide on $\mathbb{R}$ so that
$g$ is continuous like $f$.


text:
Q: How to raise/lower window via mouse in Cinnamon? Compiz has an option to bind a mouse shortcut (eg, Alt+Button7) to raise or lower the window under the mouse.
I find this a very useful way to switch windows.
Is there any way to replicate this shortcut on Cinnamon?
There doesn't seem to be any built-in support for mouse-button shortcuts.
The closest I could find (this doesn't actually work) is to set a keyboard shortcut to raise window, then bind that to the mouse using xbindkeys:
# .xbindkeysrc
# Raise window
"xset r off; xdotool key Super+F1; xset r on;"
  Alt + b:7

I verified that they keyboard shortcut works, and xbindkeys works for other actions with the same mouse button, but this binding does nothing (it does type a P in terminal; not sure why).

A: The problem was that my mouse modifier was preventing the keyboard shortcut.
Adding --clearmodifiers to the xdotool command fixes this:
# Raise window
"xset r off; xdotool key --clearmodifiers Super+F1; xset r on;"
  Alt + b:7

# Lower window
"xset r off; xdotool key --clearmodifiers Super+Shift+F1; xset r on;"
  Alt + b:6


text:
Q: Trying to replicate google maps slide panel with maps v3 and jquery I'm trying to create a slide panel similar to the one used currently on the left hand side of maps.google.com
The behavior I'm trying to replicate in conjunction with this panel (as displayed on google maps)

*

*When the panel opens the maps center will stay stationary

*The map controls (zoom, scale etc) are not overlapped by the panel, as in they'll shift with the expanding of the panel.

I initially thought I could just absolutely position a div over the map but this was covering the map controls e.g. (zoom, scale etc) and positioning them elsewhere was not an option.
My other two attempts are almost there but unfortunately not quite. Note the code examples were quickly thrown together for demo purposes.
1st attempt:
http://jsfiddle.net/fdwGd/5/
Two divs, one being the sliding panel and the other holding the map contents, both floated left. The 'Close'/ 'Open' button on the white panel has a click handler that animates the change of margin of the slide panel to hide it. The map div's width expands in parallel to fill the empty space. The problem here is the whole map shifts to the right when expanding the panel (click 'Open'/ 'close' in the jsfiddle example)
Positioning the panel to the right hand side of the screen resolves this ( with the addition of overflow: hidden on the html element) Although this does not meet my design requirements.
Also note that using google maps panby(x, y) function to fix the pixel jump was very clunky, so not really an option either
2nd attempt:
http://jsfiddle.net/63uxt/1/
So figured I'd have a go at adding a custom Google map control programmatically (the control being the sliding panel in question) and using the positioning options to get the other controls to nicely fit around my slide panel. Initially thought it worked until I realized the other controls would not re-position themselves after the sliding panel was hidden. Moving the map updated the position of the native controls (zoom etc) but this is not viable.
any ideas??
Thanks

A: Ok I think I have this figured out.
a very basic example - http://jsfiddle.net/H87q7/3/
I've gone the custom map control route and used the 'step' callback  of Jquery's animate function to fire the google  map 'resize' event. This re-positions the controls on the map at each step of the animation which appears quite smooth.
Not sure how elegant it is, as I'd rather not use a custom google control as I have quite a number of html elements to wire up within the panel and adding them all programmatically isn't what I'd like to do, but anyway...
I'd love to hear opinions on alternative ways of doing this.
Thanks


text:
Q: How do I override Django's default form error templates - at the project level? I know this topic has been asked a few times before on StackOverflow, and the docs seem pretty clear about how to do it, but it's not working for me and I'm stumped.
Overriding at the project level makes the most sense to me so I created a templates directory outside my app directories - at the same level as manage.py - and I added that directory path to my TEMPLATES['DIRS'] setting
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'DIRS': [BASE_DIR / 'templates'], # Allow overriding of other apps templates
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

I'd like to override the error templates for all forms at once, but I'm testing it with just a single ModelForm at the moment.
class MyForm(ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

Inside the View I create an instance of the form, instantiating it with some request data and the values from the model object matching the id passed in the request.
mymodelinstance = get_object_or_404(MyModel, id=kwargs['mymodel_id'])
form = MyForm(request_data, instance=mymodelinstance)

I checked where the form is getting its error template by printing the path in the View
print(form.errors.template_name)

The print statement printed django/forms/errors/dict/default.html so I put a new custom default.html file inside mydjangoproject/templates/django/forms/errors/dict/.
This doesn't work however. My new default.html template file isn't being used. Any ideas for what I'm doing wrong?


text:
Q: Is it a good idea to create an interface for each domain objects? I was just looking into the source code of an existing project which uses nHibernate and found that there are interfaces created for each entity classes. E.g ICustomer for Customer class. I was just wondering what can be the advantage of this pattern as ICustomer contains mainly the properties and very few methods.

A: I would say no.  Interfaces separate behavior from implementation so that the latter can be swapped out without affecting clients of the interface.
I don't see a need for interfaces if your domain objects won't require different implementations.  Only introduce them if dynamic proxy generation or aspects or changing implementations are necessary.

A: I don't disagree with the previous comments... Although, combined with patterns like Inversion of Control (IoC) and Dependency Injection it makes isolating such layers from each other much easier. This simplifies Unit Testing, Mocking, and can also lead to more loosely coupled architectures. This can still be acheived without interfaces although you need to make sure you do not seal your classes and make members virtual so you can still mock then, generate interceptable proxies, etc...  Finally, using interfaces forces you to drop assumptions related to any one concrete implementation and instead focus on the contract represented by the interface definition.


text:
Q: Liouville theorem for fractional Laplacian Is there any Liouville type theorem for the half space problem
\begin{equation}
  \ \  \left\{\begin{aligned}
(-\Delta)^s v &= f(v)  &&\text{in } \mathbb R^N_+\\
 v  & =0 &&\text{in  }  \mathbb R^N \setminus \mathbb R^N_+\end{aligned}
  \right.
\end{equation}
where $s\in (0, 1)$ and $v$ changes sign. If $v$ is bounded and $f(v)=0$, does it imply $v \equiv 0.$

A: Yes, $v$ is necessarily zero.
The function $v$ in your question is $\alpha$-harmonic in the half-space $H = \mathbb{R}^N_+$. Lemma 17 in [K. Bogdan, The boundary Harnack principle for the fractional Laplacian. Studia Math. 123(1) (1997): 43–80] (link) asserts that if $v$ is an $\alpha$-harmonic function in an open bounded set $D$, then $v$ is regular $\alpha$-harmonic in $D$, that is, it is given by a Poisson-type integral. Therefore, if $v$ is additionally zero outside $D$, then it is zero everywhere.
In our case, $H$ is not bounded. However, one can apply the same proof as in Bogdan's paper: boundedness of $D$ is required only to assert that the exit time from $D$ is finite with probability $1$, and the exit time from $H$ has this property.


text:
Q: How stay loged even if i reload the page
before all you need to know that im learning about backend-frontend and all your tips are welcome, i want to learn the best way possible.

im using Flask and Angular, in my web app i do a login, but when i reload the page i dont stay loged, how can i do to stay loged even if i reload the page
this is my backend:
@app.route('/user/register', methods=['POST'])
def register():
    r_first_name=request.get_json()['first_name']
    r_last_name=request.get_json()['last_name']
    r_email=request.get_json()['email']
    r_comp=request.get_json()['password']
    r_password=bcrypt.generate_password_hash(request.get_json()['password']).decode('utf-8')
    result=""

    if user_database_service.if_email_domain(r_email) == False:
        result="Invalid Email"
        print(result)
        return jsonify({'result': result})

    if user_database_service.if_user_exists(r_email):
        result="user already exists"
        print(result)
        return jsonify({'result': result})

    if user_database_service.if_user_number(r_first_name, r_last_name) == False:
        result="The Names are invalid"
        print(result)
        return jsonify({'result': result})

    if len(r_comp) < 5:
        result="Password Length"
        print(result)
        return jsonify({'result': result})
    r_comp = ""

    new_user=LocalUser(first_name=r_first_name, last_name=r_last_name, email=r_email, password=r_password, created=datetime.utcnow())
    added=user_database_service.add_user(new_user)
    if added is True:
        result="user successfully added"
        print(result)
    else:
        result="unable to add"
        print(result)
    return jsonify({'result': result})

@app.route('/user/login', methods=['POST'])
def login():
    email=request.get_json()['email']
    password=request.get_json()['password']
    result=""

    response_user=user_database_service.get_user(email)

    if response_user:
        if bcrypt.check_password_hash(response_user.password, password):
            access_token=create_access_token(
                identity=
                {
                    'first_name': response_user.first_name,
                    'last_name': response_user.last_name,
                    'email': response_user.email
                }
            )
            result=jsonify({'token': access_token})
        else:
            result=jsonify({'error': 'Invalid username or password'})
    return result

and this is my authentication_service in angular:
export interface UserDetails
{
  _id: number
  first_name: string
  last_name: string
  email: string
  password: string
  exp: number
  iat: number
}

interface TokenResponse
{
  token: string
}

export interface TokenPayload
{
  id: number
  first_name: string
  last_name: string
  email: string
  password: string
}

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  constructor(private http: HttpClient, private router: Router) { }

  private token!: string;

  private saveToken(token: string): void
  {
    localStorage.setItem('usertoken', token)
    this.token=token
  }

  private getToken(): string
  {

    if(!this.token)
    {
      this.token==localStorage.getItem('usertoken')
    }

    return this.token
  }

  public getUserDetails(): UserDetails
  {
    const token=this.getToken()

    let payload
    var x
    if(token)
    {
      payload=token.split('.')[1]
      payload=window.atob(payload)
      x = JSON.parse(payload)

      return JSON.parse(payload)

    }
    else
    {
        return null as any

    }
  }

  public getUserInfo(busqueda:string): UserDetails
  {

    const token=this.getToken()

    let payload
    var x
    if(token)
    {
      payload=token.split('.')[1]
      payload=window.atob(payload)
      x = JSON.parse(payload)
     x['sub'][busqueda]
      return x['sub'][busqueda]
    }
    else
    {
        return null as any

    }
  }

  public isLoggedIn(): boolean
  {
    const user=this.getUserDetails()

    if(user)
    {

      return user.exp > Date.now()/1000
    }
    else
    {
      return false
    }
  }

  public register(user: TokenPayload): Observable<any>
  {
    const base=this.http.post<TokenResponse>(`http://localhost:3000/user/register`, user)
    const request=base.pipe(
      map((data: TokenResponse) => {
        if(data.token)
        {
          this.saveToken(data.token)
        }
        console.log(data)

        var x = JSON.stringify(data)
        console.log("Este es x: " + x)
        if ( x == '{"result":"Password Length"}')
        {
          Swal.fire({
            title: 'Error en el registro',
            text: "La contraseña debe ser mayor a 5 caracteres",
            icon: 'error',
            confirmButtonText: 'Reintentar'
        })
      }

        if ( x == '{"result":"Invalid Email"}')
        {
          Swal.fire({
            title: 'Error en el registro',
            text: "El Email ingresado es invalido",
            icon: 'error',
            confirmButtonText: 'Reintentar'
        })

      }

      if ( x == '{"result":"user already exists"}')
        {
          Swal.fire({
            title: 'Error en el registro',
            text: "El Email ingresado ya existe",
            icon: 'error',
            confirmButtonText: 'Reintentar'
        })

      }

      if ( x == '{"result":"The Names are invalid"}')
      {
        Swal.fire({
          title: 'Error en el Registro',
          text: "Los nombres no deben contener numeros",
          icon: 'error',
          confirmButtonText: 'Reintentar'
      })

    }

      if ( x == '{"result":"user successfully added"}')
        {
          Swal.fire({
            title: 'El registro es valido',
            text: "El Email ingresado es invalido",
            icon: 'success',
            confirmButtonText: 'Reintentar'
        }).then((result)=> {
        if (result.isConfirmed) {
          this.router.navigateByUrl('/login')
        }
        })

      }

      console.log(data)
        return data

      })
    )

    return request
  }

/*
  public register(user: TokenPayload): Observable<any>
  {
    console.log(this.http.post(`http://localhost:3000/user/register`, user))
    return this.http.post(`http://localhost:3000/user/register`, user)
  }
  */
  public login(user: TokenPayload): Observable<any>
  {
    const base=this.http.post<TokenResponse>(`http://localhost:3000/user/login`, user)
    const request=base.pipe(
    map((data: TokenResponse) => {
        if(data.token)
        {
          this.saveToken(data.token)
        }
        console.log(data)
        var x = JSON.stringify(data)
        console.log("Este es x: " + x)
        if ( x == '{"error":"Invalid username or password"}')
        {
          console.log("ENTRO MI LOCO")
          Swal.fire({
            title: 'Login Invalido',
            text: "Haz ingresado la contraseña incorrecta",
            icon: 'error',
            confirmButtonText: 'Reintentar'})
        }

        return data
      })
    )
    console.log("Request: " + request)
    return request

  }

  public logout(): void
  {
    Swal.fire({
      title: 'Se ha cerrado la sesion',
      text: "Se ha cerrado de la sesion actual",
      icon: 'error',
      confirmButtonText: 'OK!'

  })
    this.token=''

    window.localStorage.removeItem('usertoken')
    this.router.navigateByUrl('/')
  }
}

A: to stay login status,you can use cookie, this is normal method.
or send token in request data every time.
when you request login url,told browser send cookie to you every time.
session = "user token"
res = make_response()
    res.set_cookie('session', session)
return res

use this method to get session in cookie:
session = request.cookies.get('session')

a simple cookie check func:
@app.before_request
    def before_request():
        session = request.cookies.get('session')
        if not session :
            return jsonify({'result': "not login"})
        return None


text:
Q: Gaussain mixture Model _ Scikit Learn _ How to fit for single D data? I have started working with GMM in Sklearn library.
I have 1 D data like below

np.random.seed(2)
x = np.concatenate([np.random.normal(0, 2, 2000),
                    np.random.normal(5, 5, 2000),
                    np.random.normal(3, 0.5, 600)])

I would like to use sklearn GaussainMixture function to fit with 4 Gaussian Mixture. So i tried
clf= GaussianMixture(n_components = 4, max_iter=500, random_state=3).fit(x)

Problem
When i run  the above code i recieve an error

Reshape your data either using array.reshape(-1, 1) if your data has a
  single feature or array.reshape(1, -1) if it contains a single sample.

My trace back is

Traceback (most recent call last):
  File "C:\Users\VW3ZTWS\PycharmProjects\Data_Collection_and_learnings\venv\lib\site-packages\IPython\core\interactiveshell.py", line 2869, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-44-7de666249812>", line 1, in <module>
    clf= GaussianMixture(n_components = 4, max_iter=500, random_state=3).fit(x)
  File "C:\Users\VW3ZTWS\PycharmProjects\Data_Collection_and_learnings\venv\lib\site-packages\sklearn\mixture\base.py", line 194, in fit
    self.fit_predict(X, y)
  File "C:\Users\VW3ZTWS\PycharmProjects\Data_Collection_and_learnings\venv\lib\site-packages\sklearn\mixture\base.py", line 220, in fit_predict
    X = _check_X(X, self.n_components, ensure_min_samples=2)
  File "C:\Users\VW3ZTWS\PycharmProjects\Data_Collection_and_learnings\venv\lib\site-packages\sklearn\mixture\base.py", line 55, in _check_X
    ensure_min_samples=ensure_min_samples)
  File "C:\Users\VW3ZTWS\PycharmProjects\Data_Collection_and_learnings\venv\lib\site-packages\sklearn\utils\validation.py", line 552, in check_array
    "if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[-0.03338572  0.3163226  -1.94596018 ...  2.93448979  2.77931282
  3.28590084].

Question
Whether I cannot fit GMM for 1 D data ?
I am not sure about the mistake what i have made, Kindly clarify-

A: What you posted tells you how to proceed:

Reshape your data either using array.reshape(-1, 1) if your data has a
  single feature or array.reshape(1, -1) if it contains a single sample.

If your dataset is 1D, it has a single feature, therefore:
x = x.reshape(-1, 1)

and the rest of code should work.


text:
Q: How to use IHostingEnvironment How do I use the  IHostingEnvironment interface without initiating it in a constructor?
my Startup.cs:
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

My Class:
public class FileReader
{
    // I don't want to initiate within a constructor

    public string ReadFile(string fileName)
    {
       // this is wrong! how can I use it?
       var filename = Path.Combine(IHostingEnvironment.WebRootPath, fileName);
    }
}

A: You should use the integrated dependency injection as it makes your code decoupled and easier to change without breaking stuff and make it very easy to unit test.
If you would access it via static class or method, then your code becomes hard to test as in unit test it would always use the project path and not some specific string for testing.
The way you described it absolutely correct and it's NOT wrong! Below just the complete example.
public class FileReader
{
    private readonly IHostingEnvironment env;
    public FileReader(IHostingEnvironment env)
    {
        if(env==null)
            throw new ArgumentNullException(nameof(env));

        this.env = env;
    }

    public string ReadFile(string fileName)
    {
       var filename = Path.Combine(env.WebRootPath, fileName);
    }
}

If the env value is null in the constructor, you may need to register it yourself in Startup.cs, if ASP.NET Core doesn't do it already:
services.AddSingleton<IHostingEnvironment>(env);

where env is the instance passed to the Startup constructor.


text:
Q: Can 'case - when' returns mutiple results? Assume there is a table dim_user_info which comprises non-repeat user_id and its id_number.
Now I want to classify them:
select
a.user_id,
(case when user_id in (1,3,5,7) then 'class1'
when id_number in (128,329,349) then 'vip'
end) as category
from dim_user_info a

If a piece of user info meets two conditions at the same time, I want to get the full info, like user c in the following table:
user_id  id_number   category
1          111        class1
2          128         vip
3          329        class1
3          329         vip
6          128         vip
7           55        class1

Is this doable in hive? Thanks for your help.

A: You can try using a UNION query:
select
    user_id,
    'class1' as category
from dim_user_info
where user_id in (1,3,5,7)
union all
select
    user_id,
    'vip'
from dim_user_info
where id_number in (128,329,349)

I don't know if this would be the most performant solution in Hive SQL, but it is one way to have the same record appear multiple times, once for each possible matching category.
If you also want to include non matching users, you could use another union for that.

A: If not all users are classified, you could use a classification table with the columns
user_id,
id_number,
category
and the query
select
a.user_id, c.category
from dim_user_info a
left outer join  classification c
on (a.user_id = c.user_id or a.id_number = c.id_number)

A: select  ui.usr
       ,e.col

from    dim_user_info ui
        lateral view explode(array(
             case when user_id   in (1,3,5,7)     then 'class1' end
            ,case when id_number in (128,329,349) then 'vip'    end
            )) e

where   e.col is not null


text:
Q: PowerShell object multiple lines different properties $vms = @()

$foo = New-Object -TypeName PSObject
$foo | Add-Member -MemberType NoteProperty -Name "Name" -Value "Host1"
$foo | Add-Member -MemberType NoteProperty -Name "OSDisk" -Value "64 GB"
$vms += $foo

$bar = New-Object -TypeName PSObject
$bar | Add-Member -MemberType NoteProperty -Name "Name" -Value "Host2"
$bar | Add-Member -MemberType NoteProperty -Name "OSDisk" -Value "64 GB"
$bar | Add-Member -MemberType NoteProperty -Name "DataDisk1" -Value "128 GB"
$vms += $BAR

$vms[0] | ft
$vms[1] | ft
$vms | ft

As you can see, the second row has more properties than the first row.
When displaying, I get only the properties present in the first row, the others are ignored.
PS C:> $vms[0] | ft
Name  OSDisk
----  ------
Host1 64 GB

PS C:> $vms[1] | ft
Name  OSDisk DataDisk1
----  ------ ---------
Host2 64 GB  128 GB

PS C:> $vms | ft
Name  OSDisk
----  ------
Host1 64 GB
Host2 64 GB

What am I hoping to achieve is to have every property in every row:
Name  OSDisk  DataDisk1
----  ------  ----------
Host1 64 GB
Host2 64 GB    128 GB

[edit]
The properties may vary, in my case a VM may have one or more datadisks.

A: Some time ago I made a helper function to complete the first item in an array of objects with all headers found:
function Complete-ObjectHeaders {
    # function to add properties to the first item in a collection of PSObjects
    # when this object is missing properties from items further down the array.
    # you may need this is you have such a collection and want to export it
    # to Csv, since Export-Csv only looks at the first item to create the
    # csv column headers.
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [PSObject[]]$Collection,

        [int]$MaxItemsToTest = -1,  # < 0 --> test all items in the collection
        [switch]$SortHeaders
    )

    # Try and find all headers by looping over the items in the collection.
    # The headers will be captured in the order in which they are found.
    if ($MaxItemsToTest -gt 0) {
        $MaxItemsToTest = [math]::Min($MaxItemsToTest, $Collection.Count)
        $headers = for($i = 0; $i -lt $MaxItemsToTest; $i++) {
            ($Collection[$i].PSObject.Properties).Name
        }
        $headers = $headers | Select-Object -Unique
    }
    else {
        $headers = $Collection | ForEach-Object {($_.PSObject.Properties).Name} | Select-Object -Unique
    }

    if ($SortHeaders) { $headers = $headers | Sort-Object }

    # update the first object in the collection to contain all headers
    $Collection[0] = $Collection[0] | Select-Object $headers

    ,$Collection
}

In your case, you could do this
Complete-ObjectHeaders -Collection $vms | Format-Table -AutoSize

to output

Name  OSDisk DataDisk1
----  ------ ---------
Host1 64 GB
Host2 64 GB  128 GB

Hope that helps


text:
Q: Cake on Ubuntu LAMP stack always sending  in pages I have a problem with my Cake application on Ubuntu 14.10. I try to see the source code from the page, it shows:
<?php

then the content shows after this tag.
This is a problem specially with AJAX request content, because this string appended breaks all the JavaScript.
Here is my controller:
<?php
/**
 * Index
 *
 * The Front Controller for handling every request
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.webroot
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

ini_set('memory_limit', '256M');

/**
 * Use the DS to separate the directories in other defines
 */
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

/**
 * These defines should only be edited if you have cake installed in
 * a directory layout other than the way it is distributed.
 * When using custom settings be sure to use the DS and do not add a trailing DS.
 */

/**
 * The full path to the directory which holds "app", WITHOUT a trailing DS.
 *
 */
if (!defined('ROOT')) {
    define('ROOT', dirname(dirname(dirname(__FILE__))));
}

/**
 * The actual directory name for the "app".
 *
 */
if (!defined('APP_DIR')) {
    define('APP_DIR', basename(dirname(dirname(__FILE__))));
}

/**
 * The absolute path to the "cake" directory, WITHOUT a trailing DS.
 *
 * Un-comment this line to specify a fixed path to CakePHP.
 * This should point at the directory containing `Cake`.
 *
 * For ease of development CakePHP uses PHP's include_path. If you
 * cannot modify your include_path set this value.
 *
 * Leaving this constant undefined will result in it being defined in Cake/bootstrap.php
 *
 * The following line differs from its sibling
 * /lib/Cake/Console/Templates/skel/webroot/index.php
 */
//define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'lib');

/**
 * Editing below this line should NOT be necessary.
 * Change at your own risk.
 *
 */
if (!defined('WEBROOT_DIR')) {
    define('WEBROOT_DIR', basename(dirname(__FILE__)));
}
if (!defined('WWW_ROOT')) {
    define('WWW_ROOT', dirname(__FILE__) . DS);
}

// for built-in server
if (php_sapi_name() === 'cli-server') {
    if ($_SERVER['REQUEST_URI'] !== '/' && file_exists(WWW_ROOT . $_SERVER['PHP_SELF'])) {
        return false;
    }
    $_SERVER['PHP_SELF'] = '/' . basename(__FILE__);
}

if (!defined('CAKE_CORE_INCLUDE_PATH')) {
    if (function_exists('ini_set')) {
        ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path'));
    }
    if (!include 'Cake' . DS . 'bootstrap.php') {
        $failed = true;
    }
} else {
    if (!include CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php') {
        $failed = true;
    }
}
if (!empty($failed)) {
    trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
}

App::uses('Dispatcher', 'Routing');

$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(
    new CakeRequest(),
    new CakeResponse()
);

I try to found some solution to this but didn't find it.


text:
Q: How to pass the return value of jquery dialogue box button function in some called function I want to get the return value of jquery dialogue box, depends on return value true or false  of dialogue I need to call some other function , Here is my trial,but here it is returning [object object].
 function someFunction()
    {
      returnVal=$('#uploadMsrDialog').dialog('open');
      alert(returnVal);// RETURNING [object object]
      if(returnVal==true)
      {
        do some thing...
      }
    }

Here is my dialogue box open script :
  $(function() {
  $('button#btnAdmViewRej').click(function(){
  $('#uploadMsrDialog').dialog('open');
 });
$('#uploadMsrDialog').dialog({
    autoOpen: false,
    width: 250,
    height: 200,
    position: 'top',
    modal: true,
    resizable: false,
    buttons: {
               "OK":function()
                 {
                    callback(true);
                 });
                     $(this).dialog("close");
                 },
                   "Close": function() {
                    callback(false);
                 $(this).dialog("close");
                }
    } //end of buttons:
    });

function callback(val)
{
  return val;
}

A: function someFunction()
{
  var returnVal=$('#uploadMsrDialog').dialog('open');
  /*
  returnVal is a jquery wrapper object $('#uploadMsrDialog').
  At this point the dialog is shown and is waiting for
  the user to click OK or Close. The execution continues and
  someFunction exits. callback function has not
  executed yet.
  */
}

The logic that depends on what user clicked (OK or Close) should be in callback:
function callback(val)
{
  if(val)
  {
    do some thing...
  }
}


text:
Q: Parâmetros Stored Procedures Estou com uma dúvida e queria pedir a ajuda de vocês. Seguinte: tenho uma proc e quero que quando eu não passar um parâmetro ela me retorne null e quando isso acontecer trazer a data do dia  -1 e hora zerada e se for passado parâmetro execute normal segue como eu estava fazendo.
CREATE PROCEDURE Dbo.AtualizaTMP_Venda(
    @IdContrato INT = 1
)
    AS

IF @IdContrato = NULL
    BEGIN
    SELECT CAST(CAST(GETDATE() -1 AS DATE) AS DATETIME)
    END

A: Você deve fazer a verificação o NULL com o IS ao invés de = (O motivo você pode conferir na resposta da pergunta "Por que valores NULL não são selecionados?". Depois disso você deve usar a função DATEADD para retornar a data atual -1 dia:
CREATE PROCEDURE Dbo.AtualizaTMP_Venda(
  @IdContrato INT = NULL
) AS
BEGIN
  IF @IdContrato IS NULL
  BEGIN
    SELECT DATEADD(DAY, -1, GETDATE()) AS data;

    RETURN;
  END;

  -- Continua a execução normal
END;
GO

DATEADD
Retorna uma data especificada com o intervalo numérico especificado (inteiro assinado) adicionado à parte da data especificada.


text:
Q: How to remove unnecessary line breaks in data before writing to CSV What I'm trying to do is store a bunch of information into a .csv
file.After running the script and getting all the email addresses into a csv file I notice the following problem. Around cell CE the row breaks and a new row is being created. Sometimes the row ends up breaking in the middle of an email address.
Practical example:
email, name@email.com, name@email.com, name@email.com, name@em
ail.com, name@email.com, name@email.com, name@email.com, name@email.c
om, name@email.com, name@email.com, name@email.com, name@
email.com]
I also need to mention that Im trying to pull 20k contacts with this script.
import requests
import csv
import unicodedata
import getpass

# Credentials
url = 'https://....com/api/v2/users.json'
csvfile = 'users2.csv'

output_3 = []
output_3.append("email")

while url:

    # Use Your Sign-On Credentials
user = '...'
pwd = '...'
response = requests.get(url, auth=(user, pwd))
data = response.json()

for user in data['users']:
    email = user['email']
    decode_3 = bool(email) and unicodedata.normalize('NFKD', email)
    output_3.append(decode_3)

print(data['next_page'])
url = 'https://.../api/v2/users.json' and data['next_page']
print("users:")
print(len(output_3))

# Write to a csv file
with open((csvfile), mode='w', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow([output_3])

A: It could be that your output_3 list is fed content containing whitespace or line break characters. You could try stripping your mail of trailing whitespaces str.strip() or to manually remove whitespace characters (str.replace('\n', '') or str.replace(' ', '')).


text:
Q: Partial Ready drives in DDN storage We have a storage array : DDN SFA7700 with an extension.
The warranty is over and we prepare the new storage to copy the data. But we still need two-three weeks until the new storage will be operational.
Unfortunately, we had a big problem with our conditioner in data center.
Once the problem was resolved, I discovered that about 15 drives in the extension are marked as "Partial Ready" state.
As I understood from documentation, it means that these drives are seen only by one controller (in our case the controller 1).
We restarted the storage twice, but still the same result : the drives are still in partially ready state.
As I understood, the data could be accessible, but if I lose the controller number 1, I could lose all of data.
I have a colleague that had some similar problem in the past with another storage (Dell), but the problem was solved by restarting storage. So it seems that it does not work for us.
So, I'd like to know if somebody had seen this problem before and could give me an advice?

A: DDN is a very small player in this market so I'd be surprised if someone here has has EXACTLY the same problem but there will be many people here, including myself, that have seen similar problems on similar arrays.
If I read your question correctly you have a working array but some of the disks cannot be seen my one of the two controller - but you're about to start migrating all data from it to a new array. If that is correct and you intend to move the data VERY soon then I'd be inclined to just carry on with the fault and focus on getting off the array as soon as possible rather than pay money to fix an array that won't be in service for long. That said if the data migration is weeks or months away from being complete I may choose to get it fixed.


text:
Q: How can I get the max value within a max value in mysql? I have a schema like the following
id (INT)
Cycle_Number (INT)
Cycle_Day (INT)
Date (date)

...other columns irrelevant to the question...

How can I get the row that has the max Cycle_Day within the max Cycle_Number
For example, say I have the following data
ID Cycle_Number Cycle_Day Date
1  1            1         2011-12-01
2  1            2         2011-12-02
3  2            1         2011-12-03
4  2            2         2011-12-04
5  2            3         2011-12-05
6  2            4         2011-12-06
7  3            1         2011-12-07
8  3            2         2011-12-08
9  3            3         2011-12-09
The query would return row 9. (It has the highest Cycle_Day within the highest Cycle_Number)
Thanks

A: this one is compatible MySql 5.5 with no joint tables
SELECT id
FROM cycles
ORDER BY Cycle_Number DESC , Cycle_Day DESC
LIMIT 0 , 1

Regards

A: This SQL query should provide the max value you want.
SELECT ID, Cycle_Number, Cycle_Day, Date
FROM  yourTable AS t
CROSS JOIN (
  SELECT MAX(Cycle_Number) AS Cycle_Number FROM yourTable
) AS sq USING (Cycle_Number)
ORDER BY Cycle_Day DESC LIMIT 1


text:
Q: Keras: TypeError: 'float' object is not callable. Unable to call model.fit() or model.fit_generator() on very simple CNN model I am workimg on MNIST Hand Sign Dataset for classification. I have my (28*28) images pixels in a numpy array as:
X_train.shape, X_val.shape
>>
((2496, 28, 28, 1), (996, 28, 28, 1))

I have used ImageDataGenerator to make batches and train the model. I have been the following instructions:
Batch size =50, epoch=20
All filter (kernel) sizes are 3x3
Initial Conv2D layer with 64 filters
MaxPooling layer following this
Second Conv2D layer with 128 filters
Dense output layer after this

My model is as follows:
datagen = ImageDataGenerator(preprocessing_function=1./255.0)
train_gen = datagen.flow(X_train, y_train, batch_size=50)
val_gen = datagen.flow(X_val,y_val, batch_size=50)

input_ = Input(shape=(28,28,1))
x = Conv2D(64,kernel_size=(3,3))(input_)
x = ELU()(x)
x = MaxPooling2D(pool_size=(3,3))(x)
x = Conv2D(128,kernel_size=(3,3))(input_)
x = ELU()(x)
x = Flatten()(x)
out = Dense(24,activation='softmax')(x)

model = Model(inputs=input_,outputs=out)
model.compile(loss=sparse_categorical_crossentropy,optimizer=Adam(lr=0.001),metrics=['accuracy'])

model.fit(train_gen,epochs=20,)

I have used Sparse Categorical Cross Entropy because I have some missing class values in my y_labels. There are 24 classes from 0-24 but class=9 missing.
Can someone tell me why is that hapenning??
I think the problem is in train_gen because next(train_gen) gives me the same error.
Lower half of the error is:
/opt/conda/lib/python3.7/site-packages/keras/utils/data_utils.py in get_index(uid, i)
    404         The value at index `i`.
    405     """
--> 406     return _SHARED_SEQUENCES[uid][i]
    407
    408

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/iterator.py in __getitem__(self, idx)
     63         index_array = self.index_array[self.batch_size * idx:
     64                                        self.batch_size * (idx + 1)]
---> 65         return self._get_batches_of_transformed_samples(index_array)
     66
     67     def __len__(self):

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/numpy_array_iterator.py in _get_batches_of_transformed_samples(self, index_array)
    152             x = self.image_data_generator.apply_transform(
    153                 x.astype(self.dtype), params)
--> 154             x = self.image_data_generator.standardize(x)
    155             batch_x[i] = x
    156

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/image_data_generator.py in standardize(self, x)
    702         """
    703         if self.preprocessing_function:
--> 704             x = self.preprocessing_function(x)
    705         if self.rescale:
    706             x *= self.rescale

TypeError: 'float' object is not callable

A: The problem is in this part:
datagen = ImageDataGenerator(preprocessing_function=1./255.0)

The preprocessing_function parameter expects a function, not a float value. You probably confused it with the rescale parameter:
datagen = ImageDataGenerator(rescale=1./255.0)


text:
Q: SQL Query difference of count http://i.stack.imgur.com/GPlNo.png
I am trying to perform the following query:
For question number 42, all its answers, sorted so the highest-voted answer is first.
However, my query gives me an error, saying "invalid input syntax for integer: "u"
I have triple checked my database table and it is a character for vote_choice. I'm not sure how to fix this. I tried LIKE as well, but did not solve anything.
Any suggestions?
SELECT answers,
    ((SELECT COUNT(vote_choice)
    FROM vote
    JOIN answervote USING (vote_id)
    NATURAL JOIN answers
    WHERE vote_choice = 'u'
    &  vote.vote_id = answervote.vote_id
    & answervote.answer_id = answer.answer_id)
  -(SELECT COUNT(vote_choice)
    FROM vote
    JOIN answervote USING (vote_id)
    JOIN answers USING (answer_id)
    WHERE vote_choice = 'd'
    &  vote.vote_id = answervote.vote_id
    & answervote.answer_id = answer.answer_id)) AS total_points
FROM answers
JOIN questions USING (question_id)
WHERE question_id = 42
ORDER BY total_points DESC;

A: Zenksor, try replacing '&' character for the 'AND' operator.
'&' is the bitwise 'AND' in T-SQL. It might have the same meaning in other RDBMS. I have never seen & as a relational AND operator.


text:
Q: Grid of photos in xcode I lack any knowledge in xcode, cocoa touch or c+++ etc. Now, I am going to try to make a photography app, where I got a tab bar, and 4 undercategories. At the first category, I want it to be a grid of photos who can be enlarged by touching them. I really don't have time to learn more about programming for a couple of months. How is this achieved in the easiest possible way? I am currently leaning towards AQGridView, but since I have zero knowledge of the area I cannot fully understand the instructions. Now before you ask why I want to make an app without any sorts of knowledge, let me answer it. My father is a photographer, and wishes to get an app. If I manage to make one for him, I can get loads of jobs where his photographer friends pay for an app. And if I have already made it, I will probably have a template from the earlier project to take advantage from.
So, in conclusion, my question is: How do I make this possible in the easiest way possible?
Thanks.

A: Sounds like a great candidate for the new UICollectionViews. There are many grid frameworks out there, but if you have any experience with TableViews on iOS, CollectionViews are a breeze to get up and running quickly. One of the best resources for learning and implementing CollectionViews (outside of the API docs) can be found here:
UICollectionView custom layout tutorial


text:
Q: what is the advantage of string object as compared to string literal i want to know where to use string object(in which scenario in my java code).
ok i understood the diff btwn string literal and string object, but i want to know that since java has given us the power to make string object, there must be some reason, at some point string object creation would be useful. so i want to know in which scenario can we prefer string object in place of string literal.

A: In most situations, you should use String literals to avoid creating unnecessary objects.  This is actually Item 5: Avoid creating unnecessary objects of Effective Java:

Item 5: Avoid creating unnecessary objects
It is often appropriate to reuse a
  single object instead of creating a
  new functionally equivalent object
  each time it is needed. Reuse can be
  both faster and more stylish. An
  object can always be reused if it is
  immutable (Item 15). As an extreme
  example of what not to do, consider
  this statement:
String s = new String("stringette"); // DON'T DO THIS!

The statement creates a new String
  instance each time it is executed, and
  none of those object creations is
  necessary. The argument to the String
  constructor ("stringette") is itself a
  String instance, functionally
  identical to all of the objects
  created by the constructor. If this
  usage occurs in a loop or in a
  frequently invoked method, millions of
  String instances can be created
  needlessly. The improved version is
  simply the following:
String s = "stringette";

This version uses a single String
  instance, rather than creating a new
  one each time it is executed.
  Furthermore, it is guaranteed that the
  object will be reused by any other
  code running in the same virtual
  machine that happens to con- tain the
  same string literal [JLS, 3.10.5]

There is however one situation where you want to use the new String(String) constructor: when you want to force a substring to copy to a new underlying character array like in:
String tiny = new String(huge.substring(0, 10));

This will allow the big underlying char[] from the original huge String to be recycled by the GC.

A: Don't use a new String object if you know what the string is. For example:
String str = new String("foo"); // don't do this

You are thus creating an unnecessary object - once you have a String object created from the literal, and then you create another one, taking the first one as constructor argument.

A: Contrary to your question, there is a DISADVANTAGE of using a String object compared to String literal.
When you declare a String literal, String s = "foo", the compiler will check for an existing "foo" object on the heap and assign 's' to already existing "foo".
However, if you create a String object, String s = new String("foo"), an entirely new object will be created on the heap (even if there is already an existing "foo"). Strings being immutable this is totally unnecessary.
Here is good reference: http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

A: String a = "ABC";
String b = new String("ABC");
String c = "ABC";

a == b // false
a == c // true

a.equals(b) // true
a.equals(c) // true

The point is that a & c point to the same "ABC" object (JVM magic). Using "new String" creates a new object each time. IMO, using string object is a disadvantage, not an advantage. However, as another poster said, string object is useful for converting byte[], char[], StringBuffer - if you need to do that.

A: String literals are converted to String objects, and as others pointed out, creating explicit String objects is unnecessary and inperformant, as it defeats String pooling.
However, there is one situation where you want to create new Strings explicitly: If you use just a small part of a very long String. String.substring() prevents the original String from getting GC'd, so you can save memory when you write
String s = new String(veryLongString.substring(1,3));

instead of
String s = veryLongString.substring(1,3);

A: literal strings are objects created in a String Pool and if they have the same value, they are referencing to the same object.
System.out.println("abc"=="abc"); // the output is true

Meanwhile, string object are real objects in memory and if they have the same value, there's no guarantee that they are referencing to the same object.
String a = new String("abc");
String b = new String("abc");
System.out.println(a==b); // the output is false


text:
Q: How can I validate a range in laravel? I have a table in which number details of document is stored.
For example, for invoice, number range is 101 to 105.
Now when this range ends (invoice no 105 created). At that time, Pop-up alert is shown to user to set the range again.
When he sets range for invoice for 2nd time, he should not be able to set old range i.e. 101-105 again.
How can I check this ?


text:
Q: How to check data redundancy on float32 variable in C? I would like to check data corruption of a variable in some function. In general, if it is a unsigned integer variable i can easily check like below method
sender side:
uint8 actual_data = 23;
uint8 send_data = ~actual_data; /*bitwise NOT*/
send_data_to_other(send_data, actual_data);

receiver side:
void receive_data_to_other(uint8 received_data, uint8 actual_data)
{
   uint8 check_data = ~received_data;
   if(check_data == actual_data)
   {
     printf("data is correct");
   }
   else
   {
     printf("something wrong")
   }
}

But suppose if i am using float32 data,
eg: float32 actual_data = 23.22f;
then i can not perform bitwise NOT(~) for float32 variables.
Any one Suggest me how can we check the data verification for float32 variable in C?

A: Assuming sizeof (float) == sizeof (uint32_t):
    uint32_t data;
    uint32_t ndata;

    memcpy(&data, &f, sizeof(data));
    ndata = ~data;

But of course, your send function will need to send larger chunks of data.
To "reconstruct" float you will need to copy data in the opposite direction.
float toFloat(uint32_t data)
{
    float f;

    memcpy(&f, &data, sizeof(f));
    return f;
}

Do not worry about memcpy overhead as this function is very well known to the compiler and optimizing compilers will optimize out the call.


text:
Q: In which case do you use UIViewController class with UITableViewDelegate/UITableViewDataSource protocols instead of straight UITableViewController? I ask because I've just downloaded two example swift projects: one is a todo-list, the other is a contacts list, both use UIViewController class conformed to UITableViewDelegate/UITableViewDataSource protocols instead of UITableViewController. Is there anything different between those two practice at all?
in code:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {...}
vs.
class ViewController: UITableViewController {...}


text:
Q: How to write an async/await method as an Observable in Angular? I used to do async/await and just learned to use Observable in Angular because it's the Angular way, so I want to refactor this code snippet here to make this as an Observable:
async refreshToken() {
    const headers = this.authStorage.getRequestHeader();
    const body = {
      refreshToken: this.authStorage.getStoredValue('refreshToken'),
    };
    const newAccessToken = await this.http
      .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers })
      .toPromise();

    this.authStorage.setValueToStore('accessToken', newAccessToken);
  }

So basically I am making a post request to my backend and get a token back and then use it in the authStorage.
I tried to do this as an Observable and got this so far:
refreshToken(): Observable<any> {
    const headers = this.authStorage.getRequestHeader();
    const body = {
      refreshToken: this.authStorage.getStoredValue('refreshToken'),
    };
    return this.http
      .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers });

    this.authStorage.setValueToStore('accessToken', newAccessToken);
  }

This is okay and works but I cannot call my authStorage this way.
I cannot save it in a variable because an Observable needs to have a return...
I also tried with pipe and subscribe but no chance.
Any tips?

A: You can perform your side-effect logic inside the tap operator:
return this.http
    .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers })
    .pipe(
        tap(newAccessToken => this.authStorage.setValueToStore('accessToken', newAccessToken))
    );


text:
Q: ObservableCollection items - modify property of individual items if a flag is set I have a data grid, and observable collection is bound to it:
private ObservableCollection<RequestParameter> _parameters = new ObservableCollection<RequestParameter>();

    public ObservableCollection<RequestParameter> Parameters
    {
        get { return _parameters; }
        set { Set(ref _parameters, value); }
    }

    private bool _isPostRequest;
    public bool IsPostRequest
    {
        get { return _isPostRequest; }
        set { Set(ref _isPostRequest, value); }
    }

And the model:
public class RequestParameter
{
    public string Key { get; set; }
    public string Value { get; set; }
    public bool IsPostParameter { get; set; }
}

So on the UI, I have a checkbox and a datagrid
<DataGrid HeadersVisibility="Column" RowHeaderWidth="0" Grid.Row="2" Grid.ColumnSpan="2" ItemsSource="{Binding Parameters}" CanUserAddRows="True" AutoGenerateColumns="False" CanUserDeleteRows="True" MinHeight="140">
                            <DataGrid.Columns>
                                <DataGridTextColumn Header="Key" Binding="{Binding Key}" Width="*"/>
                                <DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*"/>
                            </DataGrid.Columns>
                        </DataGrid>
  <CheckBox HorizontalAlignment="Right" IsChecked="{Binding IsPostRequest}"/>

So if the check box is clicked, IsPostParameter of all items in the collection should be set to True.
The only way I can think of is in the getter or the setter of the Parameters field, check for IsPostRequest property of the viewmodel, and if it is, run through all parameters and set the flag.
Is there any better solution for this?

A: Add a Command to your view model and set the CheckBox command property to that command. And pass IsChecked as parameter:  CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}
Then in your command iterate over your collection items and set your field to the appropriate value.

A: I think you can check it over IsPostRequest setter property
    private bool _isPostRequest;
    public bool IsPostRequest
    {
        get { return _isPostRequest; }
        set
        {
            _isPostRequest = value;
            Parameters.ToList().ForEach(x => x.IsPostParameter = value);
            RaisePropertyChanged("IsPostRequest");
        }
    }


text:
Q: How to concatenate two or more videos with different dimensions in FFMpeg? I have two videos I would like to concatenate.

*

*First Video Dimensions = 480x640

*Second Video Dimensions = 640x480

I tried concatenating them and received an error. I've included the full error below.
ffmpeg -i 682_segment_0.mp4 -i 682_segment_1.mp4 -filter_complex \
        "[0:v:0] [0:a:0] [1:v:0] [1:a:0] concat=n=2:v=1:a=1 [v] [a]" \
       -map "[v]" -map "[a]" -ar 44100 -vcodec libx264 \
       -strict -2 -acodec aac 682.mp4

ffmpeg version 2.8.8-0ubuntu0.16.04.1 Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.2) 20160609
  configuration: --prefix=/usr --extra-version=0ubuntu0.16.04.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv
  libavutil      54. 31.100 / 54. 31.100
  libavcodec     56. 60.100 / 56. 60.100
  libavformat    56. 40.101 / 56. 40.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 40.101 /  5. 40.101
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  2.101 /  1.  2.101
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '682_segment_0.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf56.40.101
  Duration: 00:00:19.30, start: 0.000000, bitrate: 335 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 480x640 [SAR 1:1 DAR 3:4], 219 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 120 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from '682_segment_1.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf56.40.101
  Duration: 00:00:09.97, start: 0.000000, bitrate: 568 kb/s
    Stream #1:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x480 [SAR 1:1 DAR 4:3], 460 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #1:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, 3.0, fltp, 104 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
[Parsed_concat_0 @ 0x202dea0] Input link in1:v0 parameters (size 640x480, SAR 1:1) do not match the corresponding output link in0:v0 parameters (480x640, SAR 1:1)
[Parsed_concat_0 @ 0x202dea0] Failed to configure output pad on Parsed_concat_0
Error configuring complex filters.
Invalid argument

I did a bit of checking, and it appears I need to resize one of the videos to be the same size as the other video before I could concatenate it. I'm not sure if that is correct, but I resized it using ffmpeg.
ffmpeg -i 682_segment_0.mp4 -vf scale=640:480 -strict -2 682_segment_0b.mp4

After resizing the 480x640 video to 640x480 I tried the concat command again. And got another error. (I've included the final error here, but not the whole output.)
Input #0 Video Stream: 640x480 [SAR 9:16 DAR 3:4]
Input #1 Video Stream: 640x480 [SAR 1:1 DAR 4:3]

[Parsed_concat_0 @ 0x22cefe0] Input link in1:v0 parameters (size 640x480, SAR 1:1) do not match the corresponding output link in0:v0 parameters (640x480, SAR 9:16)
[Parsed_concat_0 @ 0x22cefe0] Failed to configure output pad on Parsed_concat_0

I found that resizing the DAR allowed me to concat the two videos, but the resized portion of the completed video now has the wrong aspect ratio. I was hoping to basically have "black" on the sides with my resize without cropping the video.
I attached an example here:

Resize DAR command that worked but made aspect ratios wrong:
ffmpeg -i 682_segment_0.mp4 -ar 44100 -vcodec libx264 \
       -strict -2 -acodec aac -s 360x480 682_segment_0e.mp4

I am wondering if I should try doing the concat and rescale at the same time, but I am not sure how to do so.

A: From the concat filter documentation:

All corresponding streams must have the same parameters in all
  segments; the filtering system will automatically select a common
  pixel format for video streams, and a common sample format, sample
  rate and channel layout for audio streams, but other settings, such as
  resolution, must be converted explicitly by the user.

You will have to scale and pad (or crop) to make 480x640 fit into 640x480:
ffmpeg -i 480.mp4 -i 640.mp4 -filter_complex \
"[0:v]scale=640:480:force_original_aspect_ratio=decrease,pad=640:480:(ow-iw)/2:(oh-ih)/2[v0]; \
 [v0][0:a][1:v][1:a]concat=n=2:v=1:a=1[v][a]" \
-map "[v]" -map "[a]" -c:v libx264 -c:a aac -movflags +faststart output.mp4

*

*Your ffmpeg is old: you should really consider updating to a build from the current git master branch. The easiest way to do that is to just download a binary.

*If you're scripting this then you should "conform" each input to common parameters using fps, format/aformat, and scale filters to avoid ffmpeg from choosing unexpected and undesired "common formats".

*Also see Resizing videos with ffmpeg to fit into static sized player.


text:
Q: Sum of table column by cell name I have a table, table headers and some number under the header.
I want to write a dynamic formula which will get the sum of the column under each header.
instead of
=SUM(Subeler[MERKEZ OFIS])

I want a formula to replace the name of the header, something like :
=SUM(Subeler["C6"])

the header is on C6 cell.
Why I need this :

*

*each time the header may change which is coming from powerquery

*I need the sum, somewhere on the top of the table

A: in C5 cell , i wrote the formula

="Subeler["&C6&"]"

then in the cell i have this formula :

=Sum(indirect(c5))

it was so simple but i've just figured it out...


text:
Q: JavaFX and Callbacks I am trying to set a callback for a method in JavaFX: http://docs.oracle.com/javafx/2/api/javafx/fxml/FXMLLoader.html#setControllerFactory(javafx.util.Callback)
This is the signature:
public void setControllerFactory(Callback<java.lang.Class<?>,java.lang.Object> controllerFactory)

I've tried different kind of setups, this is the latest and I can't seem to get it to compile at all, there's always something that doesn't match the signature:
val loader = new FXMLLoader()
loader.setControllerFactory(new Callback[Class[_], AnyRef] {

})

This one gives me:
error: object creation impossible, since method call in trait Callback of type (x$1: Class[_])AnyRef is not defined

How would I write that Java example in Scala?

A: As the error message says, you need to define that method in your anonymous class:
loader.setControllerFactory(new Callback[Class[_],Object] {
  def call(c: Class[_]): Object = {
    // your implementation
  }
})


text:
Q: Stack build fails due to missing dependencies I am trying to make something like acme-everything for stackage called ghci-all, e. g.  a stack project, where stack ghci gives you access to all of stackage. I added all the packages in the latest snashot to my .cabal file, and after working through all the foreign dependencies, I got the strange error:
setup-Simple-Cabal-1.22.5.0-ghc-7.10.3: At least the following dependencies
are missing:
Ebnf2ps -any,
TaxonomyTools -any,
YampaSynth -any,
alex -any,
angel -any,
bumper -any,
c2hs -any,
cabal-install -any,
cabal-rpm -any,
cabal-sort -any,
cabal-src -any,
calculator -any,
clash-ghc -any,
clckwrks-cli -any,
gipeda -any,
git-fmt -any,
gtk2hs-buildtools -any,
hackage-whatsnew -any,
haddocset -any,
happy -any,
hdevtools -any,
hledger-interest -any,
hledger-ui -any,
hopenpgp-tools -any,
hspec-setup -any,
ip6addr -any,
lentil -any,
lhs2tex -any,
moesocks -any,
mole -any,
resolve-trivial-conflicts -any,
sandman -any,
servius -any,
shelltestrunner -any,
skeletons -any,
tellbot -any,
tls-debug -any,
tttool -any,
yackage -any,
yesod-bin -any

These dependencies are listed in the file though (and should have been installed). Did I miss something important?

A: It's a confusing error message from Cabal. You're not able to add an executable only package to build-depends. You'll need to filter out projects that do not have a library.


text:
Q: Problema em concatenar usando jQuery Tenho o seguinte exemplo que não consigo fazer.
Tenho uma div:

Teste

E tenho o seguinte código:
status = 3;
codigo = 8;
$('.dados[data-attribute='+ id + ']').attr('onclick',(status+, id));

Quando eu executo esse código ele soma os valores 1+8 porém eu preciso que fique assim:
 onclick="bloquearSacado(3,8);"

Qual a maneira certa de concatenar nessa situação de modo que fique igual ao de resultado de cima?
PS: o ( e , são fundamentais.
Muito Obrigado.

A: Seu problema começa em erro de sintaxe:
(status+, id)

Essa vírgula após o + causa erro pois não tem como somar ou concatenar duas variáveis com uma vírgula no meio.
Se quer alterar o atributo do elemento com as duas variáveis status e codigo, o correto seria colocar também o nome da função e alterar os valores dentro dos parêntesis concatenando os valores fora das aspas do método:
$('.dados[data-attribute='+ id + ']').attr('onclick','bloquearSacado('+status+','+codigo+')');


text:
Q: How do I change a specific value found when looping a 2d array? Trying to replace values of an array in an array.
The array only has values 1 or 0, it is a grid.
Code is looking for a 1 and change that to 0 and also change the same column value of the row below to 1.
I belive the problem is im making the if statement invalid with the changes im trying to make. Resulting in error message.
function gravity() {
  for (var i = 0; i < rows; i++) {
    for (var j = 0; j < cols; j++) {
      if (grid[i][j] === 1){
        grid[i][j] = 0;
        grid[i+1][j] = 1;
      }
    }
  }
}

A: The problem is that when your loop is in the last row it will try to set i+1 to 1, but since i is already the last index i+1 is out of bounds.
To fix this you can simply add an if
You also have another bug. Since you interate from top to bottom you move any 1's down to the next row, then you go through the next row and find the exact same 1's that you have just moved down and move them down again. This repeats until all 1's are gone, all in a single call to gravity(). To fix this you have to interate through the rows from bottom to top.

var grid = [
  [1,0,0,0],
  [0,0,1,0],
  [0,0,0,0],
  [0,1,0,0]
]

var cols = 4;
var rows = 4;

function gravity() {
  for (var i = rows - 1; i >= 0; i--) {
    for (var j = 0; j < cols; j++) {
      if (grid[i][j] === 1){
        grid[i][j] = 0;
        if(i+1 < rows) {
          grid[i+1][j] = 1;
        }
      }
    }
  }
}

var iterations = 0;

var intervalId = setInterval(() => {
  gravity();
  for(var row of grid) {
    console.log(row.join(','))
  }
  console.log("");
  iterations++;
  if(iterations == 4) {
    clearInterval(intervalId);
  }
}, 400)


text:
Q: How to map values from map to object based on containsKey? I have a map of values like so:
Map<String, Object> values = Map.of("name", "myName", "address", null);

I want to update an object like this:
class User {
  String name;
  String address;
  String country;
}

Now I want the fields in User to be overwritten only if the source map has the key defined. So the address field should be set to null (because there's an explicit mapping to null), but the country field should not be changed (because there's no "country" key in the map).
This is similar to what nullValuePropertyMappingStrategy = IGNORE does, but not quite, as the check is a map.containsKey check instead of a standard null check.
Can I extend MapStruct so it can do this?
My MapStruct code:
@Mapper
interface MyMapper {
    @Mapping(target = "name", expression = "java( from.getMap().get(\"name\") )")
    @Mapping(target = "address", expression = "java( from.getMap().get(\"address\") )")
    @Mapping(target = "country", expression = "java( from.getMap().get(\"country\") )")
    To get(MapWrapper from, @MappingTarget To to);
}

A: MapStruct can't do this out of the box.
However, you could wrap your Map into a Bean. So something like this:
public class MapAccessor{

private Map<String, Object> mappings;

   public MapAccessor(Map<String, Object> mappings) {
      this.mappings = mappings;
   }

   public Object getAddress(){
       return this.mappings.get("address");
   }

   public boolean hasAddress(){
       return this.mappings.containsKey("address");
   }
   ...
}

And then you could a normal mapper mapping WrappedMap to your targetbean and using the NullValuePropertyMappingStrategy..
Note: your mapper is a lot simpler than as well..

@Mapper( nullValuePropertyMappingStrategy = NullValueProperertyMappingStrategy.IGNORE )
interface MyMapper {

    To get(MapAccessor from, @MappingTarget To to);
}


text:
Q: c++ destructor called before end of program When I run the following code in VS2013:
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Auteur {
public:
    Auteur(string n, bool p = false)
    : nom(n), prime(p)
    {}
    const string getNom(){
        return nom;
    }
    bool getPrix(){
    return prime;
    }
   //Auteur(const Auteur&) = delete;

private:
   string nom;
   bool prime;
   };
class Oeuvre{
public:
    Oeuvre(string t, Auteur &a, string lang)
    : titre(t), langue(lang), auteur(a)
    {}
     tring getTitre(){
    return titre;
     }
const Auteur & getAuteur(){
    return auteur;
     }
    string getLangue(){
    return langue;
     }
    void affiche(){
    cout << titre << " ," << auteur.getNom() << " en " << getLangue() << endl;
    }

   ~Oeuvre(){
    cout << "L'oeuvre " <<titre << ", " << auteur.getNom() << ", en " << langue     << " n'est plus disponible." << endl;
   }
   //Oeuvre(const Oeuvre&) = delete;
 private:
    string titre;
    Auteur &auteur;
string langue;
};

class Exemplaire{
public:
Exemplaire(Oeuvre & oeuvre)
    : oeuvre(oeuvre)
{
    Auteur a = oeuvre.getAuteur();
    cout << "Nouvel exemplaire de : " << oeuvre.getTitre() << ", " << a.getNom() <<" en " << oeuvre.getLangue() << endl;
}
Exemplaire(Exemplaire const& ex)
    : oeuvre(ex.oeuvre)
{
    Auteur a = oeuvre.getAuteur();
    cout << "Copie d'un exemplaire de : " << oeuvre.getTitre() << ", " << a.getNom() << ", en " << oeuvre.getLangue() << endl;
}
const Oeuvre & getOeuvre() const{
    return oeuvre;
}
void affiche(){
    Auteur a = oeuvre.getAuteur();
    cout << "Exemplaire de : " << oeuvre.getTitre() << ", " << a.getNom() << ", en " << oeuvre.getLangue() << endl;
}
~Exemplaire(){
    Auteur a = oeuvre.getAuteur();
    cout << "Un exemplaire de " << oeuvre.getTitre() << ", " << a.getNom() << ", en " << oeuvre.getLangue() << " a été jeté !" << endl;
 }

private:
Oeuvre  &oeuvre;
};
class Bibliotheque{
public:
Bibliotheque(string nom)
    : nom(nom)
{
    cout << "La bibliothèque " << nom << " est ouverte !" << endl;
}
string getNom(){
    return nom;
}
void stocker(Oeuvre &oeuvre, int n = 1)
{
    for (int i = 0; i < n; i++){
        exp.push_back(new Exemplaire(oeuvre));
    }
}
void lister_exemplaires(string langue = ""){
    int taille = exp.size();
    if (langue.empty() == true)
    {
        for (auto & ex : exp) {
            (*ex).affiche();
        }

    }
    else {
        for (int i(0); i<taille; i++)
        {
            Oeuvre o = exp[i]->getOeuvre();
            if (o.getLangue() == langue){
                exp[i]->affiche();
            }
        }
    }
}
int compter_exemplaires(Oeuvre ev){
    int ct = 0;
    for (auto &ex : exp) {
        Oeuvre ew = (*ex).getOeuvre();
        Auteur at = ew.getAuteur();
        Auteur a = ev.getAuteur();
        if (ew.getTitre() == ev.getTitre() && at.getNom() == a.getNom() && ew.getLangue() == ev.getLangue())
            ct++;
    }
    return ct;
}
void afficher_auteurs(bool b= false){
    for (auto & ex : exp)
    {
        Oeuvre ev = (*ex).getOeuvre();
        Auteur auteur = ev.getAuteur();
        string s = auteur.getNom();
        if (b){
            if (auteur.getPrix())
            cout << s << endl;
        }

    }

}
~Bibliotheque(){
    cout << "La bibliothèque " << getNom() << " ferme ses portes, \net détruit ses exemplaire :" << endl;
    int taille = exp.size();
    for (int i(0); i<taille; i++)
        delete exp[i];
}

 private:
string nom;
vector <Exemplaire *> exp;
 };

int main()
{
Auteur a1("Victor Hugo"),
    a2("Alexandre Dumas"),
    a3("Raymond Queneau", true);

Oeuvre o1("Les Misérables", a1, "français"),
    o2("L'Homme qui rit", a1, "français"),
    o3("Le Comte de Monte-Cristo", a2, "français"),
    o4("Zazie dans le métro", a3, "français"),
    o5("The Count of Monte-Cristo", a2, "anglais");

Bibliotheque biblio("municipale");
biblio.stocker(o1, 2);
biblio.stocker(o2);
biblio.stocker(o3, 3);
biblio.stocker(o4);
biblio.stocker(o5);

cout << "La bibliothèque " << biblio.getNom()
    << " offre les exemplaires suivants :" << endl;
biblio.lister_exemplaires();

const string langue("anglais");
cout << " Les exemplaires en " << langue << " sont :" << endl;
biblio.lister_exemplaires(langue);

cout << " Les auteurs à succès sont :" << endl;
biblio.afficher_auteurs(true);

cout << " Il y a " << biblio.compter_exemplaires(o3) << " exemplaires de "
    << o3.getTitre() << endl;

return 0;
}

I get the following output:
La bibliothÞque municipale est ouverte !
Nouvel exemplaire de : Les MisÚrables, Victor Hugo en franþais
Nouvel exemplaire de : Les MisÚrables, Victor Hugo en franþais
Nouvel exemplaire de : L'Homme qui rit, Victor Hugo en franþais
Nouvel exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas en franþais
Nouvel exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas en franþais
Nouvel exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas en franþais
Nouvel exemplaire de : Zazie dans le mÚtro, Raymond Queneau en franþais
Nouvel exemplaire de : The Count of Monte-Cristo, Alexandre Dumas en anglais
La bibliothÞque municipale offre les exemplaires suivants :
Exemplaire de : Les MisÚrables, Victor Hugo, en franþais
Exemplaire de : Les MisÚrables, Victor Hugo, en franþais
Exemplaire de : L'Homme qui rit, Victor Hugo, en franþais
Exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en franþais
Exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en franþais
Exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en franþais
Exemplaire de : Zazie dans le mÚtro, Raymond Queneau, en franþais
Exemplaire de : The Count of Monte-Cristo, Alexandre Dumas, en anglais
 Les exemplaires en anglais sont :
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre L'Homme qui rit, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Zazie dans le mÚtro, Raymond Queneau, en franþais n'est plus disponible.
Exemplaire de : The Count of Monte-Cristo, Alexandre Dumas, en anglais
L'oeuvre The Count of Monte-Cristo, Alexandre Dumas, en anglais n'est plus disponible.
 Les auteurs Ó succÞs sont :
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre L'Homme qui rit, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
Raymond Queneau
L'oeuvre Zazie dans le mÚtro, Raymond Queneau, en franþais n'est plus disponible.
L'oeuvre The Count of Monte-Cristo, Alexandre Dumas, en anglais n'est plus disponible.
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre L'Homme qui rit, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre Zazie dans le mÚtro, Raymond Queneau, en franþais n'est plus disponible.
L'oeuvre The Count of Monte-Cristo, Alexandre Dumas, en anglais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
 Il y a 3 exemplaires de Le Comte de Monte-Cristo
La bibliothÞque municipale ferme ses portes,
et dÚtruit ses exemplaire :
Un exemplaire de Les MisÚrables, Victor Hugo, en franþais a ÚtÚ jetÚ !
Un exemplaire de Les MisÚrables, Victor Hugo, en franþais a ÚtÚ jetÚ !
Un exemplaire de L'Homme qui rit, Victor Hugo, en franþais a ÚtÚ jetÚ !
Un exemplaire de Le Comte de Monte-Cristo, Alexandre Dumas, en franþais a ÚtÚ jetÚ !
Un exemplaire de Le Comte de Monte-Cristo, Alexandre Dumas, en franþais a ÚtÚ jetÚ !
Un exemplaire de Le Comte de Monte-Cristo, Alexandre Dumas, en franþais a ÚtÚ jetÚ !
Un exemplaire de Zazie dans le mÚtro, Raymond Queneau, en franþais a ÚtÚ jetÚ !
Un exemplaire de The Count of Monte-Cristo, Alexandre Dumas, en anglais a ÚtÚ jetÚ !
L'oeuvre The Count of Monte-Cristo, Alexandre Dumas, en anglais n'est plus disponible.
L'oeuvre Zazie dans le mÚtro, Raymond Queneau, en franþais n'est plus disponible.
L'oeuvre Le Comte de Monte-Cristo, Alexandre Dumas, en franþais n'est plus disponible.
L'oeuvre L'Homme qui rit, Victor Hugo, en franþais n'est plus disponible.
L'oeuvre Les MisÚrables, Victor Hugo, en franþais n'est plus disponible.

Where Instead I should  get the following output:
La bibliothèque municipale est ouverte !
Nouvel exemplaire de : Les Misérables, Victor Hugo, en français
Nouvel exemplaire de : Les Misérables, Victor Hugo, en français
Nouvel exemplaire de : L'Homme qui rit, Victor Hugo, en français
Nouvel exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en français
Nouvel exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en français
Nouvel exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en français
Nouvel exemplaire de : Zazie dans le métro, Raymond Queneau, en français
Nouvel exemplaire de : The Count of Monte-Cristo, Alexandre Dumas, en anglais
La bibliothèque municipale offre les exemplaires suivants :
Exemplaire de : Les Misérables, Victor Hugo, en français
Exemplaire de : Les Misérables, Victor Hugo, en français
Exemplaire de : L'Homme qui rit, Victor Hugo, en français
Exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en français
Exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en français
Exemplaire de : Le Comte de Monte-Cristo, Alexandre Dumas, en français
Exemplaire de : Zazie dans le métro, Raymond Queneau, en français
Exemplaire de : The Count of Monte-Cristo, Alexandre Dumas, en anglais
 Les exemplaires en anglais sont :
Exemplaire de : The Count of Monte-Cristo, Alexandre Dumas, en anglais
 Les auteurs à succès sont :
Raymond Queneau
 Il y a 3 exemplaires de Le Comte de Monte-Cristo
La bibliothèque municipale ferme ses portes,
et détruit ses exemplaires :
Un exemplaire de "Les Misérables, Victor Hugo, en français" a été jeté !
Un exemplaire de "Les Misérables, Victor Hugo, en français" a été jeté !
Un exemplaire de "L'Homme qui rit, Victor Hugo, en français" a été jeté !
Un exemplaire de "Le Comte de Monte-Cristo, Alexandre Dumas, en français" a été jeté !
Un exemplaire de "Le Comte de Monte-Cristo, Alexandre Dumas, en français" a été jeté !
Un exemplaire de "Le Comte de Monte-Cristo, Alexandre Dumas, en français" a été jeté !
Un exemplaire de "Zazie dans le métro, Raymond Queneau, en français" a été jeté !
Un exemplaire de "The Count of Monte-Cristo, Alexandre Dumas, en anglais" a été jeté !
L'oeuvre "The Count of Monte-Cristo, Alexandre Dumas, en anglais" n'est plus disponible.
L'oeuvre "Zazie dans le métro, Raymond Queneau, en français" n'est plus disponible.
L'oeuvre "Le Comte de Monte-Cristo, Alexandre Dumas, en français" n'est plus disponible.
L'oeuvre "L'Homme qui rit, Victor Hugo, en français" n'est plus disponible.
L'oeuvre "Les Misérables, Victor Hugo, en français" n'est plus disponible.

Can you please tell me where is exactly the problem. why the Oeuvre class destructor is called before the end of main program ?

A: Inside your loops in 'afficher_auteurs', 'compter_exemplaires', etc, you are making copies of the objects, like this;
 Oeuvre ev = (*ex).getOeuvre();

so while getOeuvre is returning the object by reference, the receiver variable 'ev' is not receiving it by reference, and hence a copy is made.  The destructor of these copied objects will be called on exit of the loop (when it goes out of scope) -- this is likely be the reason you are seeing the destructor running before the 'main' is completing.
Try fix this to change the code to receive by reference and see if that works, like this;

Oeuvre& ev = (*ex).getOeuvre();

or

const Oeuvre& ev = (*ex).getOeuvre();

and while you are at it, you probably want to declare all your methods on Oeuvre as 'const', like

const Auteur & getAuteur() const {....

as you otherwise will not be able to use those methods on a const object.

A: The destructor for the Oeuvre class that you're seeing isn't for any of the variables initialized as directly in int main (e.g., o1, o2, etc.); it's for temporary variables used elsewhere in the program.
For example:
void afficher_auteurs(bool b= false){
for (auto & ex : exp)
{
    // **This is a temporary Oeuvre**
    Oeuvre ev = (*ex).getOeuvre();

    Auteur auteur = ev.getAuteur();
    string s = auteur.getNom();
    if (b){
        if (auteur.getPrix())
        cout << s << endl;
    }

} // **The temporary Oeuvre is destroyed here**

It's not unusual for destructors to be invoked before the end of the program. A destructor is invoked whenever an object is being destroyed.
Variables that are automatically allocated (i.e., on the stack), are automatically destroyed when they go out of scope.
Variables that are dynamically allocated (e.g., using new) are destroyed when they are explicitly deallocated (e.g., using delete).

A: the problem is here:
void lister_exemplaires(string langue = ""){
  int taille = exp.size();
  if (langue.empty() == true)
  {
    for (auto & ex : exp) {
        (*ex).affiche();
    }

  }
  else {
    for (int i(0); i<taille; i++)
    {
        /************************/
        Oeuvre o = exp[i]->getOeuvre();
        if (o.getLangue() == langue){
            exp[i]->affiche();
        }
        /************************/
    }
  }
}

You get the Oeuvre and make a local copy. When the for-loop ends, this temporary object is destroyed and its destructor called.
Use a reference instead:
const Oeuvre &o = exp[i]->getOeuvre();
//... as before


text:
Q: How do I set and save to a Rails API a Backbone collection nested within a Backbone Model? I want to nest a Backbone collection (Profiles) within a Backbone Model (Guild), and populate this collection with one Profile model (to start with).
My goal is that when a user creates a new Guild, the model corresponding to this user should be added to the "users" attribute of the Guild.
Therefore in my View I call a createGuild function that is defined within my model, which takes as an argument the model for the Profile of the logged in user.
createGuild(
    attrs: CreatableGuildArgs,
    profile: Backbone.Model,
    error: (errors: string[]) => void,
    success: () => void
  ) {

    this.set(attrs);
    this.set('users', new Profiles());
    this.get("users").add(profile);

    console.log(this.get("users").length);
    console.log(this.get("users").at(0));

    this.save(
      {},
      {
        url: this.urlRoot(),

        success: () => success(),
        error: (_, jqxhr) => {
          error(this.mapServerErrors(jqxhr?.responseJSON));
        },
      }
    );
  }

The two console.logs work fine within my createGuild function: I see a Profiles collection populated with one user profile, of length 1.
However, the call to the save function is not working and returns the following error in my terminal :
Started POST "/guilds" for 172.18.0.1 at 2020-11-23 19:05:56 +0000
Cannot render console from 172.18.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
 Processing by GuildsController#create as JSON
Parameters: {"name"=>"gsdfgdhtfg", "ang"=>"GDG", "users"=>"[object Object]"}
Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.0ms | Allocations: 2121)

NoMethodError (undefined method `each' for "[object Object]":String):

app/controllers/guilds_controller.rb:15:in `create'

In my chrome console I get : "Uncaught TypeError: Cannot convert undefined or null to object"
Here are my Rails models :
class Guild < ApplicationRecord
    has_one_attached :img
    has_many :users
    accepts_nested_attributes_for :users

    validates :img, blob: { content_type: :image }
    validates :name, presence: true, uniqueness: true, length: {minimum: 5, maximum: 20}
    validates :ang, presence: true, length: {minimum: 2, maximum: 5}
end

class User < ApplicationRecord
    has_one_attached :avatar
    belongs_to :guild, optional: true

    validates :avatar, blob: { content_type: :image, size_range: 1..5.megabytes }
    validates :name, presence: true
    validates :name, length: {minimum: 3, maximum: 32}
    validates :login, presence: true, uniqueness: true
end

And the Rails controller for the create method of guild:
  def create
    @guild = Guild.create(guild_params)
    if @guild.save
        @guild
    else
        render json: @guild.errors, status: :unprocessable_entity
    end
  end

  private

  def guild_params
    params.permit(:name, :ang, :img, :users)
  end

And here is my json.jbuilder files :

*

*_guild.json.jbuilder :

json.extract! guild, :id, :name, :ang, :points, :atWar, :created_at, :updated_at
json.img_url url_for(guild.img) if guild.img.attached?
json.users guild.users do |json, user|
  json.partial! user
end

*

*create.json.jbuilder :

json.partial! "guilds/guild", guild: @guild

And finally, here is my complete Guild model :
export default class Guild extends Backbone.Model {

  constructor(options?: any) {
    super(options);
  }

  urlRoot = () => "http://localhost:3000/guilds";

  sync(method: string, model: Guild, options: JQueryAjaxSettings): any {
    if (method == "create") {
      var formData = new FormData();

      _.each(model.attributes, function (value, key) {
        formData.append(key, value);

      });
      _.defaults(options || (options = {}), {
        data: formData,
        processData: false,
        contentType: false,
      });
    }
    return Backbone.sync.call(this, method, model, options);
  }

  createGuild(
    attrs: CreatableGuildArgs,
    profile: Backbone.Model,
    error: (errors: string[]) => void,
    success: () => void
  ) {

    this.set(attrs);

    this.set('users', new Profiles());
    this.get("users").add(profile);

    console.log(this.get("users").length);
    console.log(this.get("users").at(0));

    this.save(
      {},
      {
        url: this.urlRoot(),

        success: () => success(),
        error: (_, jqxhr) => {
          error(this.mapServerErrors(jqxhr?.responseJSON));
        },
      }
    );
  }

  mapServerErrors(errors: Record<string, string[]>) {
    return Object.keys(errors).map((key) => `${key} ${errors[key].join(",")}`);
  }
}

Does anyone know how to fix this?
Thank you