text:
Q: Find the order of a differential equation in Sympy I have a differential equation defined in Sympy (0.7.6.1), for example:
>>> y = Function('y')
>>> x = Symbol('x')
>>> y0 = y(x)
>>> y1 = y0.diff(x)
>>> y2 = y1.diff(x)
>>> eq = y2 - 2*y1 + y0
>>> eq
                      2
         d           d
y(x) - 2*--(y(x)) + ---(y(x))
         dx           2
                    dx

I would like Sympy to tell me the order of the equation. I found nothing in the documentation. I faintly hoped that degree might work, but it doesn't:
>>> degree(eq)
1
>>> degree(eq, y)
0

Context: For pedagogical purpose, I've written a solver for constant-coefficient linear homogeneous ODEs. It finds the characteristic equation and solves it with Sympy's roots. Currently I have to pass the ODE order by hand next to the ODE itself, which is inconvenient.

A: You can use ode_order. This gives you the order of the differential equation with respect to a function:
>>> ode_order(eq, y)
2


text:
Q: How to get the coordinates of where a line and a circle intersect when the result gives an imaginary number? if you select a two points (everything in 2 dimensions), draw a circle centered on the first point and connect the two points with a line, and you know both of the point's coordinates and the radius of the circle, how do you get the coordinates of where the line and the circle intersect when the result is an imaginary number? sometimes when solving this problem the quadratic formula has a negative number on it's root which makes it impossible for me to know the coordinates of the point. anyone know how to solve this problem?
For Example. if you take the first point's coordinates (center of the circle) as (1,1), the second point's coordinates as (-2,2) and the radius of the circle as 1.
now if you use the equation for a circle ($r^2=(x-x0)^2+(y-y0)^2$) and replace $y$ with the equation for the line ($y = mx+b$), we get the equation for the coordinate of the interception ($r^2=(x-x0)^2+(mx+b-y0)^2$).
we get $m$ by doing $\frac{y0-y1}{x0-x1}$ which in this case is $-\frac{1}{3}$. We get $b$ from $mx-y$ which in this case is $-\frac{4}{3}$. now if we put everything in the equasion, it should be like this: $1^2=(x-1)^2+(-\frac{1}{3}x-\frac{4}{3}-1)^2$
which I solve like this:
$1=(x-1)^2+(-\frac{1}{3}x-\frac{7}{3})^2$ $<=>$
$0=x^2-2x+1+\frac{1}{9}x^2+\frac{14}{9}x+\frac{49}{9}-1$ $<=>$
$\frac{10}{9}x^2-\frac{4}{9}x+\frac{49}{9}=0$ $<=>$
$x=\frac{-(-\frac{4}{9})\pm\sqrt{(-\frac{4}{9})^2-4\times(\frac{10}{9})\times(\frac{49}{9})}}{2\times(\frac{10}{9})}$ $<=>$
$x=\frac{\frac{4}{9}\pm\sqrt{-24}}{\frac{20}{9}}$
as you can see I can't calculate the X value of the interception because the $\sqrt{-24}$ gives a imaginary number.

A: Here's a simple geometric approach to finding the intersection point. Call the point around which the circle is drawn $u$, call the other point $v$, and call the intersection point $x$. Because $x$ lies along the line connecting $u$ and $v$, the displacement between $x$ and $u$ must point along the same direction as the displacement between $v$ and $u$. Next, because $x$ lies on a circle of radius $R$ around $u$, the displacement between $x$ and $u$ must have length $R$. Hence the displacement between $x$ and $u$ is given by $R(v-u)/\|v-u\|_2$, and the intersection point is thus given by,
$$x = u + R\frac{v-u}{\|v-u\|_2}$$
Plugging in coordinates should give you your answer! For instance, take $R=1$, $u=(1,1)$, and $v=(-2,2)$. Then $v-u=(-3,1)$, and $\|v-u\|_2=\sqrt{9+1}=\sqrt{10}$. So the intersection point is,
$$x=(1,1) + \frac{1}{\sqrt{10}}(-3,1)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I clear Bootstrap 4 errors after I submit my React form? I'm using React 16.13.0 with Bootstrap 4.  I have the following component created, that I use in my React form ...
const Input = (props) => {
    return (

      <FormLabel>{props.title}</FormLabel>
      <FormControl
            isInvalid={props.errors && Boolean(props.errors[props.name])}
            type={props.type}
            id={props.name}
            name={props.name}
            value={props.value}
            placeholder={props.placeholder}
            onChange={props.handleChange}
          />

      {props.errors && props.errors[props.name] && (
          <FormControl.Feedback type="invalid">
                 {props.errors[props.name].map((error, index) => (
                     <div key={`field-error-${props.name}-${index}`} className="fieldError">{error}

                 ))}
          </FormControl.Feedback>
      )}

    )
}

export default Input;

Below is the handle form submit function as well as some of the container where I create my form ...
  async handleFormSubmit(e) {
    e.preventDefault();
    const NC = this.state.newCoop;
    delete NC.address.country;

    try {
      const response = await fetch(FormContainer.REACT_APP_PROXY + '/coops/',{
        method: "POST",
        body: JSON.stringify(this.state.newCoop),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const result = await response.json();
        window.flash('Record has been created successfully!', 'success')
        return result;
      }
      throw await response.json();
    } catch (errors) {
      console.log('_error_: ', errors);
      this.setState({ errors });
    }
  }

...

  render() {
    if (this.state.coopTypes && !this.state.coopTypes.length) {
      return null;
    }
    return (

        <form className="container-fluid" onSubmit={this.handleFormSubmit}>
            <FormGroup
                controlId="formBasicText">

                <Input inputType={'text'}
                   title= {'Name'}
                   name= {'name'}
                   value={this.state.newCoop.name}
                   placeholder = {'Enter cooperative name'}
                   handleChange = {this.handleInput}
                   errors = {this.state.errors}
                   /> {/* Name of the cooperative */}

The issue is, after I submit my form, if there were errors from the previous run, they are still displayed on the screen.

Is there a standard way to clear out Bootstrap error displays after a successful form submission?

A: Since you are using this.state.errors to provide the error information prop to your <Input> component, you simply need to update your handleInput(...) function to clear this.state.errors when your input value changes. The idea is something like this:
handleInput = (event) => {
  const errors = Object.assign({}, this.state.errors);
  const target = event.target;

  // remove the error value for a specific input only
  delete errors[target.name];
  this.setState({ errors });

  // Do whatever else needs to be done here for your input
}

Here's a working sample of how this works: https://jsfiddle.net/4gqr0cfa/

A: You need to add or remove form validation based on whether form is valid or not. To do this, add validated prop on the Form which is initially set to false.
How can i make it work?
Follow below mentioned steps:

*

*create a boolean state variable in the component containing the Form and its initial value should be false.
const [validated, setValidated] = useState(false);

*add a prop named validated on the form and set its value equal to the boolean state variable created in step 1.
<Form validated={validated}>
   ...
</Form>

*When form is submitted, check if form is valid, if it is, set state variable, validated, to true.
Here's a working demo

function App() {
  const [ validated, setValidated ] = React.useState(false);
  const [ form, setForm ] = React.useState({
    fields: {
      name: { type: 'text', value: '', title: 'Name' },
      email: { type: 'email', value: '', title: 'Email' },
      password: { type: 'password', value: '', title: 'Password' }
    },
    errors: {}
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    const errors = {};
    let invalid = false;

    Object.entries(form.fields).forEach(([k, v]) => {
      if (!errors[k]) errors[k] = [];

      if (!v.value) {
        errors[k].push(`${k} is required`);
        invalid = true;
      }

      if (k === 'email' && !v.value.includes('@')) {
        errors[k].push('enter a valid email address');
        invalid = true;
      }

      if (k === 'password' && v.value.length < 8) {
        errors[k].push('password should be atleast 8 characters long');
        invalid = true;
      }
    });

    setForm({ ...form, errors });

    if (invalid) {
      setValidated(false);
    } else {
      setValidated(true);
    }
  };

  const handleChange = ({ target }) => {
    const updatedField = { ...form.fields[target.name], value: target.value };

    const fields = {
      ...form.fields,
      [target.name]: updatedField
    };

    setForm({ ...form, fields });
  };

  return (

      <ReactBootstrap.Form noValidate validated={validated} onSubmit={handleSubmit}>
        {
          Object.entries(form.fields).map(([k, v]) => {
            return (
              <Input
                key={k}
                title={v.title}
                type={v.type}
                name={k}
                value={v.value}
                placeholder={v.title}
                handleChange={handleChange}
                errors={form.errors}
              />
            );
          })
        }
        <ReactBootstrap.Button type="submit">Submit form</ReactBootstrap.Button>
      </ReactBootstrap.Form>

  );
}

const Input = (props) => {
    return (
      <ReactBootstrap.Form.Group>
        <ReactBootstrap.FormLabel>{props.title}</ReactBootstrap.FormLabel>
        <ReactBootstrap.FormControl
          isInvalid={
            Array.isArray(props.errors[props.name])
             ? props.errors[props.name].length > 0
                 ? true : false
             : false
          }
          type={props.type}
          id={props.name}
          name={props.name}
          value={props.value}
          placeholder={props.placeholder}
          onChange={props.handleChange}
        />

        {props.errors && props.errors[props.name] && (
            <ReactBootstrap.FormControl.Feedback type="invalid">
                  {props.errors[props.name].map((error, index) => (
                      <div key={`field-error-${props.name}-${index}`} className="fieldError">{error}

                  ))}
            </ReactBootstrap.FormControl.Feedback>
        )}
      </ReactBootstrap.Form.Group>
    )
}

ReactDOM.render(<App />, document.getElementById('root'));
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />

You can also view the same demo on stackblitz
You can improve the above demo by indicating to the user that the input field is valid or invalid by adding green or red border repectively by using is-valid and is-invalid classes.

function App() {
  const [ validated, setValidated ] = React.useState(false);
  const [ form, setForm ] = React.useState({
    fields: {
      name: { type: 'text', value: '', title: 'Name' },
      email: { type: 'email', value: '', title: 'Email' },
      password: { type: 'password', value: '', title: 'Password' }
    },
    errors: {}
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    const errors = {};
    let invalid = false;

    Object.entries(form.fields).forEach(([k, v]) => {
      if (!errors[k]) errors[k] = [];

      if (!v.value) {
        errors[k].push(`${k} is required`);
        invalid = true;
      }

      if (k === 'email' && !v.value.includes('@')) {
        errors[k].push('enter a valid email address');
        invalid = true;
      }

      if (k === 'password' && v.value.length < 8) {
        errors[k].push('password should be atleast 8 characters long');
        invalid = true;
      }
    });

    setForm({ ...form, errors });

    if (invalid) {
      setValidated(false);
    } else {
      setValidated(true);
    }
  };

  const handleChange = ({ target }) => {
    const updatedField = { ...form.fields[target.name], value: target.value };

    const fields = {
      ...form.fields,
      [target.name]: updatedField
    };

    setForm({ ...form, fields });
  };

  return (

      <ReactBootstrap.Form noValidate validated={validated} onSubmit={handleSubmit}>
        {
          Object.entries(form.fields).map(([k, v]) => {
            return (
              <Input
                key={k}
                title={v.title}
                type={v.type}
                name={k}
                value={v.value}
                placeholder={v.title}
                handleChange={handleChange}
                errors={form.errors}
              />
            );
          })
        }
        <ReactBootstrap.Button type="submit">Submit form</ReactBootstrap.Button>
      </ReactBootstrap.Form>

  );
}

const Input = (props) => {
    return (
      <ReactBootstrap.Form.Group>
        <ReactBootstrap.FormLabel>{props.title}</ReactBootstrap.FormLabel>
        <ReactBootstrap.FormControl
          isInvalid={
            Array.isArray(props.errors[props.name])
             ? props.errors[props.name].length > 0
                 ? true : false
             : false
          }
          type={props.type}
          id={props.name}
          name={props.name}
          value={props.value}
          placeholder={props.placeholder}
          onChange={props.handleChange}
          className={
             Array.isArray(props.errors[props.name])
             ? props.errors[props.name].length > 0 ? 'is-invalid': 'is-valid'
             : ''
          }
        />

        {props.errors && props.errors[props.name] && (
            <ReactBootstrap.FormControl.Feedback type="invalid">
                  {props.errors[props.name].map((error, index) => (
                      <div key={`field-error-${props.name}-${index}`} className="fieldError">{error}

                  ))}
            </ReactBootstrap.FormControl.Feedback>
        )}
      </ReactBootstrap.Form.Group>
    )
}

ReactDOM.render(<App />, document.getElementById('root'));
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />

View this demo on stackblitz
You can read about the form validation in bootstrap at the official docs of react-bootstrap and bootstrap


text:
Q: How can i get City and State name from PlaceAutocomplete api? I have done the piece of code to get city name. But now as per new requriement i also need state name from the com.google.android.gms.location.places.ui.PlaceAutocomplete api.
You can refer the piece of code what i have done for getting city.
AutocompleteFilter autocompleteFilter = new AutocompleteFilter.Builder()
                    .setCountry("IN")
                    .setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS)
                    .build();

            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)//MODE_OVERLAY
                    .setFilter(autocompleteFilter)
                    .build(this);
            startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
            Utils.dismissProgressBar();
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                AppLog.log(TAG, "Place: " + place.getName());
                AppLog.log(TAG, "getAddress: " + place.getAddress());
                mCityName.setText(place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                AppLog.log(TAG, status.getStatusMessage());
                Toast.makeText(status.getStatusMessage(), true);
            } else if (resultCode == RESULT_CANCELED) {
                //Toast.makeText("Unable to find place", true);
            }
        }
    }

A: It works for me this way:
final Place place = PlaceAutocomplete.getPlace(this,data);
Geocoder geocoder = new Geocoder(this);
try
{
    List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);
    String city = addresses.get(0).getSubAdminArea();
    String country = addresses.get(0).getAdminArea();

} catch (IOException e){
    e.printStackTrace();
}

A: Using Geocoder We can get City name.
Try this.
final Place place = PlaceAutocomplete.getPlace(this,data);
Geocoder geocoder = new Geocoder(this);
try
{
    List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);
    String address = addresses.get(0).getAddressLine(0);
    String city = addresses.get(0).getAddressLine(1);
    //String country = addresses.get(0).getAddressLine(2);

} catch (IOException e){
    e.printStackTrace();
}


text:
Q: Shortcut to jump between declaration and implementation in XE7 I have been at this for hours. I want to rip my eyes out.
We use XE7 C++Builder. Is there a simple shortcut that allows a poor programmer like me to easily jump between the declaration of a method in a header file, to the implementation in the cpp file, and vice versa?
I found this link which says Shift+Ctrl+Down Arrow and Shift+Ctrl+Up Arrow should do it, but they don't. They simply don't work.
I know I can hover with the mouse and hold Ctrl on the keyboard, but this only opens the declaration. I want a simple shortcut to move in either direction (implementation to declaration and vice-versa).
Is there something else that needs to be enabled (in Tools>Options>Editor Options>Key Mappings )?

A: I hit Ctrl+F in the header file with the cursor at the beginning of the function name, which auto-populates the search box with the function name, then press Enter. Then I hit Ctrl+F6 (switch to cpp file), and then F3 (next instance of search).


text:
Q: Python JSON find parent node based on key I've got the following function which allows me to search through json and return the value of the key that is searched for.
However, I'm trying to find the actual parentNode of the key being searched for and finding this a bit difficult.
def bar(somejson, key):
    def val(node):
        # Searches for the next Element Node containing Value
        e = node.nextSibling
        while e and e.nodeType != e.ELEMENT_NODE:
            e = e.nextSibling
        return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e
                else None)
    # parse the JSON as XML
    foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),)))
    # and then search all the name tags which are P1's
    # and use the val user function to get the value
    return [val(node) for node in foo_dom.getElementsByTagName('name')
            if node.firstChild.nodeValue in key]

Ive tried using parentNode instead of firstChild, but its not working. Any idea where I'm going wrong?


text:
Q: Error when I was trying to render a map of items I am trying to figure out where my error is in my react js page
I have tried different things like changing it into a state component, return and render statements, etc. But its still giving me

"TypeError: Cannot read property 'map' of undefined
  Recipes
  src/components/Recipes.js:4
    1 | import React from "react";
    2 |
    3 | const Recipes = (props) => (
  4 |
    5 |      { props.recipes.map((recipe)=> {
    6 |         return (
    7 |
  View compiled"

App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import InputForm from "./components/InputForm";
import Recipes from "./components/Recipes"

const API_KEY= "mykey";

class App extends Component {

  state= {
    recipes: []
  }

  getRecipe  = async (e) => {
  e.preventDefault();
  const recipeName = e.target.elements.recipename.value;
  const api_call = await fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${recipeName}&page=2`)

  const data = await api_call.json();
  this.setState({ recipes: data.recipes });
}
  render() {
    return (

          React Cookbook

        <InputForm getRecipe={this.getRecipe} />
       <Recipes recipes={this.state.recipes} />

    );
  }
}

export default App;

Recipes.js
import React from "react";

const Recipes = (props) => (

     { props.recipes.map((recipe)=> {
        return (

{ recipe.title }

            )
        })}

)

export default Recipes;

A: As Andrew notes in the comments, it sounds like the response from the server is undefined, and that's what is getting added to the recipes state object. You can check for this in the console. Are your API key and recipe name valid, for example? Are you accessing the correct part of the returned data?
As an aside, recipes in state is empty on the first render. You need to check for that possibility in your code. Here I've simply returned an empty div, but you could add a loading spinner or something there instead to provide useful feedback to the user.
render() {

  const { recipes } = this.state;

  if (!recipes.length) return
;

  return (

        React Cookbook

      <InputForm getRecipe={this.getRecipe} />
      <Recipes recipes={recipes} />

  );

}


text:
Q: Trying to select li element with JQuery I am looking to get the text/data contained in between the opening and closing LI tags with JQuery. Below is the code that I am working with. The page as it stands right now will asyncriously go out and query a data base based on what I type into the form. I want to be able to click on on of the LI items and place it in a div labeled #in_attendance. Thanks for all the help in advance.
<!DOCTYPE html>

<title></title>

    <?php
        echo form_open('search/attend');
        echo form_input(array('name' => 'search', 'id' => 'search', 'autocomplete' => 'off'));
        echo form_close();
    ?>

A: The problem you have is your clcik handler is not going to bind to future elements. Use on() method to attach event to parent that is permanently in the page and by passing in the selector you want to handle the element "li" as second argument, clcik will register on "li" only
$("#selections").on('click','li',function() {
            alert($(this).text());
        });

A: In addition to using .on(), you could move the click handler to your $.post() complete event:
    $(document).ready(function() {
        $('#search').keyup( function() {
            var item = $('#search').val();
            var html = "";
            $.post("./search/attend", { 'search' : item },
            function(data){
                for(i=0; i<data.bro.length; i++){
                    options = data.bro[i].first_name, " ", data.bro[i].last_name;
                    html = html.concat("
", data.bro[i].first_name," ",data.bro[i].last_name,"
");
                }
                document.getElementById('selections').innerHTML = html;

                $("#selections li").click(function() {
                 alert($(this).text());
                });
            },
            "json");
        });
    });

A: You need to keep your event binded. See below for sample.
$('#selections li').live('click', function() {
  alert($(this).text());
});


text:
Q: Non-alphanumeric Characters sets not working I'm working to localize an app. I have my english xliff file that was translated. When I import the es.xliff (spanish) I get Localizable.strings (Spanish) and I can flip the app to Spanish, same with French.
For some reason with languages like Korean and Arabic ko.xliff and ar.xliff this is not working and I not getting a Localizable.strings file for this languages.
Any ideas?

A: The answer is to have the files in separate folders and choose them individually.


text:
Q: How to list users from all Identity Domains in Oracle Cloud Infrastructure? I need to retrieve a list of all users present in my Oracle Cloud environment via REST API or Go SDK.
Looking at the REST API docs, the Go SDK docs, and the OCI CLI docs, nowhere seems to provide an option to supply Identity Domain as an argument.
oci iam user list returns only the set of users present in the "Default" domain, even when I authenticate as a user in another domain.
Is there a way to fetch users from other Identity Domains?

A: Here is the REST API doc to list all users in the identity domain:
https://docs.oracle.com/en/cloud/paas/iam-domains-rest-api/op-admin-v1-users-get.html
Also, please use the domain URL for the API endpoint? Something like this: https://{domainUrl}/admin/v1/Users).
Unfortunately, we have Go SDK (or other SDKs and CLI) support only for IAM resources but not for Identity Domains (IDCS).
Thanks.


text:
Q: Is there a simple way to run an authenticated Google Analytics query using curl? I'd like to run a Google Analytics API query using curl, on the command line, and I am puzzled by the available authentication methods. I hoped I would simply get a client ID and a secret to pass along with the curl request, but all the OAuth authentication stuff looks like it insists on a round-trip through a server or a browser.
What's the easiest way to "persistently", once and for all until revoked, authenticate a command-line script to query Google Analytics, then? I don't want to open a browser each time I want to run the script.

A: This is what I have arrived at, so far:
{-# LANGUAGE OverloadedStrings #-}

import Data.Yaml
import Control.Monad
import Data.ByteString.Char8 (pack, unpack)
import Data.Monoid
import Network.Google.OAuth2
import Network.HTTP.Conduit
import Network.HTTP.Types (hAuthorization)
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as L8

data OAuth2Credentials = OAuth2Credentials {
    getClientID :: String,
    getClientSecret :: String
} deriving (Show, Eq)

instance FromJSON OAuth2Credentials where
    parseJSON (Object value) = OAuth2Credentials <$>
        value .:  "clientID" <*>
        value .:  "clientSecret"
    parseJSON _ = mzero

parseOAuth2Credentials :: String -> Maybe OAuth2Credentials
parseOAuth2Credentials source = Data.Yaml.decode $ pack source

main :: IO ()
main = do
    source <- readFile "analytics-credentials.yml"
    let creds = parseOAuth2Credentials source
    case creds of
        Just creds -> do
            let client = OAuth2Client (getClientID creds) (getClientSecret creds)
            token <- getAccessToken client authScope (Just tokenCacheFile)
            request <- parseUrl analyticsQueryURL
            response <- withManager $ httpLbs $ authorize token request
            L8.putStrLn $ responseBody response
        Nothing -> return ()
    where
        authorize token request = request { requestHeaders = [(hAuthorization, B8.pack $ "Bearer " <> token)] }
        analyticsQueryURL = "…"
        authScope = ["https://www.google.com/analytics/feeds/"]
        tokenCacheFile = "analytics-token.yml"

Not exactly curl and not exactly simple, but after the initial browser-based token generation the access tokens are cached in a file and subsequent requests don't need any human interaction.


text:
Q: Non-isomorphic modules generated by one element Let $G$ be a finite abelian group. I have the $\mathbb{C}[G]$-module, $\mathbb{C}[G]=n_{1}V_{1}\oplus \cdots\oplus n_{r}V_{r}$, where the $V_{i}$ form a complete set of irreducible submodules of $\mathbb{C}[G]$. I know that every $n_{i}$  equal to $1$ because $G$ is abelian.
I'm trying to understand why the submodules are definitely  non isomorphic. How can I prove that ?
I know that its right but I don't know why.

A: The irreducible (i.e. simple) submodules are nonisomorphic because they have distinct annihilators.
$V_1$ is annihilated by $0\oplus V_2\oplus V_3\oplus\cdots$ and $V_2$ is annihilated by $V_1\oplus 0 \oplus V_3\oplus\cdots$ and so on.

A: There are as many non-isomorphic modules as conjugacy classes, so in your notation $r \geq |G|$ since the list is complete. By a dimension argument, you can see that each is $1$-dimensional and can appear only once.


text:
Q: How does this soft charge circuit work?

This circuit is a DC bus capacitor soft charge from a 3phase inverter.
I've seen a lot of similar products but this one is a little strange and I'm curious how it works.
I want to know why the transformer's output is rectified(I assume) knowing that the contactor works with AC.

A: Perhaps there is a hidden center tap on the transformer secondary that connects to the circuit common (L3) through the lower primary lead.
A center-tap connection would answer another mystery about the circuit pointed out in another answer: Because of the series capacitor connected to the collector of the PNP transistor, the timer circuit can't energize RL indefinitely.
With RL initially open (and assuming a center tap), the hypothesis is that the half-wave-rectified DC applied to the contactor is not enough to pull it in. When the timer closes RL after the soft-charge period, both diodes can conduct, and the contactor sees the full-wave-rectified output of the transformer. The full-wave-rectified voltage closes the contactor. Finally, the timer allows RL to open (because of the PNP series capacitor), but the half-wave-rectified voltage is now sufficient to hold the contactor closed.
If this is how the circuit works, I'm curious about the operating margins. Under high-line conditions, the initial half-wave-rectified voltage could risk closing the contactor before it should close. However, doubling the average coil voltage between half-wave and full-wave rectification roughly quadruples the magnetic force, so good margins are plausible with a carefully selected transformer voltage. If margins aren't a problem, an advantage of this kind of approach is that it reduces static power consumption by de-energizing the relay and lowering the coil power of the contactor when the soft-charge cycle is complete.

A: The schematic around the left side of the transformer can't be correct.  Please retrace that part of the circuit and make corrections.
It very much looks as if the contactor coil is driven with pulsating DC.
The capacitor in the middle of the bottom diagram looks not correct.  I don't think that it is in series with the signal.  Could you re-check that as well?


text:
Q: Is there a generic method for cloning CLOS objects? I'm looking for a way to clone CLOS objects in a shallow manner, so the created object would be of the same type with the same values in each slot, but a new instance. The closest thing I found is a standard function copy-structure which does this for structures.

A: Here's a slightly different version of the function submitted by danlei.  I wrote this a while ago and just stumbled across this post.  For reasons that I don't entirely recall, this calls REINITIALIZE-INSTANCE after copying.  I think it's so you could make some changes to the new object by passing additional initargs to this function
e.g.
(copy-instance *my-account* :balance 100.23)

This is also defined as generic function over objects that are 'standard-object's.  Which might or might not be the right thing to do.
(defgeneric copy-instance (object &rest initargs &key &allow-other-keys)
  (:documentation "Makes and returns a shallow copy of OBJECT.

  An uninitialized object of the same class as OBJECT is allocated by
  calling ALLOCATE-INSTANCE.  For all slots returned by
  CLASS-SLOTS, the returned object has the
  same slot values and slot-unbound status as OBJECT.

  REINITIALIZE-INSTANCE is called to update the copy with INITARGS.")
  (:method ((object standard-object) &rest initargs &key &allow-other-keys)
    (let* ((class (class-of object))
           (copy (allocate-instance class)))
      (dolist (slot-name (mapcar #'sb-mop:slot-definition-name (sb-mop:class-slots class)))
        (when (slot-boundp object slot-name)
          (setf (slot-value copy slot-name)
            (slot-value object slot-name))))
      (apply #'reinitialize-instance copy initargs))))

A: There is no standard predefined way to copy CLOS objects in general. It is not trivial, if possible at all, to provide a reasonable default copy operation that does the right thing (at least) most of the time for arbitrary objects, since the correct semantics change from class to class and from application to application. The extended possibilities the MOP provides make it even harder to provide such a default. Also, in CL, being a garbage collected language, copying of objects is not really needed very often, e.g. when passed as parameters or being returned. So, implementing your copy operations as needed would probably be the cleanest solution.
That being said, here is what I found in one of my snippet files, which might do what you want:
(defun shallow-copy-object (original)
  (let* ((class (class-of original))
         (copy (allocate-instance class)))
    (dolist (slot (mapcar #'slot-definition-name (class-slots class)))
      (when (slot-boundp original slot)
        (setf (slot-value copy slot)
              (slot-value original slot))))
    copy))

You will need some MOP support for class-slots and slot-definition-name.
(I probably adopted this from an old c.l.l thread, but I can't remember. I never really needed something like this, so it's utterly untested.)
You can use it like this (tested with CCL):
CL-USER> (defclass foo ()
           ((x :accessor x :initarg :x)
            (y :accessor y :initarg :y)))
#<STANDARD-CLASS FOO>
CL-USER> (defmethod print-object ((obj foo) stream)
           (print-unreadable-object (obj stream :identity t :type t)
             (format stream ":x ~a :y ~a" (x obj) (y obj))))
#<STANDARD-METHOD PRINT-OBJECT (FOO T)>
CL-USER> (defparameter *f* (make-instance 'foo :x 1 :y 2))
*F*
CL-USER> *f*
#<FOO :x 1 :y 2 #xC7E5156>
CL-USER> (shallow-copy-object *f*)
#<FOO :x 1 :y 2 #xC850306>

A: This solution does not require sl-mob:
(defun copy-slot (s d slot)
  `(setf (,slot ,d) (,slot ,s)))

(defun copy-by-slots (s d slots)
  (assert (eql (class-of s) (class-of d)))
  (let ((f (lambda (s$) (eval (copy-slot s d s$)))))
    (mapcar f slots)))

(copy-by-slots src dest quoted-list-of-slots)

A: I mention a dirty trick producing a clone of a CLOS instance.
(defclass cl () ((sl1 :initarg :sl1) (sl2 :initarg :sl2)))

(defmethod update-instance-for-different-class ((copy cl) (original cl) &key)
  (setf clone copy))

(setf a (make-instance 'cl :sl1 111 :sl2 222))

(change-class a 'cl)

(eq clone a) -> NIL
(eql (slot-value a 'sl1) (slot-value clone 'sl1)) -> T

Implies CLOS itself needs a notion of clone.


text:
Q: ASP.NET C# SQL Server Money format I have a issue I'm developing a webshop but when I have to post the data on to the Payment Gateway I need to money to be like 1,00$ to be 100 but in the SQL Server database it's 1,0000 and when I use the price formatstring {0:c} so how do I convert it to 100?

A: take the dollars * 100 to get it to the whole number value.  Do not use the string formatter and you will just have the numeric value.
ie
(Price*100).ToString();


text:
Q: How can I get two numbers that are written in a single line - is there a Split() method? I want to ask the user for input in console. He'll be writing down two numbers separated by a single space.
In Java is there something like the C# Split() method I can use?
Thank you!

A: Yes, there is: String.split. Note that it takes a regex as the parameter though. Alternatively you could use a StringTokenizer or a Scanner.

A: There is a split() method in String class.
String.split();


text:
Q: dynamical height of article tag Have trouble dynamically adjusting content blocks, their height in particular.
have code structure(don't mind if missed any closing tags or etc., they are there in running version):

        some content(might involve image)

        some more content

      some more content
      some bottom content

  .....

..

So issue, sometimes some of content is to long so it overflows my default height of 265px. I would like to make it more dynamical and make height adapt, but as all articles need to align according to design guidelines, the height of all articles need to be the same, in other words, if I dynamically adjust height from 265px to 280px on one article it should be the same height on all other. I was thinking about some js checks, but as there is a lot events(filters, searches and etc., everything is asynchronous it is a lot to cover with js).
Any ideas on CSS solutions?
Looked into flexbox CSS solution, but it doesn't seem to adapt good on so many layers of content in article.
Any suggestions, possible solutions or links would help a lot.
Thanks in forward!

A: Here you have a good article about the topic with different approaches.
I like the One True Layout Method:
HTML:

I am listed first in source order.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit
      amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

CSS:
#one-true { overflow: hidden; }
#one-true .col {
    width: 27%;
    padding: 30px 3.15% 0;
    float: left;
    margin-bottom: -99999px;
    padding-bottom: 99999px;
}
#one-true .col:nth-child(1) { margin-left: 33.3%; background: #ccc; }
#one-true .col:nth-child(2) { margin-left: -66.3%; background: #eee; }
#one-true .col:nth-child(3) { left: 0; background: #eee; }
#one-true p { margin-bottom: 30px; } /* Bottom padding on col is busy */

demo

A: Is this what you're looking for? http://jsfiddle.net/swm53ran/91/

    Here is some content

    Here is some content

    Here is some content

    Here is some content

$(document).ready(function() {
    var height = 0;
    $('.content').each(function() {
        if (height < $(this).height()) {
            height = $(this).height();
        }
    });
    $('.content').each(function() {
        $(this).height(height);
    });
});

A: Enclose the articles in divs and then use flex box. Then use the flex-box-grow and flex-box-shrink properties on the items


text:
Q: Browser back-button in AJAX problem I try to enable a brwoserback button for my tabs. But the problem is that in some cases the the hash dissapears.
function showTab1(){
    window.location.hash = 'tab1';
    oldHash = window.location.hash;
    //showTab1
}
function showTab2(){
    window.location.hash = 'tab2';
    oldHash = window.location.hash;
    //showTab2
}
function checkBrowserBackButtonInHome(){

    setInterval(function(){
        if(window.location.hash != oldHash) {
            //Do something
        }
    }, 50);
}
showTab1();

and than I click on showTab2. And when I click on the browser back button the hash dissapears. index.php instead of index.php#tab1
EDIT:
It seems like this only happens in chrome web browser

A: try using this instead of the interval:
$(window).bind('hashchange', function() {
  //Do something
});


text:
Q: Emacs Doom: Define Interactive Function to Mark a String in Buffer I am simply trying to write an interactive emacs function that switches butters and marks a string. The function switches buffers and finds the string, but does not mark it. What am I missing? Thanks in advance for any advice.
(defun pubmed-find-pmid ()
  "From PubMed-Search buffer select `pmid' in PubMed-Entry buffer "
  (interactive)
  (other-window 1)
  (re-search-forward "PMID: ")
  (set-mark-command)
  (doom/forward-to-last-non-comment-or-eol))


text:
Q: Polymorphic vector Hi can someone please explain what is wrong with the following code?I am first including the child of an abstract class in another class which will be using this child.
#include "child.h"

Then I'm populating the 2d vector below with pointers which point to instances of the child.
vector<vector<abstractitem*>*>vec;

I am then using this class function in my class. The function get is found in the abstract class.
void fn::getall()
{
    for (int i=0;i<m_nrows;i++)
    {
        for(int j=0;j<m_ncolumns;j++)
        {

            vec[i][j]->get(); //error on this line: do you intend to use . instead?

        }
        printf("\n");
    }

}

Your help  will be much appreciated.

A: you either need to change
vector<vector<abstract*>*> vec;

into
vector<vector<abstract*>> vec;

or change
vec[i][j]->get();

into
(*vec[i])[j]->get();

the former is probably better, there is no good reason why the outer vector should hold pointers to the inner vector.
even better would be using smart pointers:
vector<vector<shared_ptr<abstract>>> vec;

it frees you completely from object memory management

A: Notice that your outer vector is a vector of pointers to vectors, not a vector of vectors. This means that your function call resolves like this:
vec[i][j]->get();
(vector<abstractitem*>*)[j]->get();
*(vector<abstractitem*>* + j)->get();
vector<abstractitem*> ->get();

You can see the error in the last line: your get() function is attempting to run on a vector, but you wrote it expecting it to be an abstractitem*.
Either change your declaration to a vector of vectors, or add a dereference to your call:
vector<vector<abstractitem*>> vec; //option 1
(*vec[i])[j]->get(); //option 2


text:
Q: get the matching part out of cloudant json I'm working with cloudantDB as DB for my spring application.
The thing that I'm trying to do is:

*

*check if there is a timeslot and topic in the document

*if there is a topic filled in:

*check the userId who has submitted that topic and return all of the items for that user.

{
  "_id": "393c7748cf487f7c5223839dfdf5adf9",
  "_rev": "2-889c6d9d14fcc3c90a00e91aca5f2f4c",
  "name": "conference 1",
  "type": "conference",
  "location": "conf loc",
  "tag": "confTag",
  "startDate": "2015-05-04T22:00:00.000+0000",
  "endDate": "2015-05-08T22:00:00.000+0000",
  "timeslots": {
    "8a03b160-48e3-4f99-be38-2a2da34e5890": {
      "id": "8a03b160-48e3-4f99-be38-2a2da34e5890",
      "startDate": "2015-04-07T10:45:00.000+0000",
      "endDate": "2015-05-07T12:45:00.000+0000",
      "location": "Location",
      "topic": {
        "id": "4ad235ef-5938-4461-8a2e-346bf105c5b6",
        "title": "wa nen coole title",
        "description": "dees is een goei omschrijving",
        "tags": "cloud, tag",
        "attachment": "file.exe",
        "speakerId": null
      }
    },
    "a59b1dfd-d1c5-491f-bc02-807e38595ba4": {
      "id": "a59b1dfd-d1c5-491f-bc02-807e38595ba4",
      "startDate": "2015-05-05T10:00:00.000+0000",
      "endDate": "2015-05-05T11:15:00.000+0000",
      "location": "mlkjs",
      "topic": {
        "id": "8b753adb-9a15-486f-9209-b9cc5ef134a1",
        "title": "test132",
        "description": "met speakerId",
        "tags": "sldkjf",
        "attachment": "kklsjdf",
        "speakerId": "speaker"
      }
    },
    "080153e7-f8bc-453e-b49a-a1df4679ceef": {
      "id": "080153e7-f8bc-453e-b49a-a1df4679ceef",
      "startDate": "2015-05-09T11:30:00.000+0000",
      "endDate": "2015-05-09T13:30:00.000+0000",
      "location": "file upload",
      "topic": {
        "id": "e3533a60-a0ba-4439-a9e9-b29e69be47db",
        "title": "fdgdfg",
        "description": "fdsgdsggdfgdfg",
        "tags": "dfgsdg",
        "attachment": null,
        "speakerId": null
      }
    }
  },
  "defaultTwitterText": "Hallo",
  "twitterUrl": "https://twitter.com/intent/tweet?button_hashtag=confTag&text=Hallo"
}

So far I have this:
function(doc) {
{ if (doc.type === 'conference') {
    if(doc.timeslots.size !==0 ){
            emit( null, doc);
        }
    }
  }
}

Thanks!

A: I think you might want something like:
function (doc) {
    if (doc.type == 'conference'){
    if (doc.timeslots){
            for (var i in doc.timeslots) {
                if(doc.timeslots[i].topic){
                    emit(doc.timeslots[i].topic.speakerId, doc.timeslots[i])
                }
            };
        }
    }
}

that'll make a view of key:speaker, value: topic object, which you can then query with ?key=speaker to see the list of all the topic objects for the speaker.


text:
Q: Obtain XML section in string VB.NET I'm using vb.net and I have a WebService that sends me a SOAP envelope as a result.
<?xml version="1.0" encoding="utf-8"?>

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <tfd:Answer DateAnswer="2014-05-02T17:19:38" Certificate="30001000000100000801" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    </soapenv:Body>
</soapenv:Envelope>

I'm already able to obtain individual values from inside de XML like DateAnswer or Certificate but now I need to receive the whole section with the "Answer" tag for later storage. In other words this:
<tfd:Answer DateAnswer="2014-05-02T17:19:38" Certificate="30001000000100000801" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

Is there a simple way to obtain this whole section in a string? I've looked it up but I sense I'm not using the correct key words for the search.

A: Here is the code I used to solve my problem.
Dim Xns As XNamespace = XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/")
mySection = myXMLDocument.Descendants(Xns + "Body").First().FirstNode.ToString()

"mySection" contains the string I need.


text:
Q: for loop in R: How to apply a defined function to loop through rows and columns in R? I have a dataset named trainset that has 50 variables. For each row, I need to sum up the values under columns called Systolic.Blood.Pressure, Blood.Urea.Nitrogen, Blood.Sodium, Age, heart.rR and COPD values. I already defined a function to sum these up:
m.gwtg = function(Systolic.BP, Sodium, COPD){
  if (Systolic.BP>=200){
    pt.sbp = 0
  }else if (Systolic.BP>= 190){
    pt.sbp = 2
  }else if (Systolic.BP>= 180){
    pt.sbp = 4
  }else if (Systolic.BP>= 170){
    pt.sbp = 6
  }else if (Systolic.BP>= 160){
    pt.sbp = 8
  }else if (Systolic.BP>= 150){
    pt.sbp = 9
  }else if (Systolic.BP>= 140){
  if (Sodium>=139){
    pt.sodium =  0
  }else if (Sodium>= 137){
    pt.sodium =  1
  }else if (Sodium>= 134){
    pt.sodium =  2
  }
  if (Age>=110){
    pt.age = 28
  }else if (Age>= 100){
    pt.age = 25
  }else if (Age>= 90){
    pt.age = 22
  }else if (Age>= 80){
    pt.age = 19
  }else if (Age>= 70){
  if (COPD == 1){
    pt.copd =2
  } else {
    pt.copd = 0
  }
  total = pt.sbp + pt.bun+ pt.sodium +pt.age + pt.hr+ pt.copd
  return(if (total < 79){
    outcome = 0
  } else {
    outcome = 1
  })
}

I have problem with coding out the for loop to loop through the trainset and apply the function defined for each row. I tried to code the loop like this:
for (i in 1:nrow(trainset)) {
  Systolic.BP[i] <- trainset$Systolic.blood.pressure[i]
  Sodium[i]  <- trainset$Blood.sodium[i]
  COPD[i]  <- trainset$COPD[i]
  total[i] <- Systolic.BP[i]+ Sodium[i] +COPD[i]

  outcome.gwtg.trainset[i]= m.gwtg(total[i])

}

I got quite confused on on the code out the for loop. Thanks for any answers!

A: This is a more concise way to calculate the outcome:
library(tidyverse)

calc_score <- function(systolic_bp, bun, sodium) {
  systolic_bp_score <- case_when(
    systolic_bp >= 200 ~ 0,
    systolic_bp >= 190 ~ 2,
    systolic_bp >= 180 ~ 4
  )
  bun_score <- case_when(
    bun >= 150 ~ 28,
    bun >= 140 ~ 27
  )
  sodium_score <- case_when(
    sodium >= 139 ~ 0,
    sodium >= 137 ~ 1
  )
  systolic_bp_score + bun_score + sodium_score
}

# example data
trainset <- tibble(
  systolic_bp = c(180, 195),
  bun = c(145, 180),
  sodium = c(138, 140)
)

trainset %>%
  mutate(
    score = list(systolic_bp, bun, sodium) %>% pmap_dbl(calc_score),
    outcome = as.numeric(score > 97)
  )
#> # A tibble: 2 × 5
#>   systolic_bp   bun sodium score outcome
#>         <dbl> <dbl>  <dbl> <dbl>   <dbl>
#> 1         180   145    138    32       0
#> 2         195   180    140    30       0

Created on 2022-03-25 by the reprex package (v2.0.0)

A: You should avoid loops and similar functions (eg, *apply() and purrr::map()) whenever possible in R. R is designed to work with vectors, and loops are much much slower.
Instead of this loop operation, do the following:

*

*Recode each column into its transformed values

*Add up the transformed values

*Recode the transformed values into the 0/1 outcome

These operations should be done vector-wise to be efficient (and to avoid the tricky indexing problems you are encountering).
For example:
m.gwtg <- function(data) {
  data <- dplyr::mutate(data,
    pt.sbp = dplyr::case_when(
      Systolic.BP >= 200 ~ 0,
      Systolic.BP >= 190 ~ 2,
      Systolic.BP >= 180 ~ 4,
      Systolic.BP >= 170 ~ 6,
      Systolic.BP >= 160 ~ 8,
      Systolic.BP >= 150 ~ 9,
      Systolic.BP >= 140 ~ 11,
      Systolic.BP >= 130 ~ 13,
      Systolic.BP >= 120 ~ 15,
      Systolic.BP >= 110 ~ 17,
      Systolic.BP >= 100 ~ 19,
      Systolic.BP >=  90 ~ 21,
      Systolic.BP >=  80 ~ 23,
      Systolic.BP >=  70 ~ 24,
      Systolic.BP >=  60 ~ 26,
      Systolic.BP >=  50 ~ 28, # should Systolic.BP < 50 be NA or 28?
      # else
      TRUE ~ NA_real_
    ),
    pt.bun = dplyr::case_when(
      BUN >= 150 ~ 28,
      BUN >= 140 ~ 27,
      BUN >= 130 ~ 25,
      BUN >= 120 ~ 23,
      BUN >= 110 ~ 21,
      BUN >= 100 ~ 19,
      BUN >=  90 ~ 17,
      BUN >=  80 ~ 15,
      BUN >=  70 ~ 13,
      BUN >=  60 ~ 11,
      BUN >=  50 ~  9,
      BUN >=  40 ~  8,
      BUN >=  30 ~  6,
      BUN >=  20 ~  4,
      BUN >=  10 ~  2,
      BUN  <  10 ~  0,
      # else
      TRUE ~ NA_real_
    ),
    pt.sodium = dplyr::case_when(
      Sodium >= 139 ~ 0,
      Sodium >= 137 ~ 1,
      Sodium >= 134 ~ 2,
      Sodium >= 131 ~ 3,
      Sodium  < 131 ~ 4,
      # else
      TRUE ~ NA_real_
    ),
    pt.age = dplyr::case_when(
      Age >= 110 ~ 28,
      Age >= 100 ~ 25,
      Age >=  90 ~ 22,
      Age >=  80 ~ 19,
      Age <=  70 ~ 17,
      Age >=  60 ~ 14,
      Age >=  50 ~ 11,
      Age <=  40 ~  8,
      Age >=  30 ~  6,
      Age >=  20 ~  3,
      Age  <  20 ~  0,
      # else
      TRUE ~ NA_real_
    ),
    pt.hr = dplyr::case_when(
      HR >= 105 ~ 8,
      HR >= 100 ~ 6,
      HR >=  95 ~ 5,
      HR >=  90 ~ 4,
      HR >=  85 ~ 3,
      HR >=  80 ~ 1,
      HR  <  80 ~ 0,
      # else
      TRUE ~ NA_real_
    ),
    pt.copd = dplyr::case_when(
      COPD == 1 ~ 2,
      COPD == 0 ~ 0,
      # else
      TRUE ~ NA_real_
    ),
    total = pt.sbp + pt.bun + pt.sodium + pt.age + pt.hr + pt.copd,
    outcome = dplyr::if_else(total < 79, 0, 1)
  )
  return(data)
}

example_data <- data.frame(
  Systolic.BP = c(170, 160, 200),
  BUN = c(60, 150, 10),
  Sodium = c(134, 131, 139),
  Age = c(40, 80, 20),
  HR = c(90, 105, 80),
  COPD = c(1, 0, 0)
)

m.gwtg(example_data)
#>   Systolic.BP BUN Sodium Age  HR COPD pt.sbp pt.bun pt.sodium pt.age pt.hr
#> 1         170  60    134  40  90    1      6     11         2     17     4
#> 2         160 150    131  80 105    0      8     28         3     19     8
#> 3         200  10    139  20  80    0      0      2         0     17     1
#>   pt.copd total outcome
#> 1       2    42       0
#> 2       0    66       0
#> 3       0    20       0

Created on 2022-03-25 by the reprex package (v2.0.1)


text:
Q: Update object instance with partial using three dot notation Let me start with an example:
let john = {
    name: "John",
    age: 21
}

let newAge = {
    age: 22
}

john = {...john , ...newAge};

By doing the above I can update john by passing the newAge object with the dot notation (spread operator). The advantage here is that it is easy to extend this behavior and easily update the values of an object by passing the updated values in partial object.
I want to do something similar with a class.
interface IPerson {
    name?: string;
    age?: number;

class Person implements IPerson {
    update(value: IPerson) {
        // somehow make it work?
    }
}

I just don't see how I can do this with this.
Is this possible?


text:
Q: Unity3D Resources Folder and memory I'm currently trying to understand how Unity creates its builds because my teams is creating a texture heavy game and it's crucial that we have enough memory for the game to function in the various environments (specifically web and iOS).
To test out the memory, I created a scene with a 166MB Resources folder and a cube. If you want to try it you can download it here: http://www.mediafire.com/?a137tz6anatf6qi. The cube's for debugging purposes: When the scene is just loaded, it's green. It changes to blue and a second later starts to load all the textures in Resources. When it turns red it unloads all unused assets (which is basically everything because I didn't assign the textures to anything).
Now I've read about the disadvantages of Resources folder in various places, but my issue is: with an empty scene and one game object, when the scene just starts, the process already takes up more than 600MB in the task manager!! After loading all Resources, it goes up to 1.3GB. Why? What is the 600MB that is being loaded? And how come the Resources folder bloats up by ~6 times?? I read something about the compression actually increasing the file size of the images, is that true?

A: You do not specify if you are running a build or in editor mode. I'm guessing you are running in editor mode, and I think Unity loads all resources in editor mode in case you want to change something on the fly.
Make an actual build of your cube test project and re-check the memory usage. According to this, it will not even put your unused resources in the build (and as far as my experience goes, that is true).
Unity is already very efficient on doing what you want (outside the editor mode), so I think you shouldn't have to worry too much with it. Take a trial version of Unity IOs and build your cube project for actual device testing.
This page lists texture compression types you can use for each platform. You may want to check out:
"RGB Compressed PVRTC 2 bits    Compressed RGB texture. Lower quality format suitable for diffuse textures. 2 bits per pixel (16 KB for a 256x256 texture)"


text:
Q: SQL BEGINNERS QUERY I have two columns in a table MEM and SUB, like below
| MEM | | SUB |
|-----| |-----|
| 101 | | 101 |
| 201 | | 201 |
| 202 | | 201 |
| 203 | | 201 |
| 301 | | 301 |

How do I find out the SUB which has no MEM beside itself?
How can I query to find the row like 101 and 301?
PS: I'm new into this, pardon me if the information is incomplete.

A: This will give you all the subs where the Mem and Sub are not the same.
SELECT SUB
    FROM TABLE
    WHERE MEM <> SUB

This will give you a distinct list of Sub's that, at one point or another, do not have a matching MEM.
SELECT DISTINCT SUB
    FROM TABLE
    WHERE MEM <> SUB

EDIT:

I WANT TO FIND OUT ALL SUB THATHAS ONLY ONE MEM

This is a really simple SQL query.  You'll probably learn it better if you did some research.
Regardless, here is what you need:
SELECT SUB
  , COUNT(MEM) AS CountOfMem
     FROM TABLE
     GROUP BY SUB
     HAVING COUNT(MEM) = 1

If this is it, make sure to mark it as answered.


text:
Q: Hyper parameters to tune in Bayesian network? In tree based models and neural networks, we can optimised the models by tuning the hyper parameters(such as: learning rate, number of neutrons.. etc). Is there a hyper parameters to tune in Bayesian networks?
Thank you,
Shosho


text:
Q: How to get past null characters in a file posted to an asp.net form? I have an asp.net MVC application that takes in uploaded NMEA track files from small GPS loggers.  In some cases, the loggers will inject null (0x0) values into the track file text.  Is there a way to strip out these 0x0 characters from the HttpPostedFile's InputStream before saving the file to the server's file system for processing?  As it is, I can only get to the first null character and that's all of the file that gets saved on the server.
Thanks,
Matthew

A: InputStream is binary and shouldn't care about zeros. So, the problem is with the data conversion to text - but you didn't show the code that you use to convert.
You may manually skip/replaces zeros:
var outstream = new StringStream();
var b;
while ((b = http.InputStream.ReadByte()) != -1)
  if (b != 0)
      outstream.Write(b);

and now you got stream without zeros (of course you can read in blocks, etc, if you want to).

A: If you use SaveAs, it should write zeros. Can you check the InputStream content in debugger (for example using my reading method above) - are you sure that HttpPostedFile does contain zeros - that is, that you receive data correctly? Do you use ENCTYPE="multipart/form-data" for your upload form?


text:
Q: How to edit the environment variable $LD_LIBRARY_PATH? I want to add the Intel MKL library path to the environment variable
$LD_LIBRARY_PATH. I added the following script in the ~/.bashrc file:
MKL=/home/nby/install_software/intel/composerxe/mkl # this is the path where the MKL installed
export LD_LIBRARY_PATH=$MKL/lib/intel64:$LD_LIBRARY_PATH

Then I checked whether the mkl path has been successfully added. In the terminal, I tried like this,
source ~/.bashrc
echo $LD_LIBRARY_PATH

I found the mkl path is NOT shown. I don't know why? Could anyone help me? THX!

A: How about trying this:
export MKL=/home/nby/install_software/intel/composerxe/mkl
export LD_LIBRARY_PATH=$MKL/lib/intel64:$LD_LIBRARY_PATH

The first export ensures that the MKL variable is defined for all child bash processes.


text:
Q: Why does thread.join fail when called in destructor of global variable I reduced my problematic code to the following. I have a class C that runs a member function on its own thread. In the destructor of C I want to cleanly exit this thread. This works fine as long as c is defined within main (1), but not when it is a global variable (2). In the latter case, I see that the thread function returns but that the t.join() hangs.
#include <mutex>
#include <condition_variable>
#include <thread>
#include <iostream>

using namespace std;

class C
{
public:
    C()
    {
        stop = false;
        t = thread(&C::ThreadFunc, this);
    }
    ~C()
    {
        stop = true;
        cv.notify_all();
        if (t.joinable())
        {
            cout << "joining" << endl;
            t.join();
            cout << "joined" << endl;
        }
    }

private:
    void ThreadFunc()
    {
        while (true)
        {
            unique_lock<mutex> lock(m);
            cv.wait(lock, [&]{return stop;});
            cout << "returning" << endl;
            return;
        }
    }

    thread t;
    mutex m;
    condition_variable cv;
    bool stop;
};

C c;  // does *not* work (2)

int _tmain(int argc, _TCHAR* argv[])
{
    C c;  // does work (1)
    return 0;
}

The reason I use a global variable is that it is actually part of a dll. When the destructor is triggered from DllMain on DLL_PROCESS_DETACH, the same problem occurs.
Is there an explanation and a solution to this problem?

A: It's a deadlock. You are holding a lock that t requires in order to terminate while you are waiting for t to terminate.
Say as part of t's detach process, it makes some calls into the DLL. How can the DLL sensibly handle a request when there is a thread (the thread that called join) that is partially attached to it? Once you start detaching, and until you finish detaching, the DLL is an inconsistent state and cannot sensibly handle thread attach and detach operations.
You really don't want to try to join a thread while your process is in a context you can't control.


text:
Q: Subfields of splitting field I recently started learnig field and Galois theory and was given this problem:
Given polynomial over Q
$\displaystyle f=2x^{6} \ −\ 4x^{5} \ −\ 3x^{4} \ −\ x^{3} \ +\ 8x^{2} \ +\ 6x\ −\ 6\ \in \ Z[ x] \ $
find splitting field K of f, and determine degree [K : Q].
Then find all subfields M of K satisfying [K : M]=2.
I managed to find splitting field K as $\displaystyle \mathbb{Q}\left( \sqrt[3] 2,\zeta _{3,}\sqrt{3}\right) \ $
and [K : Q] = 12
where $\displaystyle \zeta _{3}$ is 3rd root of unity.
I also think that galois group  of f is non abellian.
However when I try to figure out to what group it is precisely I get stuck.
If I missunderstood something or made mistake, please let me know. If not, how should I proceed?

A: Hint: We have
$$
f=(x^3 - 2)(2x^2 - 6x + 3)(x + 1).
$$
Further references:
Galois group of a reducible polynomial over $\mathbb {Q}$
Galois group of a reducible polynomial


text:
Q: Convert a Javascript Audio Player timestamp to a C# TimeSpan? I'm not sure the best way to word this question but hoping someone can decipher what i'm asking lmao.
I have a system of timestamps in C#:
"beatTime": "00:00:05.0840000"

which gets converted to a TimeSpan via JSONDeserializer.
I am trying to make a way of capturing times in a React app using javascript, which captures time from the audio player like this:
"beatTime": 226.539319

besides the obviously stringification, i'm wondering if anyone knows the format of either the C# or javascript one so I can convert it?
Thanks...hope this kinda made sense


text:
Q: Designing a GraphQL schema for an analytics platform I'm just starting to explorer GraphQL as an option for my analytic platform API layer.
My UI is mainly built from tables and charts. most of the times the data represents some DB columns grouped by a dimension.
I've found the following article https://www.microsoft.com/developerblog/2017/09/28/data-independent-graphql-using-view-model-based-schemas/ from Microsoft, describing their take on how suck GraphQL schemas should be designed (see below).
type Query {
  channels(source: String!, query:String!, appId:String!, apiKey:String!): [Channel]
  lineCharts(source: String!, query:String!, appId:String!, apiKey:String!, filterKey:String, filterValues:[String]): [LineChart]
  pieCharts(source: String!, query:String!, appId:String!, apiKey:String!): [PieChart]
  barCharts(source: String!, query:String!, appId:String!, apiKey:String!, filterKey:String, filterValues:[String]): [BarChart]
}

type Channel {
  name: String
  id: Int
}

type LineChart {
  id: String
  seriesData : [Series]
}

type PieChart {
  id: String
  labels: [String]
  values: [Int]
}

type BarChart {
  id: String
  seriesData : [Series]
}

type Series {
  label: String
  x_values: [String]
  y_values: [Int]
}

It seems to me that this design is strict, forcing any new chart to be added to the root Query. How can the schema be more generic, without loosing GraphQL benefits?

A: You could do something with union types and inline/fragments
union Chart = LineChart | PieChart | BarChart

type Query {
  charts(
    source: String!
    query: String!
    appId: String!
    apiKey: String!
    filterKey: String
    filterValues: [String]
  ): [Chart]
}

Then you can have your charts resolver bring ALL the charts and write your queries like
fragment Identifiers on Chart {
  __typename
  id
}
query {
  charts(...) {
    ...on LineChart {
      ...Identifiers
      seriesData
    }
    ...on PieChart {
      ...Identifiers
      labels
      values
    }
    ...on BarChart {
      ...Identifiers
      seriesData
    }
  }
}

The Identifiers will provide you with some information about what type you're dealing with and it's id, but you can extend it to whatever you like as long as those fields are common to all types on that union (or you can spread it only on some of the types).
There are 2 ways you can go about if you don't want to bring in all the charts:

*

*Add inline fragments for only the types you want, but the rest will still be there, in the form of empty objects.

*Pass another argument to the resolver representing the type/s you want

P.S. You can get as granular as you like, there are also interfaces and input types.


text:
Q: Is there a javascript event when items are added to or removed from the DOM? I'm trying to build a Chrome browser extension, that should enhance the way the twitter website behaves in Google Chrome. I want to mark the top tweet that gets moved down when new tweets are loaded, and scroll to it.
I'm able to fetch the top tweet before the click by hooking the mousedown event using .live(). After that, I have to wait until the tweets are loaded, before I scroll down to the previous tweet. I have a hack in place with a setTimeout() now, and that works for me, but I'd like a better solution.
Possible solutions:

*

*Somehow hook an event that fires when elements are loaded to a div

*Hook an event that fires when an element gets removed from the DOM

A: Since you are targeting Google Chrome, you could use the DOM Level 2 Mutation Events, specifically:

*

*DOMNodeInserted

*DOMNodeRemoved
You can bind them by using addEventListener:
someElement.addEventListener('DOMNodeInserted', eventHandlerFunction, false);

Or since you're using jQuery's, with the bind method:
$(selector).bind('DOMNodeInserted', function () {
  //..
});

Be careful to not modify the affected DOM in those events, because you could get into an infinite event recursion, for example, if you insert an element in the DOMNodeInserted event, it will fire again.


text:
Q: Add element to function in place C++ Add element to function in place C++
Python code:
l1 = [1, 2, 3]
l2 = l1 + [4]
print(l2) #[1, 2, 3, 4]

l3 = l1+l2
print(l3) #[1, 2, 3, 1, 2, 3, 4]

Is there a way to do this in C++

A: You clarified in a comment that you want to do it "in place". In C++17 there isn't an operator or function in the standard library for concatenating two vectors (or containers), but it is pretty easy to create one yourself:
template <class T>
std::vector<T> concat(const std::vector<T>& v1, const std::vector<T>& v2)
{
    auto res = v1;
    res.insert(res.end(), v2.begin(), v2.end());
    return res;
}

In C++20 all this changes as we will get ranges.
Until then you can use the ranges-v3 library (on which the standard ranges are based):
views::concat(v1, v2);

This returns a range. That should be enough as you should take range views as parameters or at least iterators. The advantage is that views are lazy. They don't do the actual transformations until you iterate over them and don't create new containers. If you however still need a vector you can do that like this:
#include <range/v3/view.hpp>

using namespace ranges;

auto test()
{

    std::vector v1{10, 20, 30};
    std::vector v2{1, 2, 3, 4, 5};

    auto v = views::concat(v1, v2) | to<std::vector>();
}

There has been a comment about creating an overloaded operator+ instead of the function. That would be a bad idea for a few reasons:
Overloading an operator with only standard classes as parameters is a bad idea as you can't open namespace std to define it there and defining it elsewhere will cause problems with ADL.
Second, even if you could, a golden rule is to overload an operator to do expected things. In this case, an operator+ would be expected by (some/most) people to do element-wise addition.

A: I believe you're trying to add an element to a vector in c++.
vector<int> v;       // { }
v.push_back(10);     // { 10 }

To append one vector to another vector, you could use insert
vector<int> v = { 11, 12 };
vector<int> v2 = { 13, 14 };

v.insert(v.end(), v2.begin(), v2.end());     // { 11, 12, 13, 14 }

The first parameter to insert is an iterator pointing to where you want the second vector's elements to be inserted. The 2nd and 3rd parameters are the iterators pointing to the beginning and end of the second vector, they denote the boundaries of which elements to insert into the first vector.
This operation effectively appends the second vector into the first vector.


text:
Q: What algorithm is used when rows in tables are sorted? Let's assume that we have a table with two columns. The table contains data and our goal is to sort that table.
Assume our data looks like this, where y1 and y2 are the data in the columns.

You can produce that plot with MATLAB or GNU Octave.
% Simulate the model
[t,y] = ode45(@odefunc,[0 20],[1; -2]);

% Plot the simulation
close all
plot(t,y(:,1),'-r',t,y(:,2),'-b')
title('Solution of van der Pol Equation (\mu = 1) with ODE45');
xlabel('Time t');
ylabel('Solution y');
legend('y_1','y_2')
grid on

function dydt = odefunc(t,y)
  dydt = [y(2); (1-0.1*y(1)^2)*y(2)-y(1) + 1];
end

If we look above the plot, we are going to se the data like this:

You can create that plot with this code:
% Plot 3D bar
figure
imagesc(y)
colorbar

Here we can see that the plot have a very much like a "table-look". My question is what algorithm is used when sorting the rows in the table so every row that looks almost the same, have it's own unique position in the table.
For example, if we have a table like this.
0 2 4
1 3 5
2 4 6
3 5 7
4 6 8
5 7 9
0 2 4
1 3 5
2 4 6
3 5 7
4 6 8
5 7 9
0 2 4
1 3 5
2 4 6
3 5 7
4 6 8
5 7 9
0 2 4
1 3 5

The code if you want to create that table.
j = 0;
rows = 20;
for i = 1:rows
  disp(sprintf("%i %i %i", j, j+2, j+4))
  j = j + 1;
  if(j + 4 >= 10)
    j = 0;
  end
end

We can see that there are four rows of 0 2 4 and three rows of 5 7 9.
I want all rows 0 2 4 close to each other and all rows 5 7 9 close to each other. And.... 0 2 4 cannot be after 5 7 9 because then the plot would look terrible.
For example, assume that we begining with row 1, the first row 0 2 4. Then we are looking for the same rows of 0 2 4 and let's say we found four rows 0 2 4. Then we sort them.
0 2 4
0 2 4
0 2 4
0 2 4

Now next row would be 1 3 5 and we find two rows of 1 3 5. We sorting them.
0 2 4
0 2 4
0 2 4
0 2 4
1 3 5
1 3 5

After we have sorted for a while, we are going to have a table like this.
0 2 4
0 2 4
0 2 4
0 2 4
1 3 5
1 3 5
2 4 6
2 4 6
2 4 6
2 4 6
3 5 7
3 5 7
3 5 7
.
.
.
.
5 7 9
5 7 9
5 7 9

And now, we found 1 2 4, which is very similar to 0 2 4. So we need to place 1 2 4 close to 0 2 4, perhaps between 0 2 4 or 1 3 5 or after 0 2 4 or before 0 2 4. How do I even know that 1 2 4 should be placed close to 0 2 4? That's the issue!!!.
How can I sort that?
I need to do that in C-programming language because speed is most important here, but I think I will start to do it in GNU Octave. I'm pretty sure that there is a SQL-sorting algorithm I'm looking for.
Notice in practice, there are numbers, integers, 10-bit e.g values between 0-1023.


text:
Q: how to show count increment value on icon on next page after clicking from first page button  class ContentPage extends Component {

     constructor(){
    super()
    this.state = {
      data: '',
      count: 0 ,
    }
    this.handleClick = this.handleClick.bind(this)
        this.deletehandle = this.deletehandle.bind(this)

  }

      handleClick(){
    this.setState(prevState => {
      return {
        count: prevState.count + 1
      }
    })
  }
   deletehandle(){
  if (this.state.count === 0) {
      this.setState({
        counter: 0
      });
    } else {
      this.setState(prevState => ({
        count: this.state.count - 1
      }));
    }

   }

this is my increment and decrement code on first page and after on press handleclicked it increases and the state value i want to show is on next page on icon
i have used

                    {this.state.count}

          </View>
          <View style={{alignItems:'flex-end',alignContent:'flex-end',marginLeft:260}}>
     <View style={{flexDirection:'row'}}>
            <Text style={{fontSize: 18}}> Quantity : </Text><Text style={{fontSize:18}}>{this.state.count}</Text>
          </View>
         </View>

<View style={{height: 4, width: 30}} />
            <TouchableOpacity
            // onPress={this._AddCart}
            onPress={this.handleClick}
              style={{
                height: 40,
                width: 130,
                backgroundColor: 'orange',
                justifyContent: 'center',
                alignItems: 'center',
                borderRadius:8
              }}>
              <Text style={{color:"#FFFFFF",fontSize:15}} >Add to Cart{this.state.count}</Text>
            </TouchableOpacity>

edited my code now showing my count state in the same page but i want to show my count numbers on next screen ?

A: This example is just focusing on how to pass the data as props from the parent to the child component. So please ignores the syntax and other issues.
// Parent Component
class ParentComponent extends Component {
  // Pass count to Child Component as props
  <ChildComponent count={this.state.count}/>
}

// Child Component
class ChildComponent extends Component {
  // call count in child component using props
  this.props.count
}

A: You need to pass your count property down to the component where you want to use it (exactly like @Sourav Singh has shown in his answer). I composed an increment/decrement example for you, hope you find it helpful:
https://codesandbox.io/s/react-typescript-429re
Also, you might find some interesting insights in Components and Props article from official React documentation.


text:
Q: Embed C Struct - Function In Python I'm writing a little MySql C program which should be embed in Python code. For demonstration purposes program will execute MySql INSERT and SELECT commands on database. How can I make this struct and function to work in python code and pass MySql result to python or cdef variable.
Can someone help, thanx in advance !
HERE IS MY C WORKING CODE:
HEADER FILE: "chi2.h"
struct _MYSQL
{
char *server;
char *user;
char *password;
char *database;
char *table;
char *ptr_statement;
char *user_input;
MYSQL *connection;
MYSQL_RES *result;
};
MYSQL_RES *_GET_MYSQL(struct _MYSQL *DATA);

C CODE FILE: "chi2.c"
#include "/usr/include/python2.7/Python.h"
#include "mysql.h"
#include "stdio.h"
#include "stdlib.h"
#include "chi2.h"

MYSQL_RES *_GET_MYSQL(struct _MYSQL *DATA)
{
DATA->result = NULL;
DATA->ptr_statement = NULL;
DATA->connection = mysql_init(NULL);

/* Connect to database */
if (!mysql_real_connect(DATA->connection, DATA->server, DATA->user, DATA->password, DATA->database, 0, NULL, 0))
{
mysql_close(DATA->connection);
fprintf(stderr, "%s\n", mysql_error(DATA->connection));
exit(1);
}

/* Get MySql query */
DATA->ptr_statement = malloc(sizeof(int) * 16);   // int is 4 bytes * 16 (64 bytes * 8 = 512 bits)
snprintf(DATA->ptr_statement, *(DATA)->ptr_statement, "INSERT INTO hash (hash_name) VALUES ('%s')", DATA->user_input);
if(mysql_query(DATA->connection, DATA->ptr_statement))
{
free(DATA->ptr_statement);
DATA->user_input = NULL;
mysql_close(DATA->connection);
fprintf(stderr, "%s\n", mysql_error(DATA->connection));
exit(1);
}
mysql_commit(DATA->connection);
free(DATA->ptr_statement);
DATA->user_input = NULL;

DATA->ptr_statement = malloc(sizeof(signed short int));   // short int is 2 bytes (16 bits)
sprintf(DATA->ptr_statement, "SELECT * FROM %s", DATA->table);
if (mysql_query(DATA->connection, DATA->ptr_statement))
{
free(DATA->ptr_statement);
mysql_close(DATA->connection);
fprintf(stderr, "%s\n", mysql_error(DATA->connection));
exit(1);
}

mysql_commit(DATA->connection);
free(DATA->ptr_statement);
DATA->result = mysql_use_result(DATA->connection);
return DATA->result;
mysql_close(DATA->connection);
mysql_free_result(DATA->result);
}

int main(int argc, char *argv[])
{
struct _MYSQL *DAT;
MYSQL_ROW ROW;
MYSQL_RES *RESULT = NULL;

DAT->server = "localhost";
DAT->user = "test1";
DAT->password = "test1";
DAT->database = "test";

DAT->table = "hash";
DAT->user_input = "HELLO :D";
RESULT = _GET_MYSQL(&(*DAT));
while ((ROW = mysql_fetch_row(RESULT)) != NULL)
printf("%s - %s \n", ROW[0], ROW[1]);
}

mysql_free_result(RESULT);
RESULT = NULL;
ROW = NULL;
DAT->table = NULL;
DAT->user_input = NULL;

//fflush(stdin);
//system("clear");
return EXIT_SUCCESS;
}


text:
Q: To retrieve the value from one dialog box and display it in another dialog I am having a dialog box which ask for your name and address and when you click ok button it opens another dialog where it should display the name and address.I have tried it using ajax post ,but nothing seems to work in the desired way.Please help me out.Thanks in advance.
Here is what I have tried:
display.php:
<input type="button" id="dialog_open" name="dialog_open" value="dialog_open" ></input>

<form action = "" method="post">

        Name :<input type="text" class="form-control input-sm" name="name" id="name" />
        Address: <textarea row="3" col="50" class="form-control input-sm" name="address" id="address" ></textarea>

            <?php echo $_POST['keyname']; ?>

Address:<?php echo $_POST['keyadd']; ?>

my script code:


text:
Q: Casting A String To An Int From A JTextField In Java So I'm trying to use the text entered in a TextField as an Int... heres my code
int command1 = (int) (command.getText());

But I get the error "Cannot cast from string to int" an I can't figure it out... can anyone help?
p.s. the text in the TextField is not numbers so
int command1 = (int) (Double.parseDouble(command.getText()));

Will not work...

A: You need to parse the string containing the integer, not simply cast it.
int aInt = Integer.parseInt(aString);

Edit: "P.S. The Text In The TextField Is NOT Numbers "   you can't create an int out of something that is not a number.  "ABC" cannot be an int.

A: Use the Integer wrapper object...
int iVal = Integer.parseInt(String);


text:
Q: How can I get correct COLLATE clause with Forward Engineer SQL CREATE Script of MySQL Workbench? I'm using MySQL Workbench 6.2.5.0 build 397 (32bits).
I have a table which is something like the following screenshot:

Note that I've specified utf8mb4 - utf8mb4_bin as Collation that supposed to be used in SQL that will be produced by Export => Forward Engineer SQL CREATE Script. But it doesn't work as I expected. It produces the definition of column as follows:
  `idtable1` VARCHAR(16) CHARACTER SET 'utf8mb4' NOT NULL,

This is not what I want. I want the following one instead:
  `idtable1` VARCHAR(16) COLLATE utf8mb4_bin NOT NULL,

How can I get that? Do I have any missing settings for Workbench?


text:
Q: Comparing two directory recursively, copy content of directory to third directory using shell script I have two directories say A and B.
I want to compare directory B with A.
Directory A and directory B have many common directories(contains is same) and file.
If file is not present in directory A then copy file to directory C by maintaining directory structure.
e.g. If in Directory A following relative path not is not exist.
B/hellboy/MyScripts/dir1/

I want to copy this path and descendant files and directory to directory C.
I  tried a lot with the diff command. But I think it is not possible. Please help me to get out of this.

A: Have a look at rdiff-backup (a relative of rsync), it might provide what you want out of the box.

A: Does the following script snippet come close to what you are looking for?
#!/usr/bin/env bash

# Setup for testing:
# mkdir -p A/l1-{1,2,3}/l2-{4,5,6}
# mkdir -p B/l1-{2,3,4,5}/l2-{1,2,3,4}
# touch B/l1-{3,4,5}/l2-{2,3,4}/file-${RANDOM}
# touch {A,B}/l1-2/l2-4/never_goes_to_C

while read f d _; do
  if [ -e "A/$f" ]; then
    echo "---> FOUND: A/$f"
  else
    echo "---> NOT FOUND: A/$f, moving to C"
    mkdir -p "C/$d" && cp -a "B/$f" "C/$d"
  fi;
done < <(cd B; find . -printf "%p %h\n")


text:
Q: jQuery preloading of external website Let's say my main site is called
mainsite.com

On my mainsite.com I have a bunch of external links, such as:
external.com/search.php?type=xxx&date=xxx&id=xxx&product=xxx

When my visitors click on these links they load fine for all but one problem. They take 20-30 seconds to load!
The reason for this is the target URL on external.com is performing a product search.
So what I'm finding is my visitors are leaving before the link loads!
Anyone have any solutions I can try?
I can not make any changes to external.com as it's not my site! I can only add something to mainsite.com.

A: Use AJAX to load the remote sites into a hidden DIV as soon as your main page loads. When the user clicks on the link, hide the main DIV and show the corresponding DIV.  Since AJAX runs asynchronously in the background, the loading will happen while the user is reading the main page, and hopefully it will be done by the time they click on the link.
Another option is to use AJAX at the time the user clicks on the link. While waiting for the page to arrive, display a spinner and a message saying "This takes a while, please wait...".


text:
Q: Swing - Group Layout I am coding a GUI in Swing and I am using Grouplayout
Here is my code:
    GroupLayout tLayout = new GroupLayout(card3ContentPane);
    card3ContentPane.setLayout(tLayout);
    tLayout.setAutoCreateGaps(true);
    tLayout.setAutoCreateContainerGaps(true);

    tLayout.setHorizontalGroup(tLayout.createSequentialGroup()
            .addGroup(tLayout.createParallelGroup()
                    .addComponent(label))
                    .addGroup(tLayout.createParallelGroup()
                            .addComponent(lname)
                            .addComponent(lpreis)
                            .addComponent(lalter)
                            .addComponent(lkategorie))
                            .addGroup(tLayout.createParallelGroup()
                                    .addComponent(textname)
                                    .addComponent(textpreis)
                                    .addComponent(textalter)
                                    .addComponent(combo)
                                    .addComponent(bsuchen))
                                    .addGroup(tLayout.createParallelGroup()
                                            .addComponent(table))
            );

    tLayout.setVerticalGroup(tLayout.createSequentialGroup()
            .addComponent(label)
            .addGroup(tLayout.createParallelGroup()
                    .addComponent(lname)
                    .addComponent(textname))
                    .addGroup(tLayout.createParallelGroup()
                            .addComponent(lpreis)
                            .addComponent(textpreis))
                            .addGroup(tLayout.createParallelGroup()
                                    .addComponent(lalter)
                                    .addComponent(textalter))
                                    .addGroup(tLayout.createParallelGroup()
                                            .addComponent(lkategorie)
                                            .addComponent(combo))
                                            .addGroup(tLayout.createParallelGroup()
                                                    .addComponent(bsuchen))
                                                    .addGroup(tLayout.createParallelGroup()
                                                            .addComponent(table)));

    log.info("Leave showWarenSuchen");

}

Here is a screen-shot of how it looks like right now:  http://www.bilder-space.de/bilder/e7423f-1332615779.jpg
How can I place them in a vertical order, not so chaotic like right now?


text:
Q: why map function give undefined while iteration? const a=[{name:'ee'},{name:"ddsf"}]
const b=a.map(({name})=>{
  if(name!='ee')
  return {
    key:'dd',
    name:name +'sss'
  }
})

console.log(b)

I am getting
[undefined, [object Object] {
  key: "dd",
  name: "ddsfsss"
}]

why  undefined ?
Expected output
[[object Object] {
  key: "dd",
  name: "ddsfsss"
}]

here is code
https://jsbin.com/wujekavivo/edit?html,js,console,output

A: You want .filter before .map.
const b = a.filter(o => o.name != 'ee')
  .map(o => ({
      key: 'dd',
      name: o.name + 'sss'
    })
  );

This is because .map always returns an array of length equal to the original. By filtering first, you're reducing it down to the desired set.
You can also use .reduce() to accomplish both at once.
const b = a.reduce((o, acc) =>
    o.name == 'ee' ? acc : acc.concat({
      key: 'dd',
      name: o.name + 'sss'
    })
, []);

A: The map function returns an array that has correspondence with the array you iterate to. So the undefined value corresponds to the first item in the array with name: 'ee'. If you just want to get those with name !== 'ee', you can just use filter instead. Or better yet you can do:
a.reduce((arr, {name}) => {
  if(name === 'ee') {
    arr.push({
      key: 'dd',
      name: name + 'sss',
    });
  }
  return arr;
}, []);

Unlike map, reduce you pretty much have more control.


text:
Q: Convert filename-date to datetime I have files with filenames like filename-0001#18-02-2012^16.04.43.JPG.
I have split the file names to extract the date/time part.
Now I want convert that part (e.g. 18/02/2012 - 16:04:43) to something like 1482581580 so I can sort by date/time.
This is my code:
$convert =

$string = $withoutExt;
$find = array('/_/', '/\./', '/-/');
$replace = array('/', ':', '/');
$result = preg_replace($find, $replace, $string);
$split   = preg_split('/\/00|\^|#/', $result);
//print_r($split);
$korrasNimi = $split[0];

$date = $split[2];
$time = $split[3];

<td data-order="<?php echo $convert ?>">

       <?php echo $kuupaev; echo ' - ' echo $kellaaeg; ?>

How can I get the numerical representation of the date?

A: If you have a string like 18/02/2012 - 16:04:43 then you can create datetime object from a certain format:
$date = DateTime::createFromFormat('d/m/Y - H:i:s', '18/02/2012 - 16:04:43');
$timestamp = $date->format('U');
echo $timestamp;


text:
Q: WordPress отказывается показывать карту для *НЕ* администраторов здравствуйте подскажите пожалуйста,такая дичь происходит.Если зайти на страницу администратором,то видно карту.Когда заходишь гостем\пользователем\кем-угодноНеадмином,то карта не грузится.Просто пустой div,сайт кинуть не могу,так как на локальном.Подключаю файл map.php через include строчки кода:
map.php

Подключается в файле тут:

<?php include('map.php'); ?>

UPD: Выдаёт блок как надо,просто нету визуализации карты.

A: Тег script предназначен для описания скриптов, может содержать ссылку на программу или ее текст на определенном языке.
Одновременно добавлять и то и другое нельзя.
Разделите код и загрузку апи на два тега script.


text:
Q: How to display project structure in java I have a error in a project I am currently working on. I wanted to post the problem in Stack overflow and want to display project structure like this :
src
├── main
│   └── java
│       └── Main.java
├── manifest.txt
├── run.sh
└── test
    └── java
        └── MainTest.java

I have copied this structure from another question. I am currently using eclipse and maven as well. If i amnot clear about my question.. here it is again. how to get project structure of a java project I am working on-like done above- ?? )Sorry for the bad english. not my first language)

A: The simplest way I know to resolve this is using OS commands. In that case, the question was already answwered in other posts like this
In Windows you can run the following commands in a cmd terminal:

*

*cd the\root\folder\of\your\project

*tree /f or tree /f > tree.txt
In Linux, the tree command should be available in most distributions.
You could use it by typing in a command terminal:

*

*tree /the/root/folder/of/your/project
If you are looking for a specific feature in Eclipse, then I can't help you. I don't know if such a feature exists.


text:
Q: DGM1, virtual raster error I want to create a virtual raster with DEM1, existing of 133 tiles (QGIS 3.18.3). It show following processing warning:
GDAL command:
gdalbuildvrt -resolution average -separate -r nearest -input_file_list C:/Users/v.dosky/AppData/Local/Temp/processing_1eb4cddcda444e0d8d1834f5567da2b6/59fdb7c3769b4883ae765e00a787f3dc/buildvrtInputFiles.txt "//fileserver/freigabe/02_Projekte"

GDAL command output:
Warning 6: gdalbuildvrt does not support positive NS resolution. Skipping //fileserver/freigabe/02_Projekte/DGM1_Kacheln_DTMBIN1UTM_406000_5296000_dtm.xyz
Warning 6: gdalbuildvrt does not support positive NS resolution. Skipping //fileserver/freigabe/02_ProjekteBearbeitung/02_GIS/02_Rohdaten/DGM1_Kacheln_DTMBIN1UTM_406000_5296000_dtm.xyz

and following Python error:
2021-09-15T10:38:31     WARNING    warning:C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\requests\status_codes.py:18: DeprecationWarning: invalid escape sequence \o

 traceback: File "", line 1, in
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 354, in startPlugin
  if not _startPlugin(packageName):
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 334, in _startPlugin
  plugins[packageName] = package.classFactory(iface)
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\__init__.py", line 29, in classFactory
  from MetaSearch.plugin import MetaSearchPlugin
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\plugin.py", line 34, in
  from MetaSearch.dialogs.maindialog import MetaSearchDialog
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\dialogs\maindialog.py", line 50, in
  from owslib.csw import CatalogueServiceWeb # spellok
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\owslib\csw.py", line 27, in
  from owslib.util import OrderedDict
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\owslib\util.py", line 32, in
  import requests
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\requests\__init__.py", line 114, in
  from .models import Request, Response, PreparedRequest
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\requests\models.py", line 43, in
  from .status_codes import codes
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 724, in exec_module
  File "", line 860, in get_code
  File "", line 791, in source_to_code
  File "", line 219, in _call_with_frames_removed

2021-09-15T10:38:31     WARNING    warning:C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py:737: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
  mod = _builtin_import(name, globals, locals, fromlist, level)

 traceback: File "", line 1, in
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 354, in startPlugin
  if not _startPlugin(packageName):
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 334, in _startPlugin
  plugins[packageName] = package.classFactory(iface)
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\__init__.py", line 29, in classFactory
  from MetaSearch.plugin import MetaSearchPlugin
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\plugin.py", line 34, in
  from MetaSearch.dialogs.maindialog import MetaSearchDialog
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\dialogs\maindialog.py", line 56, in
  from MetaSearch.dialogs.manageconnectionsdialog import ManageConnectionsDialog
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\dialogs\manageconnectionsdialog.py", line 35, in
  from MetaSearch.util import (get_connections_from_file, get_ui_class,
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins\MetaSearch\util.py", line 35, in
  from jinja2 import Environment, FileSystemLoader
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\jinja2\__init__.py", line 33, in
  from jinja2.environment import Environment, Template
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\jinja2\environment.py", line 15, in
  from jinja2 import nodes
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 1035, in _handle_fromlist
  File "", line 219, in _call_with_frames_removed
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\jinja2\nodes.py", line 19, in
  from jinja2.utils import Markup
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 983, in _find_and_load
  File "", line 967, in _find_and_load_unlocked
  File "", line 677, in _load_unlocked
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\jinja2\utils.py", line 485, in
  from collections import MutableMapping
  File "C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python\qgis\utils.py", line 737, in _import
  mod = _builtin_import(name, globals, locals, fromlist, level)
  File "", line 1032, in _handle_fromlist
  File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\collections\__init__.py", line 52, in __getattr__
  DeprecationWarning, stacklevel=2)*


text:
Q: Is that the type of browser is important when using karma? I'm a Karma beginner, and I was wondering if the type of browser (firefox, chrome, phantom etc.) does really matter, because all the results will be displayed on the terminal.
Could anyone tells me why we should bother with the browser ?

A: There are many reasons why you want to choose a browser for testing: first of all cross-browser compatibility.
Once you've created your web-app you want that the behavior of your functions/features are consistent on any browser you are expecting from your customer base.
If you want to be more specific: IE most of the time is what you want to test.
Note that if you are running covering metrics on your tests, some branches of the code might be executed only by some specific browser agents (and versions) sometimes.
Sometimes it's convenient run your tests on some headless browser (such PhantomJS) to run faster (even though I'm not sure it's faster than Chrome on Karma, due to a known issue)


text:
Q: cassandra: create supercolumn using Perl In Cassandra 1.0 the Thrift interface doesn't support batch_insert anymore. What's the current method to insert a supercolumn via perl?

A: batch_mutate replaced batch_insert in 0.7.