text:
Q: Why is networkd changing the MAC addresses of my bonded interfaces? When I add the config files below into /etc/systemd/network and restart systemd-networkd, I find that the MAC addresses of bond0, eth0 and eth2 have all been changed to a single, locally administered address. This breaks DHCP, and doesn't follow the expectation set by the Linux kernel bonding documentation that states that the bond interface will take the MAC address of one of its slaves.
According to the networkd documentation, the issue appears to be this:

MACAddress=
The MAC address to use for the device. For "tun" or "tap" devices, setting MACAddress= in the "[NetDev]" section is not supported. Please specify it in "[Link]" section of the corresponding systemd.network(5) file. If this option is not set, "vlan" devices inherit the MAC address of the physical interface. For other kind of netdevs, if this option is not set, then MAC address is generated based on the interface name and the machine-id(5).

(Emphasis mine.)
How do I prevent this MAC address generation and tell networkd to just use one from the slaves?
Files
10-bond0.netdev
[NetDev]
Name=bond0
Kind=bond

[Bond]
Mode=802.3ad

10-bond0.network
[Match]
Name=bond0

[Network]
DHCP=ipv4

20-eth0.network
[Match]
Name=eth0

[Network]
Bond=bond0

20-eth2.network
[Match]
Name=eth2

[Network]
Bond=bond0

A:
How do I prevent this MAC address generation and tell networkd to just use one from the slaves?

As far as I know this is not possible. In my project I do set it up using another script. According to Debian Systemd docu Systemd-networkd may assign different MAC then the one of physical interface.
You can fix it manually adding MACAddress=xx:xx:xx:xx:xx:xx
I know you didn't mention the OS, but still, your symptoms fit to the Debian...

A: Here is sample interface and bond file config, MACADDR may solve your issue.
#Redhat/Centos
#  cat /etc/sysconfig/network-scripts/ifcfg-eno1
DEVICE=eno1
NAME=eno1
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
NM_CONTROLLED=no

# cat /etc/sysconfig/network-scripts/ifcfg-eno2
DEVICE=eno2
NAME=eno2
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
NM_CONTROLLED=no

# cat /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
NAME=bond0
TYPE=Bond
MACADDR=a0:36:9f:0f:b1:70         #Assigning fixed mac address
ONBOOT=yes
BOOTPROTO=dhcp
NM_CONTROLLED=no
BONDING_OPTS="mode=active-backup primary=eno1 miimon=100"

Or for Ubuntu
#eth0 interace file
auto eth0
iface eth0 inet manual
bond-master bond0
bond-primary eth0

#eth1 interace file
auto eth1
iface eth1 inet manual
bond-master bond0

#bond file
auto bond0
iface bond0 inet static
hwaddress ether xx:xx:xx:xx:xx:xx         #fixed mac address
address x.x.x.x                           #Your can remove these lines if it's dhcp
netmask x.x.x.x
gateway x.x.x.x
bond-mode active-backup
bond-miimon 100
bond-slaves none


text:
Q: Using result of Solve in further calculations I'm trying to make a code for Gauss-Legendre quadrature. First I find the roots of the polyinomial with
roots[n_,x_]:=Solve[LegendreP[n, x] == 0]

Then I need to make $n$ functions which are products of $n-1$ terms, in the form of
$$
\prod_{\substack{j=1\\j\neq i}}^{n} \frac{x-x_j}{x_i-x_j}
$$
with the $x_j$ being elements of roots[n,x], but I have to exclude $x_i$ in each function.
I tried this:
w[i_, x_] := Product[(x - roots[n, x][[j]])/(roots[n, x][[i]] -
   roots[n, x][[j]]), {j, 1, n}, j!=i]

but I get an error Part specification j is neither an integer nor a list of integers. So now I have two concerns, is there a way to make a product (mind you, I need to make $n$ products for an arbitrary integer $n$) with skipping one iteration, and how do I use the results I get from Solve in the definition of w?

A: You can extract roots from a Solve command using the replacement operation /.:
xroots[n_]:= Solve[LegendreP[n, x] == 0]
roots[n_]:= x /. xroots[n]

Your Product call combined with an If condition, as suggested in the comment above, should do the trick.
w[i_, x_] :=
Product[
If[i==j,1,
(x - roots[n][[j]])/(roots[n][[i]] - roots[n][[j]])
]
,{j,1,n}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Injection of a field from a ScriptableObject I have a ScriptableObjectInstaller
public class Settings : ScriptableObjectInstaller<Settings>
{
    [Header("Gravity settings")] public GravityHandler.Settings GravitySettings;
    [Header("Movement settings")] public MovementHandler.Settings MovementSettings;

    public override void InstallBindings()
    {
        Container.BindInstance(GravitySettings);
        Container.BindInstance(MovementSettings);
    }
}

and a class
public class GravityHandler : IGravityHandler
{
    private readonly Settings _settings;
    private readonly BoxCollider2D _groundBox2D;

    public GravityHandler(BoxCollider2D groundBox2D, Settings settings)
    {
        _groundBox2D = groundBox2D;
        _settings = settings;
    }

    public bool IsGrounded()
    {
        if (_groundBox2D.OverlapCollider(_settings.ContactFilter2D, null) > 0)
            return true;
        return false;
    }

    [Serializable]
    public class Settings
    {
        public ContactFilter2D ContactFilter2D;
        public Vector3 GravityForce=new Vector2(0, -9.8f);
    }
}

All I want is to be able to change Settings.GravitySettings, and then inject its value into GravityHandler._settings, so i can use the settings inside GravityHandler.
But when I validate my scene it shows me an error:

ZenjectException: Unable to resolve type 'GravityHandler+Settings' while building object with type 'GravityHandler'.
  Object graph:
  Player
  MovementHandler
  GravityHandler

What do I do wrong and how to fix this?

A: Okay, I just forgot to put the scriptable object into SceneContext. I also had to change its name to match the name of the class.


text:
Q: show spinner before adding widget android For a widget I am creating for the Android OS, I want the user to first select a certain option from a Spinner. Just like when you add a shortcut to the homescreen.
Is that possible or do you have to start an Activity?
If it is possible, can anyone explain how to do it?

A: Spinner widgets do not exist on their own -- you have to have them in an Activity. Android's app widget framework supports the notion of a configuration activity that is automatically launched when somebody chooses your widget. Just put your Spinner in there.


text:
Q: Python write to csv with comas in each field I'm trying to export a list of strings to csv using comma as a separator. Each of the fields may contain a comma. What I obtain after writing to a csv file is that every comma is treated as a separator.
My question is: is it possible to ignore the commas (as separators) in each field?
Here is what I'm trying, as an example.
import csv

outFile = "output.csv"
f = open(outFile, "w")

row = ['hello, world' , '43333' , '44141']

with open(outFile, 'w') as writeFile:
    writer = csv.writer(writeFile)
    writer.writerow(row)

writeFile.close()

The output looks like this: outputObtained
What I would like is something like this: outputExpected
I think a way to solve this would be to use a different separator, as I read in some sites. But my question is if there is a way to solve this using comma (',') separators.
Thanks

A: You just need to tell Calc/Excel that your quoting character is a "

A: You can do .replace(',','') which will replace the commas in the text with a space (or whatever else you want.
I don't know a way to keep the comma in the text but not let it act as a separator, like \, maybe? Somebody else could probably shed some light on that.

A: I believe you can try wrapping the fields which contain a non-delimiting comma in double quotes. If that does not work, you are probably out of options. Afterall, you need to somehow convey the information about which comma is doing what to the software that is doing the CSV display for you or the user.
Perhaps this will be helpful:
https://www.rfc-editor.org/rfc/rfc4180#page-3

*Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes.  For example:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx


text:
Q: Maximum principle applied to the Delta "function". Let $\Omega\in \mathbb{R}^n$ be a bounded domain with a fixed $x\in \Omega$. Let $u$ be a function subject to $$\begin{cases} \Delta u=\delta (y-x),  & \forall y \in \Omega\\ u=0, & \forall y \in \partial\Omega\end{cases} $$
Prove that $u$ has a fixed sign and determine this sign.
My approach: Intuitively speaking, since $\delta$ is a nonnegative "function" inside $\Omega$, so by the maximum principle we have $u(y)<\max_{\partial\Omega} u=0$ which implies the sign is negative. However, this argument is not rigorous as $\delta (y-x)$ is a distribution rather than a function. Could anyone make my argument rigorous? I think the main part of the argument is to deal with the singularity at $y=x.$


text:
Q: Consider the intergal $I = \int_{1}^{∞} e^{ax^2+bx+c}dx$ decide in each case whether the integral $I$ converges.
QUESTION: Consider the intergal $$I = \int_{1}^{\infty} e^{ax^2+bx+c} dx$$where $a,b,c$ are constants. Some combinations of values for these constants are given below and you have to decide in each case whether the integral $I$ converges.
$(A)$ $I$ converges for $a = −1, b = 10 ,c = 100$.
$(B)$ $I$ converges for $a = 1, b = −10 ,c = −100$.
$(C)$ $I$ converges for $a = 0, b = −1, c = 100$.
$(D)$ $I$ converges for $a = 0,b = 0 ,c = −100$.

I don't know how to solve this problem. Can anyone please explain how to do this?

A: (A) we got $I = \int_{1}^{\infty} e^{-x^2+10x+100} dx$
It happens that $e^{-x^2+10x+100} \sim_\infty e^{-x^2}$ which converges (it's smaller than $e^{-x}$ which is easy to prove that converges).
(B) we got $I = \int_{1}^{\infty} e^{x^2-10x-100} dx$
Then $e^{x^2-10x-100} \sim_\infty e^{x^2}$ which does not converge.
(C) we got $I = \int_{1}^{\infty} e^{-x+100} dx$
This integral converges and you can calculate that it is equal to $e^{99}$
(D) is false as e^{-100} is a costant.


text:
Q: Django custom form template and help text I'm trying iterate over form fields, and not want to use default {{ field }} tag. I want customise each field in cycle.
{% for field in wizard.form %}

                {{ field.label }}

            {{ field|add_error_class:"error" }}

            {% if field.errors %}
                {{ field.errors.as_text }}
            {% endif %}

{% endfor %}

I want to use something instead
{{ field|add_error_class:"error" }}.

Renders to:
<input class="timepicker" id="id_1-begin_time" name="1-begin_time" type="text" value="01:30:00" />

I want:
<input class="**{{ field.class }}**" id="id_{{ field.html_name }}" name="{{ field.html_name }}" type="**{{ field.type }}**" value="{{ field.value }}" />

A: Create tag:
from django import template
register = template.Library()

@register.filter(name='add_class')
def add_class(field, args):
   return field.as_widget(attrs={"class": args})

Or in form define. Answer is here


text:
Q: How can I arrange the output of sympy.latex when the input is an expression made of constants? sympy.latex arranges the terms of an equation in ascending order:

I've read this answer which provides a way to arrange the output of sympy.latex if you are using symbols.
Is there a way to arrange an expression of constants, so that the output of sympy.latex is something like this?
.


text:
Q: How can I have a cross forest mailbox in Exchange 2010? I have two forests, forest A, forest B.
Forest A has no Exchange server.
Forest B has 2010 Enterprise.
Forest A does not trust Forest B.
Forest B does trust Forest A.
The users are in Forest A, and I want Forest B to use those users in A and give them mailboxes in the B Exchange server but authenticate with A's domain controller.
Is this possible?  If so how can I do it?
I cannot use Federation Services because I only have one 2010 Exchange server and it is in Forest B.
Thanks.

A: Obviously, without the caveat information (which I'll happily update this answer with) my gut instinct is to say you need to build a 'resource forest'. Effectively, what this does is it allows users from one Forest access Exchange resources within another forest. This can be used effectively when two companies merge but have no desire to restructure their AD forests. This TechNet article will walk you through setting up Exchange in this fashion.


text:
Q: Why do I have to provide default ctor? Why do I have to provide default ctor if I want to create an array of objects of my type?
Thanks for answers

A: Because they have to be initialized.
Consider if it wasn't the case:
struct foo
{
    foo(int) {}

    void bar(void) {}
};

foo a[10];
foo f = a[0]; // not default-constructed == not initialized == undefined behavior

Note you don't have to:
int main(){
   // initializes with the int constructor
   foo a[] = {1, 2, 3};
}

// if the constructor had been explicit
int main(){
   // requires copy-constructor
   foo a[] = {foo(1), foo(2), foo(3)};
}

If you really need an array of objects and you can't give a meaningful default constructor, use std::vector.
If you really need an array of of objects, can't give a meaningful default constructor, and want to stay on the stack, you need to lazily initialize the objects. I have written such a utility class. (You would use the second version, the first uses dynamic memory allocation.)
For example:
typedef lazy_object_stack<foo> lazy_foo;

lazy_foo a[10]; // 10 lazy foo's

for (size_t i = 0; i < 10; ++i)
{
    // create a foo, on the stack, passing `i` to the constructor
    a[i].create(i);
}

for (size_t i = 0; i < 10; ++i)
    a[i].get().bar(); // and use it

// automatically destructed, of course

A: The default constructor will be called for each object in the array.
You don't have to specify a default constructor as one will be created for you.
Just make sure you don't declare a constructor with no parameters as private or protected.
Here's an example of one being created for you:
class C
{
};

C c[10];

Whereas if you make it private you get a compiling error:
class C
{
private:
    C()
    {

    }
};

C c[10];

A: When defining an array, you cannot specify ctor parameter, hence every object in the array must be constructed using the default ctor.
Normally, the C++ compiler will create the default ctor for you automatically.  But, if you define a ctor with parameters, then the automatically creation of the default ctor is supressed, and you must explicitly write one.

A: Because when the array is initialized, default constructors are called for its items.


text:
Q: Folder Permissions for new partition - can't move files I'm using Ubuntu 14.04.  I used the install CD to repartition my HD by resizing /dev/sda1 and creating /dev/sda3 as a Primary Partition.  I named it "Media".  When I reboot from HD, when I try to move files from the home directory to the new partition, I get an error message  "Error while copying.  The folder "TV" cannot be copied because you do not have permissions to create it in the destination."
The new partition shows up in Gparted as locked, with mount point /media/ian/Media and Label Media.
I want to move my media files from the boot partition to a separate partition.
Any advice?

A: In addition to Mina's answer, it would seem you don't have 'ownership' of the area. To solve this we'll use ´chown´ (change owner) and ´chgrp´ (change Group)

*

*Type ´sudo chown /media/ian/Media ian' this makes you the owner, rather than it being 'owned' by the ´root´ account.

*Type ´sudo chgrp /media/ian/Media $x´ where $x is tour group name. (It's likely just ian. If it's not, you probably already know what it is.) If you are unsure of your group name type ´ls -l ~´ and your group name will be the second 'name' column, next to 'ian'.
Note: In Linux Mint 17(and probably in Ubuntu 14.04) the owner-name and the group-name comes first i.e.
sudo chown ian /media/ian/Media

&
sudo chgrp $x /media/ian/Media

A: Use sudo!
Type in a terminal gksudo nautilus and move your files from there


text:
Q: How to return the results of mySql query using express.js? I am trying to get the results of my simple SELECT command to the index.js file, where I would like to have all records separated in a array. If I print the results in the database.js the JSON.parse just work fine. But if I want to return them and get them into the index.js where I need them, I always get undefined when I print it.
index.js CODE
const express = require('express');
const app = express();
const database = require('./database');

app.use(express.json());

app.use(express.urlencoded());

app.use(express.static('public'));

app.get('/form', (req,res) =>{
    res.sendFile(__dirname + '/public/index.html' );
    console.log(req.url);
    console.log(req.path);
})

app.listen(4000, () =>{
    console.log("Server listening on port 4000");
    database.connection;
    database.connected();
    //console.log(database.select());
    let results = [];
    //results.push(database.select('username, password'));
    let allPlayer = database.select('username');
    console.log(allPlayer);
});

database.js CODE
let mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    database: 'minigames',
    user: 'root',
    password: 'root'
});

function connected(){
    connection.connect((err) => {
        if(err) throw err;
        console.log("Connected...");
    })
}

function select(attribute){
    let allPlayer = [];
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {

    if(err) throw err;
        return Object.values(JSON.parse(JSON.stringify(result)));
    })
}
module.exports = {connection, connected, select};

A: Understand that one of the main things that make JavaScript different from other languages is that it's asynchronous, in simple terms meaning code doesn't "wait" for the code before it to finish executing. Because of this, when you're trying to query a database, which takes some time, the code after it gets impatient and executes regardless of how to the query is doing. To solve this problem, the mysql package utilizes callbacks, which allows you to pass a function to it to execute once the query is finished with the queries result.
Because the library operates on callbacks, it doesn't return anything; that seems quite problematic for using it somewhere else, doesn't it?
To solve this problem, we can make our own callback. Or better yet, use the newer JavaScript feature called promises, where you can basically "return" anything from a function, even when you're in a callback.
Let's implement it with the query:
function select(attribute) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
      if(err) return reject(err);
      resolve(Object.values(JSON.parse(JSON.stringify(result))));
    });
  });
}

To "return" from a promise, we pass a value to the resolve function. To throw an error, we call the reject function with the error as the argument.
Our new function is rather easy to use.
select("abcd").then(result => {
  console.log("Result received:", result);
}).catch(err => {
  console.error("Oops...", err);
});

You might look at this code and go, "Wait a minute, we're still using callbacks. This doesn't solve my problem!"
Introducing async/await, a feature to let you work just with that. We can call the function instead like this:
// all 'await's must be wrapped in an 'async' function
async function query() {
  const result = await select("abcd"); // woah, this new await keyword makes life so much easier!
  console.log("Result received:", result);
}
query(); // yay!!

To implement error catching, you can wrap you stuff inside a try {...} catch {...} block.


text:
Q: Pytorch: executiin on GPU: RuntimeError: Expected object of backend CUDA but got backend CPU for argument #3 'index' How to make model execute on GPU in Pytorch?
I load model like:
def load_tocotron_2_model():
    model = Tacotron2(num_chars=n_chars, r=CONFIG.r, attn_win=CONFIG.windowing, attn_norm=CONFIG.attention_norm,
                      prenet_type=CONFIG.prenet_type, forward_attn=CONFIG.use_forward_attn,
                      trans_agent=CONFIG.transition_agent)

    if use_cuda:
        cp = torch.load(MODEL_PATH)
    else:
        cp = torch.load(MODEL_PATH, map_location='cpu')

    model.load_state_dict(cp['model'])

    if use_cuda:
        model.cuda()

    model.eval() # Set eval mode

    return model

If use_cuda is False then model runs ok, but if it's True I get error:
  File "/data/user/external_projects/text-to-speech/mozila-tts-wavernn-cpu/TTS/models/tacotron2.py", line 50, in inference
    embedded_inputs = self.embedding(text).transpose(1, 2)
  File "/data/user/external_projects/text-to-speech/mozila-tts-wavernn-cpu/TTS/my_env_gpu/lib/python3.5/site-packages/torch/nn/modules/module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)
  File "/data/user/external_projects/text-to-speech/mozila-tts-wavernn-cpu/TTS/my_env_gpu/lib/python3.5/site-packages/torch/nn/modules/sparse.py", line 117, in forward
    self.norm_type, self.scale_grad_by_freq, self.sparse)
  File "/data/user/external_projects/text-to-speech/mozila-tts-wavernn-cpu/TTS/my_env_gpu/lib/python3.5/site-packages/torch/nn/functional.py", line 1506, in embedding
    return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
RuntimeError: Expected object of backend CUDA but got backend CPU for argument #3 'index'

self.embedding is self.embedding = nn.Embedding(num_chars, 512), do I need to specify .cuda() on some tensor or model.cuda() is sufficient?


text:
Q: Isomorphism of $\mathbb{Z}\ltimes_A \mathbb{Z}^m$ and $\mathbb{Z}\ltimes_B \mathbb{Z}^m$ Let $A$ and $B$ be matrices of finite order with integer coefficients.
Let $n\in\mathbb{N}$ and let $G_A=\mathbb{Z}\ltimes_A \mathbb{Z}^n$ be the semidirect product, where the action is $\varphi(n)\cdot (m_1,\ldots,m_n)=A^n (m_1,\ldots,m_n)$, and similarly with $B$.
It is easy to construct an isomorphism between $G_A$ and $G_B$ if $A$ is conjugate in $GL(n,\mathbb{Z})$ to $B$ or $B^{-1}$.
But, this is also a necessary condition? I mean, does $G_A\cong G_B$ implies $A\cong B$ or $A\cong B^{-1}$ in $GL(n,\mathbb{Z})$ or is there a counterexample?
I've seen in A necessary condition for two semi-direct products to be isomorphic. that it is true if A and B are hyperbolic, i.e none of their eigenvalues have module 1, but it isn't the case.
Thank you!


text:
Q: Tracking sends event from within app exchange > query studio I'm trying to access send data from within a sql ui. We have 'QueryStudio' under app exchange which let's me query data extension tables. E.g.
select AccountId
from Contact_Salesforce

Our data extensions appear to be user scoped tables that were set up for us.
I'd liek to include sends data here. If I navigate to e.g. email studio > tracking > sends I can select a campaign and see a report of summary data along with a clickable 'total sent' link which then drills down into a report with subscriber_key and send_date
My question is, this 'send event' data, does it exist in a pre built schema I can query within QueryStudio? Is there a sql interface to access this data rather than via the navigation?

A: What you are looking for is called data view. There is a number of them available, and the ones you would normally look at are:

*

*Sent

*Open

*Click

*Job

While the first 3 are global, the Job data view is BU specific. You can see all the data views and their respective fields in documentation.
Mateusz Dabrowski has some good examples, along with queries, in his article, which can be found here.


text:
Q: How can I prove that $x^2=3y+2$ cannot have integer positive solutions? I need to prove that  $x^2=3y+2$ cannot have integer positive solutions?I tried some numbers, could not find solution. But do not know how to prove.

A: The equation simplifies to $y = \frac{x^2-2}{3}$. Notice that for any integer $x$, $x^2 \equiv 0 \pmod 3$ or $x^2 \equiv 1 \pmod 3$. You can prove this yourself. Thus the numerator is never a multiple of $3$, thus $y$ is never an integer

A: we have $$3y+2\equiv 2 \mod 3$$ but for $$x \in \mathbb{Z}$$ we get $$0,1,2 \mod 3$$ but we have $$x^2\equiv 0,1 \mod 3$$ contradiction


text:
Q: @JSONField it did not work in spring boot I use @JSONField annotation for pointX and pointY, I want to change pointX to point_x!
I want to pointX show like point_x! But it did not work! It always is pointX and pointY! but other field is ok!
My java bean like this!
@Data
public class PointListOutput {

    @JSONField(name = "latest_area_point_list")
    private List<Point> latestAreaPointList;

    @Data
    public static class Point {
        @JSONField(name = "point_x")
        private Float pointX;
        @JSONField(name = "point_y")
        private Float pointY;
    }
}

my config
@Override
protected void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);

    // create FastJson converter
    final FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

    final List<MediaType> supportedMediaTypes = new ArrayList<>();
    supportedMediaTypes.add(MediaType.APPLICATION_JSON);
    supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    converter.setSupportedMediaTypes(supportedMediaTypes);

    // create configuration class
    final FastJsonConfig config = new FastJsonConfig();
    // update filter of response
    config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
    converter.setFastJsonConfig(config);

    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(converter);
}

Here is my http response, as you can see the pointX is pointX! not point_x!
{
    "code": 1,
    "message": "Success",
    "data": [
        {
            "latest_area_point_list": [
                {
                    "pointX": 1.1,
                    "pointY": 1.1
                },
                {
                    "pointX": null,
                    "pointY": 1.1
                }
            ]
        }
    ]
}

A: I resolved this, it cause by org.springframework.beans.BeanUtils.copyProperties
I used org.springframework.beans.BeanUtils.copyProperties  change DAO java bean to View java bean.
My Dao java bean
@Data
@DynamoDBTable(tableName = "xxxx")
public class PointPojo {
    @DynamoDBAttribute(attributeName = "latest_area_point_list")
    private List<Point> latestAreaPointList;

    @Data
    @DynamoDBDocument
    public static class Point {
        @DynamoDBAttribute(attributeName = "point_x")
        private Float pointX;
        @DynamoDBAttribute(attributeName = "point_y")
        private Float pointY;
    }
}

And PointPojo did no hava @JSONField(name = "point_x")
after copyProperties the Point was not PointListOutput$Point, it was PointPojo@Point, and it did not hava @JSONField(name = "point_x")
So this is the root cause!
I use orika replace org.springframework.beans.BeanUtils.copyProperties, it was perfect!


text:
Q: Managing trivial types I have found the intricacies of trivial types in C++ non-trivial to understand and hope someone can enlighten me on the following.
Given type T, storage for T allocated using ::operator new(std::size_t) or ::operator new[](std::size_t) or std::aligned_storage, and a void * p pointing to a location in that storage suitably aligned for T so that it may be constructed at p:

*

*If std::is_trivially_default_constructible<T>::value holds, is the code invoking undefined behavior when code skips initialization of T at p (i.e. by using T * tPtr = new (p) T();) before otherwise accessing *p as T? Can one just use T * tPtr = static_cast<T *>(p); instead without fear of undefined behavior in this case?

*If std::is_trivially_destructible<T>::value holds, does skipping destruction of T at *p (i.e by calling tPtr->~T();) cause undefined behavior?

*For any type U for which std::is_trivially_assignable<T, U>::value holds, is std::memcpy(&t, &u, sizeof(U)); equivalent to t = std::forward<U>(u); (for any t of type T and u of type U) or will it cause undefined behavior?

A: *

*Technically reinterpreting storage is not enough to introduce a new object as. Look at the note for Trivial default constructor states:

A trivial default constructor is a constructor that performs no action. All data types compatible with the C language (POD types) are trivially default-constructible. Unlike in C, however, objects with trivial default constructors cannot be created by simply reinterpreting suitably aligned storage, such as memory allocated with std::malloc: placement-new is required to formally introduce a new object and avoid potential undefined behavior.

But the note says it's a formal limitation, so probably it is safe in many cases. Not guaranteed though.

*No. is_assignable does not even guarantee the assignment will be legal under certain conditions:

This trait does not check anything outside the immediate context of the assignment expression: if the use of T or U would trigger template specializations, generation of implicitly-defined special member functions etc, and those have errors, the actual assignment may not compile even if std::is_assignable::value compiles and evaluates to true.

What you describe looks more like is_trivially_copyable, which says:

Objects of trivially-copyable types are the only C++ objects that may be safely copied with std::memcpy or serialized to/from binary files with std::ofstream::write()/std::ifstream::read().

*I don't really know. I would trust KerrekSB's comments.

A: *

*No, you can't. There is no object of type T in that storage, and accessing the storage as if there was is undefined. See also T.C.'s answer here.
Just to clarify on the wording in [basic.life]/1, which says that objects with vacuous initialization are alive from the storage allocation onward: that wording obviously refers to an object's initialization. There is no object whose initialization is vacuous when allocating raw storage with operator new or malloc, hence we cannot consider "it" alive, because "it" does not exist. In fact, only objects created by a definition with vacuous initialization can be accessed after storage has been allocated but before the vacuous initialization occurs (i.e. their definition is encountered).

*Omitting destructor calls never per se leads to undefined behavior. However, it's pointless to attempt any optimizations in this area in e.g. templates, since a trivial destructor is just optimized away.

*Right now, the requirement is being trivially copyable, and the types have to match. However, this may be too strict. Dos Reis's N3751 at least proposes distinct types to work as well, and  I could imagine this rule being extended to trivial copy assignment across one type in the future.
However, what you've specifically shown does not make a lot of sense (not least because you're asking for assignment to a scalar xvalue, which is ill-formed), since trivial assignment can hold between types whose assignment is not actually "trivial", that is, has the same semantics as memcpy. E.g. is_trivially_assignable<int&, double> does not imply that one can be "assigned" to the other by copying the object representation.


text:
Q: Linux find files with string and print last access time I have a command which finds all the files containing a certain string on linux:
find . -type f | xargs grep 'string' -sl

What I want is to also print the time and date that the file was last modified.

A: You can do this:
grep -rl "string" *|xargs ls -l

If you want only the times:
grep -rl "string" *|xargs ls -l|awk '{print $NF, $6, $7 }'

will print something like:
file1 2012-03-25 12:44
file2 2012-03-26 00:30


text:
Q: Get text inside selected element jQuery I am creating an application using jQuery  and I am using a swipe left handler. When  I swipe left on a 'li' element and use:
console.log($(event.target).text());.
I get the following in console

 Italian "IHOP"

I need to get "IHOP" to proceed. I am unable to find that. I have used
console.log($(event.target).find('.list-group-item').text());
but it gives me nothing. However, if I use console.log($(event.target).find('.badge').text());.
I get  Italian. What is the sorcery here !
Can anyone help ?

A: $(event.target)
     .clone()    //clone the element
     .children() //select all the children
     .remove()   //remove all the children
     .end()      //again go back to selected element
     .text();    //get the text of element

A:
I need to get "IHOP" to proceed.

It sounds like you want the text directly contained by the li and not the text contained by any descendant elements. Here's one way:
var theText = $(event.target).contents().filter(function() {
    return this.nodeType === 3;
}).text();

(See alternative below as well.)
That uses contents to get the contents of the element (including child elements, text nodes, and comments), then filter to filter out everything except the text nodes (nodeType === 3), then text to get that text as a string.
You might well want to add $.trim in there to get rid of leading and trailing whitespace, so:
var theText = $.trim($(event.target).contents().filter(function() {
    return this.nodeType === 3;
}).text());

Alternative:
In your example markup:

 Italian "IHOP"

...the text you want is always the last node within the li, so if that's reliable, you can do this instead:
var theText = $.trim($(event.target).contents().last().text());

If you can't rely on it being the last item, and this is something you need to do frequently, you could add a plug-in to do it, like this:
(function($) {
    $.fn.immediateText = function(trim) {
        var rv = this.contents().filter(onlyTextNodes).text();
        if (trim) {
            rv = $.trim(rv);
        }
        return rv;
    };

    function onlyTextNodes() {
        return this.nodeType === 3;
    }
})(jQuery);

Then to use it:
var theText = $(event.target).immediateText(true);

A: If you care about performance, don't use jQuery where you don't have to. If writing a function, a simple jsperf test shows the following in mostly plain js will run about 3 times faster than the accepted answer:
(function($) {
    $.fn. childText = function () {
      var children = this[0].childNodes;
      var text = '';
      for (var i=0, iLen=children.length; i<iLen; i++) {
        if (children[i].nodeType == '3') {
          text += children[i].data;
        }
      }
      return text;
    }
}(jQuery));

and the following plain javascript is 6 to 10 times faster, depending on the browser:
// Return the text of the child text nodes of an element,
// but not descendant element text nodes
function getChildText(element) {
  var children = element.childNodes;
  var text = '';
  for (var i=0, iLen=children.length; i<iLen; i++) {
    if (children[i].nodeType == '3') {
      text += children[i].data;
    }
  }
  return text;
}

and use it like:
var theText = getChildText(event.target);


text:
Q: Laravel not able to load other URLs other than home(/)? I installed laravel and getting home page on localhost/laravel/public.
But unable to do simple routing.
Route::get('/', function()
{
    return View::make('hello');
});

Route::get('authors',function()
{
    return View::make('hello');
});

Here i am calling the same view on localhost/laravel/public/authors.
But i am getting 404.
I have a different view that also with / but not with authors
Route::get('/', function()
{
    return View::make('authors');
});

Route::get('authors',function()
{
    return View::make('authors');
});

Now i am getting authors view on / but not with authors.
Thanks

A: If you are able to access /laravel/public/index.php/authors, then you'll need to adda RewriteBase to your .htaccess file, that is, assuming you're running Apache:
RewriteEngine on
RewriteBase /laravel/public
<other rules go here>


text:
Q: Behind the scenes of construction of a thread It is known that how to use thread. But how is the thread library implemented. I mean, like we have std::string, its functionality can be somewhat replicated, by user himself using C-strings (char arrays), it is easy.
My question is how can i achieve this for the case of thread, like how can i create a class with bare-minimum C++ datatypes and functions(without WINAPI), std::thread like functionality into a class.
I would like to give a example, my teacher has prohibited me from using std::string, and allowed to only use C-strings, but i can use OOP concepts..
class string_my
{
      private:
            char* str;
      public:
         // all the required func. to store the value in char*
 }

A: You cannot implement a thread class without either using the OS provided threading primitives or some higher level threading library (like boost::thread or std::thread) that in turn rely on said OS-provided threading primitives.


text:
Q: Calculate the largest remainder of a number I am trying to calculate the largest remainder of a number, and find what number is dividing the original number to get the largest remainder. Here is my current code I am pretty sure it works. I just want to make it faster. Any Sugestions?
int c=Integer.parseInt(br.readLine());

        if(c==2)
            pw.println(2);
        else if(c%2==0)
        {
            pw.println(c-1);
        }
        else
        {
            max=0;
            int numDivided=0;
            for(int z=1; z<c; z+=2)
            {
                if(c%z>max)
                {
                    numDivided=z;
                    max=c%z;
                }
            }
            pw.println(numDivided);

new and faster code
c=Integer.parseInt(br.readLine());
int largestRemainder = c % ((c/2) + 1);
pw.println(((c/2) + 1));

A: The largest remainder is supposed to be less than the half of the input number.
So you should use this formula, where c is the input integer:
int largestRemainder = c % ((c/2) + 1);

*

*For an even number, e.g. c = 24 it gives largestRemainder = 11

*For an odd number, e.g. c = 33 it gives largestRemainder = 16
And these results are actually correct.


text:
Q: preg_replace all non-digit characters except the number between second and third slash Assuming the input string /en/614/5d or /en/617/19, using PHP's regex functions I would like to remove all non-digit (/\D/) characters, except the 614 or 617 between the second and third slashes.
I know I can use split or explode to split the string but I need a regular expression pattern to use with preg_replace to extract only the numbers between second and third slashes.
Thanks.

A: preg_replace('/^\/[^\/]+\/|\/.+$/','',$string);

A: this should be better and simple I think
preg_replace('/\D/', '', $input_lines); //replace any non digit


text:
Q: Comparing complex eigenvectors if they are the same. You have two normalized eigenvectors $V_1$ and $V_2$ in $C^n$.  Even if $V_1 - V_2 \neq 0$, the two vectors may still represent the same eigenvector, since $a V$ for any complex number $a$ with unit length, is the same eigenvector as $V$.  One way to compare them is to normalize the two vectors in a new way:  Divide each by its first non-zero component. Hence each vector will begin $[1,\ldots]$, unless the first component was zero, in which case it would start with $[0,1,\ldots]$, etc.  Then, if $V_1 - V_2 = 0$, one can conclude that the two vectors represent the same eigenvector. Is there another way to compare them?

A: You'll have $|\langle v_1,v_2 \rangle | = 1$ if and only if they are parallel (i.e. $v_1 = a v_2$, $a \in \Bbb C$, $|a| = 1$). One direction is clear.
On the other hand, suppose $v_1 \not\parallel v_2$. Then $v_1 = c_1 v_2 + c_2 v_2^\perp$ for some unit length vector $v_2^\perp$ that is orthogonal to $v_2$, and such that $|c_1|^2 + |c_2|^2 = 1$. Thus $|c_1| < 1$ if $c_2 \neq 0$.
Then
$$|\langle v_1,v_2 \rangle| = |\langle c_1 v_2, v_2 \rangle| = |c_1| < 1,$$
proving the other direction.
This is basically the second half of the statement of Cauchy-Schwarz:
$$
|\langle v,w\rangle| \leq \|v\|\|w\|
$$
with equality if and only if $v \parallel w$.

A: You just need to find a scalar $c$ such that $v_1 = c v_2$.
Let $k$ be the first index for which $[v_2]_k \neq 0$ and let $c = { [v_1]_k \over [v_2]_k }$. If $|c| =1$ (or close) then check $\|v_1-c v_2\|$.


text:
Q: Error in Thread() This is my getAllFriends method with Thread
   ArrayList<User> users;
  private void getAllFriends()
{
    new Thread(){
        @Override
        public void run(){
            try {
                api=new Api(Account.access_token, Constants.API_ID);
                users = api.getFriends(Account.user_id,"name",null,null,null);
                user_name = users.get(0).first_name;
                api = null;

                runOnUiThread(successRunnableFriends);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
}
Runnable successRunnableFriends = new Runnable(){
    @Override
    public void run() {
        user_name = users.get(0).first_name;
        Toast.makeText(c, String.valueOf(users.size()), Toast.LENGTH_LONG).show(); // Shows 166
    }
};

It gives me certain user_name and user.size, which means that users in not empty, BUT whenever I try call getAllFriends, it Toastes null
    public void getFriends(Context _c) {
    c = _c;
    getAllFriends();
    if(users.size() == 0)
        Toast.makeText(c,String.valueOf(user_name), Toast.LENGTH_LONG).show();//null

Where is my mistake?

A: If you are sure that your thread in getAllFriends() is definitely running before the thread successRunnableFriends, then you might have an issue with the declaration of
ArrayList<User> users;

This should rather be
volatile ArrayList<User> users;

because otherwise the JVM is allowed to cash the value for a newly started thread.
Check for instance this nice article.
p.s.: if volatile doesn't work, consider the following. At the point of time when
if(users.size() == 0)
    Toast.makeText(c,String.valueOf(user_name), Toast.LENGTH_LONG).show();

is executed the api.getFriends(Account.user_id,"name",null,null,null); has most likely not been completed. So the Toast shows null. What you have to ensure is that the assignment to users in getAllFriends() is done before you access it in another thread. Use wait and notify to achieve this. Check for instance this article for the basics.


text:
Q: Testing react-router-dom Link in react, enzyme and jest Is there a specific way to test react-router-dom links in enzyme? I can't seem to get this test to work. I'd prefer it over testing the link's prop(which works, but not ideal):
expect(mountWrapper.find('a').props().href).toBe('http://redirectlink.com')

Component:
import { Link } from 'react-router-dom'

...

<Link href="http://redirectlink.com">Click Me</Link>
....

Test:
 import { MemoryRouter } from 'react-router-dom'
 import { HelmetProvider } from 'react-helmet-async'
 ...

 it('test user is redirected', () => {
    const mountWrapper = mount(
      <TestWrapper>
        <HelmetProvider>
          <MemoryRouter>
            <ErrorPage />
          </MemoryRouter>
        </HelmetProvider>
      </TestWrapper>
    )

    mountWrapper.find('a').simulate('click')
    expect(window.location.href).toBe('http://redirectlink.com')
  })


text:
Q: how do I fix CharField attribute error in django? I am a beginner and this might seem very trivial to most. I am getting an the following error:

Traceback (most recent call last):   File
  "C:\Dev\hoss\myfirst\app_one\models.py", line 3, in
      class Question(models.Model):   File "C:\Dev\hoss\myfirst\app_one\models.py", line 5, in Question
      textone = models.CharField(max_lenght=128)   File "C:\Dev\hoss\lib\site-packages\django\db\models\fields__init__.py",
  line 1037, in init
      super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'max_lenght'

for the following code and cant fix it any body can help:
from django.db import models

class Question(models.Model):

    textone =       models.CharField(max_lenght=128)
    pub_date =      models.DateTimeField()

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete = models.CASCADE)
    text = models.CharField(max_lenght=200)
    vote = models.IntegerField(default = 0)

A: There is a typo in your code. textone =models.CharField(max_lenght=128) it should be textone =models.CharField(max_length=128) and text = models.CharField(max_lenght=200), it should be text = models.CharField(max_length=200)


text:
Q: Unity menu fast when first logged in then gets progressively slower I'm running Ubuntu 16.04 with the latest updates on a 2009 Dell T5500 workstation with an nvidia Quadro NVS card.  When I run the noveau drivers, I get errors and lockups, so I run the nvidia 340 drivers (which are the recommended ones).  I've tried a few other versions of the drivers, and still get the same issues.
The problem that I have is that on boot, the Unity menu and alt-tab switchers work quickly, but after I've left the X session up for a while, they  start popping up at about 1 FPS over the the course of 5-10 seconds.  Switching to the MATE interface "fixes" the issue, but I like the easy "search for applications" launcher that Unity provides.
The dash "include online search results" is off, but I think that was a red herring, given that the alt-tab switcher exhibits the same behavior.  I've tried toying with CompizConfig settings (e.g. Dash Blur, disabling animations, etc), to no avail.
I just did a fresh install of 16.04 yesterday on a brand new, recent SSD, and I'm getting the same issues today, and I'd seen the same issue going back at least to 14.04.
So, two possible answers I'm looking for:

*

*How can I fix this to make the menus and switcher pop up quickly? or

*Does there exist another launcher for an alternate UI (e.g. MATE) that does the indexed search app launcher?

Note that running
unity --replace

or
compiz --replace

does not alleviate the problem for more than a couple of minutes.
I've installed the CompizConfig Settings Manager and tried disabling anything that seemed relevant:  Animations, Fading Windows, Window Decoration, Dash Blur, etc.  Even if I choose Enable Low Graphics Mode, the affected windows don't pop up instantly.  I've even gone into the Ubuntu Unity Plugin and set all of the Menus durations to 0, to no avail.
When running htop -d 1 (i.e. to get quick updates on the CPU usage in tenths of a second), I see a brief spike in CPU utilization from compiz and /usr/lib/xorg/Xorg during the issue, and compiz stays pegged using a full CPU until the problematic window goes away. (CPU is 4 core hyperthreaded Xeon)


text:
Q: Rails finds the module but not the class in grape setup I am following this tutorial
https://www.youtube.com/watch?v=fgn12-Yc-Sg

I have in my application.rb
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

Then on my app folder I have an api folder and inside of that the module folder converter
/app/api/converter/currency.rb

module Converter
  class Currency
    resource :converter do
      get :exchange do
        params
      end
    end
  end
end

Now rails finds the Converter module on the console but it gives error for the Currency class


text:
Q: How to insert more than 10000 rows to MSSQL Table I have a PHP project where I have to insert more than 10,000 rows to a SQL Table. These data are taken from a table and checked for some simple conditions and inserted to the second table at the end of every month.
How should I do this.
I think need more clarification. I currently use small batch (250 inserts) transferring using PHP cronjob and it works fine. But i need to do this is most appropriate method.
What will be the most appropriate one.

*

*Cronjob with PHP as I currently use

*Exporting to a file and BULK import method

*Some sort of Stored procedure to transfer directly

or any other.

A: Use insert SQL statement. :^ )

Adds one or more rows to a table or a view in SQL Server 2012. For examples, see Examples.

Example of using mssql_* extension.
$server = 'KALLESPC\SQLEXPRESS';
$link = mssql_connect($server, 'sa', 'phpfi');
mssql_query("INSERT INTO STUFF(id, value) VALUES ('".intval($id)."','".intval($value)."')");

A: Use BULK INSERT - it is designed for exactly what you are asking and significantly increases the speed of inserts.
Also, (just in case you really do have no indexes) you may also want to consider adding an indexes - some indexes (most an index one on the primary key) may improve the performance of inserts.
The actual rate at which you should be able to insert records will depend on the exact data, the table structure and also on the hardware / configuration of the SQL server itself, so I can't really give you any numbers.

A: Since the data is large, make the batch of 500 records for processing.
Check the condition for those 500 batches , till that time, make ready another batch of 500 and insert first batch and process so on.
This will not give load on your sql server.
By this way i daily process 40k Records.

A: it's so simple , you can do it using multiple while, since 10000 rows is not huge data!
$query1 = mssql_query("select top 10000 * from tblSource");
while ($sourcerow = mssql_fetch_object($query1)){
      mssql_query("insert into tblTarget (field1,field2,fieldn) values ($sourcerow->field1,$sourcerow->field2,$sourcerow->fieldn)");
}

this should be work as fine

A: SQL Server does not insert more than 1000 records in a single batch. You have to create separate batch for insertion. Here I am suggesting some of alternative which will help you.
Create one stored procedure. create two temporary table one for valid data and other for invalid data. one by one check all your rules and validation and base on that insert data into this both table.
If data is valid then insert into valid temp table else insert into invalid temp table.
Now, next using merge statement you can insert all that data into your source table as per your requirements.
you can transfer N number of records between tables so I hope this would be fine for you
Thanks.


text:
Q: Elastic search in Unravel failing with out of memory Out of memory*
Elastic search service frequently going down.
It consuming more resource and running out of memory.

A: Issue with heap memory for elastic search.
Update below value:
 Go to /installer/templates/elasticsearch/start.sh.template
Increase HEAP_MB value


text:
Q: Cómo puedo hacer este tipo de Card con Bootstrap 4? Viendo la documentación de bottstrap, en específico la documentación del componente "cards" vi un una card de publicidad de slack. Dónde hay un recuadro con fondo gris, dentro de él una imagen del lado izquierdo y texto de lado derecho. Quiero hacer una así, pero paradójicamente no hay documentación de como hacer una así, solo se puede poner una imagen y el texto de bajo, no a un lado.
Me gustaría poner dos de esos en una fila.

From the root of experience
 We dig out the best talent

Few would argue that, despite the advancements of feminism over the past three decades, women still face a double standard when it comes to their behavior. While men's borderline.

inappropriate behavior is often laughed off as "boys will be boys," women face higher conduct standards – especially in the workplace. That's why it's crucial that, as women, our behavior on the job is beyond reproach.Small Towns and Big StatesFor evidence of the double standard.

        View Details

From the root of experience
 We dig out the best talent

Few would argue that, despite the advancements of feminism over the past three decades, women still face a double standard when it comes to their behavior. While men's borderline.

inappropriate behavior is often laughed off as "boys will be boys," women face higher conduct standards – especially in the workplace. That's why it's crucial that, as women, our behavior on the job is beyond reproach.Small Towns and Big StatesFor evidence of the double standard.

        View Details

A: La mejor manera de hacerlo no es con las cards de Boostrap. Yo lo haría con el componente media-object
Te permite posicionar de forma fácil una imagen dentro de un wrap. Lee la documentación, es muy completa.
Aparte estoy usando las utilidades de espacio para añadir un padding al contenedor media

.media {
  background-color: #ebebeb;
  width: 400px;
}

.media img {
  width: 200px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />

The easiest way to sign docs, forms and agreements online. Try it free today.

    Ads via Carbon


text:
Q: Jacobian of an injective mapping Let $f:R^N \to R^N$ be a differentiable mapping, and $J_f$ its Jacobian. Suppose that $\exists a,b \in R^N : J_f(a)<0,J_f(b)>0$. I want to prove two things that seem intuitively right: 1) $f$ is not injective, 2) $\exists c \in R^N : J_f(c)=0$. I thought that such statements (or their disproof) must be well-known, but haven't found any useful information by now. If somebody has any thoughts on this issue, I'll be glad!
[Edit]
Thanks for participation, further generalizations can be discussed here.

A: As you have already seen from the comments, the real difficulty is to show that $f$ is not injective. This can be proved by using the so-called topological degree theory. Namely, if $f$ is injective, then by the invariance of domain, $f(\mathbb{R}^N)$ will be a domain. Then the topological degree is constant on $f(\mathbb{R}^N)$. On the other hand, since $f$ is differentiable everywhere, at points where the Jacobian is non-zero, one can easily prove that the local degree equals to the sign of the Jacobian, and hence the Jacobian of a differentiable homeomorphism is either non-negaitive or non-positive. So in your situation, $f$ cannot be injective.
If you want to know more on degree theory, you can read any book on topological degree theory to figure out the detailed proof of my indication.

A: In these assumptions, the topological degree $\operatorname{deg}\big(f,B(0,r),p\big)$ is well defined whenever $p\in f\big(B(0,r)\big)$; by invariance, it is the same for all such $p$ and $r$, and it's possible values are either $1$ or $-1$. In the case that $f(x)=p$ and  $J_f(x)\neq0$, by the Jacobian formula for the degree, this degree it's simply $\operatorname{sgn} J_f(x)$. This explains why either $J_f(x)\ge0$ for all $x$ or $J_f(x)\le0$ for all $x$.
[edit] As to your further question,  a smooth map  $f:\mathbb{R}^N\to\mathbb{R}^N$ may well be injective on a path connecting two points with Jacobian of opposite sign. Think e.g. to $f(x,y)=(x,y^2)$ : it's restriction to the diagonal is injective, while the Jacobian has the sign of $y$.


text:
Q: Moodle Registration Form Edit I am using moodle 2.8.1
My query is regarding Moodle registration form:
I want to add a confirm password field which would be required same as Email(again) field.
And remove the Email(again) field.
And also it is not showing the phone no. fields in registration form while they are unlocked.

A: If you want to add fields to the  registration form, you can do it using user profile fields in Site administration > Users > Accounts > User profile fields.
You have to set 'Display on signup page', which will show the field in the signup form, and 'Who is this field visible to' .
If you need more details refer: http://docs.moodle.org/26/en/User_profile_fields
Hope this helps.

A: We made a small open source module covering this use case.
It adds the field on the fly in the registration form, along with the necessary validation, using addRule and the compare rule.

A: In order to add confirm password field, you can custom login/signup_form.php file by adding one more field right after password field with compare rule like:
$mform->addElement('password', 'confirmPassword', get_string('password_confirm'), 'maxlength="32" size="12"');
$mform->setType('password', core_user::get_property_type('password'));
$mform->addRule('confirmPassword', get_string('missingpassword'), 'required', null, 'client');
$mform->addRule(array('confirmPassword', 'password'), get_string('passwords_must_match'), 'compare', 'eq', 'client');


text:
Q: What is multi line pattern in Lua? I want match multi line
/add val1::val2

and work via this pattern
^/add +(.+)::+(.+)$

but not work in multi line
for example:
/add line1
line2
::
linexx
lineYY

tested this pattern but not work
^/add ([%w%s]*)::([%w%s]*)

A: . matches any character, including \n. Since you don't want to match multi-line strings, exclude \n explicitly, i.e, use [^\n] to replace .:
^/add +([^\n]+)::+([^\n]+)$

Test:
local str1 = '/add val1::val2'
local str2 = [[/add line1
line2
::
linexx
lineYY]]

local pattern = '^/add +([^\n]+)::+([^\n]+)$'

print(str1:match(pattern))
print(str2:match(pattern))


text:
Q: Azure SDK for node is rounding large numbers in JSON responses I've been looking into building a REST api using the Azure SDK for node (https://github.com/WindowsAzure/azure-sdk-for-node).  I have a simple MessageTable in Azure tablestore - the PartitionKey is a device identifier (messages belong to a specific messaging device) and the RowKey is a number that identifies the message.
The problem is that the RowKey is a very big number which usually ends with a load of 9's (it's a 'reverse-timestamp'), and the node-azure library is rounding this number up when data is returned.  See example JSON response below:
{
"id":"http://xxx.table.core.windows.net/MessageTable(PartitionKey='12345',RowKey='2520801590159999999')",
"link":"MessageTable(PartitionKey='12345',RowKey='2520801590159999999')",
"updated":"2012-03-13T15:53:34Z",
"etag":"W/\"datetime'2011-11-24T13%3A36%3A41.9555578Z'\"",
"PartitionKey":12345,
"RowKey":2520801590160000000,
"Timestamp":"2011-11-24T13:36:41.955Z",
...other results removed for brevity
}

The "id" and "link" elements show the correct RowKey of 2520801590159999999; the "RowKey" element shows a rounded version of this: 2520801590160000000.
Anyone know what's going on?
I've also logged this question - I'm sure it's the same root cause:
https://stackoverflow.com/questions/9683515/journey-routing-fails-due-to-number-rounding
Edit @smarx:
Test code reproduced below.  When running, going to http://localhost:8080/devices/12345/messages gives the json output sampled above.  Azure table is MessageTable, partition key is deviceId (12345), rowkey is messageId (2520801590159999999).
var express = require('express');
var http = require('http');
var azure = require('azure');
var uuid = require('node-uuid');
var tableService = azure.createTableService( '[ACCOUNT_NAME]', '[ACCOUNT_KEY]' );
var app = module.exports = express.createServer();

app.configure(function(){
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/devices/:deviceId/messages', function ( req, res ) {
  var query = azure.TableQuery
    .select()
    .top( 30 )
    .from( "MessageTable" )
    .where( 'PartitionKey eq ?', req.params.deviceId );

  tableService.queryEntities( query, function (error, entities) {
    if ( null != error ) {
      res.end('Could not query MessagesTable: ' + error.code);
      return;
    }
    res.send( entities );
  });
});

app.listen(8080);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

[EDIT by @smarx]:
Simpler repro:
tableService.createTableIfNotExists('testtable', function () {
  tableService.insertEntity('testtable', {
    PartitionKey: 'pkey',
    RowKey: '2520801590159999999'
  }, function () {
    tableService.queryEntity('testtable', 'pkey', '2520801590159999999', function (error, entity) {
      console.log(entity.RowKey); // prints 2520801590160000000
    });
  });
});

A: This is a bug here: https://github.com/WindowsAzure/azure-sdk-for-node/blob/master/lib/util/atomhandler.js.
The implementation of parse (by default) tries to guess the type of a property value if none is specified, which I don't believe is the correct behavior. (The lack of a type means to use the default, which is string.)
I've filed a bug (https://github.com/WindowsAzure/azure-sdk-for-node/issues/114), including a suggested fix. You can try it yourself by just adding convertTypes = false at the top of the parse function.
Edit: This has now been fixed in the repo. (Click on the GitHub issue link above to see.)

A: JavaScript mandates that numbers use IEEE-754 floating point format.  The short answer is that it can represent integers exactly up to about 15 digits but your number is longer so it gets rounded to the nearest representable number per that specification.  (The long answer involves an explanation of the number of bits used for the exponent but has the same result.)
It sounds like node-azure should be using strings instead of numbers...


text:
Q: Dynamic Metric Spaces Fellow Mathers,
Is there a name for, and is there established theory on, metric spaces that evolve over time?
What I mean by an evolving metric space is one in which the distances between the objects in your set can change through time.
Thank you much to anyone who can point me in the right direction.

A: It depends exactly on what sort of dynamics you are after. In metric space theory the Gromov-Hausdorff metric is a way to endow a collection of metric spaces with a metric. You can then speak of convergence of metric spaces. You can view a sequence of metric spaces as a metric space evolving through time in this setting. You can even consider a path of metric spaces for continuous time.

A: I'm glad to find your question. One of my research interests is to study dynamic metric spaces from the perspective of metric geometry and persistent homology. In my papers, you can find

*

*a certain definition of dynamic metric spaces,

*metrics on dynamic metric spaces, and

*some invariants of dynamic metric spaces.
Here are the links:

*

*Spatiotemporal Persistent Homology for Dynamic Metric Spaces (arXiv version)

*Stable Signatures for Dynamic Graphs and Dynamic Metric Spaces via Zigzag Persistence
Hope this helps you. FYI, some other results will appear in my thesis.


text:
Q: Type annotation for mutable dictionary I have a class MyClass with 2 methods. The methods change an attribute dic of type dict[str, A] by adding objects of subtypes B and C:
class A:
    ...

class B(A):
    def method_B(self): ...

class C(A):
    def method_C(self): ...

class MyClass:
    dic: dict[str, A] = {}

    def add_B_obj(self, name: str):
        self.dic[name] = B()

    def add_C_obj(self, name: str):
        self.dic[name] = C()

I would like to access the methods of the objects inside the dictionary after their creation, for instance, using Pylance.
For that, the following snippet doesn't work (see the warning):
m = MyClass()
m.add_B_obj('B_obj')

m.dic['B_obj'].method_B() # Warning: Cannot access member "method_B" for type "A"

To solve that, I tried to use typing.cast.
I'm not interested in objects of type C, so I used cast to force m.dic to be of type dict[str,B].
That allows me to access the method, but there was a new warning:
from typing import cast

m = MyClass()
m.add_B_obj('B_obj')

m.dic = cast(dict[str,B],m.dic['B_obj']) # WARNING

m.dic['B_obj'].method_B # now pylance shows me the method, but there is a new warning

The new warning is:
 Cannot assign member "dic" for type "MyClass"
  "dict[str, B]" is incompatible with "dict[str, A]"
    TypeVar "_VT@dict" is invariant
      "B" is incompatible with "A"

How do I solve this new warning?

A: Type safety for dict values
All values in a dictionary are treated the same by a static type checker.
If you tell the type checker that a dictionary dic can contain values of both type A and type B, but only B has the method method_B, then it logically follows that not all of the values in dic have method_B.
There is no way for the type checker to know for certain, if some particular value from dic has method_B.
In your example, B is a subtype of A, so by annotating dic with dict[str, A] you allow both A and B to be values in that dictionary. You could make the error more explicit, if you annotate it with dict[str, Union[A, B]] (which is equivalent from a typing perspective); then mypy for example will correctly tell you:
error: Item "A" of "Union[A, B]" has no attribute "method_B"

Highlighting the fact that B has it, but that is not enough for type safety.
The only way to assure the type checker that a specific value in the dictionary has method_B is to explicitly assert it for that specific key:
...
assert isinstance(m.dic['B_obj'], B)
m.dic['B_obj'].method_B()

Even this doesn't satisfy every type checker. mypy is happy, but the PyCharm built-in type checker still marks that last call saying:
Unresolved attribute reference 'method_B' for class 'A'

The other option is to use cast properly with an intermediary variable:
b = cast(B, m.dic['B_obj'])
b.method_B()

This should satisfy all type checkers.
I hope my explanation makes it clear that there is no other way around this.

Type (in)variance
As for the variance issue after cast-ing, your attempt is wrong for two reasons.
Firstly, you are only passing the value corresponding to the key 'B_obj' to cast, not the entire dic. Which means that after your assignment
m.dic = cast(dict[str, B], m.dic['B_obj'])

The attribute dic of object m is just that value, i.e. an instance of class B. This would lead to an TypeError, as soon as you tried this:
m.dic['B_obj']

Because B is not subscriptable (i.e. can not be used with []).
The type warning you then saw was because the type checker took you by your word and assumed you were really assigning something of type dict[str, B] to m.dic (even though you weren't).
And this is not allowed, because (as you are correctly told by the type checker) a dictionary is invariant in its value type. This is true by default for all generic types in Python, as stated in PEP 484.
In other words, since you declared .dic to be of type dict[str, A], you are not allowed to assign dict[str, B] to it, even though B is a subclass of A.

Niche alternative: TypedDict
If you know ahead of time that only very specific keys will be allowed in your dictionary, you can use the TypedDict construct.
It doesn't seem like this is what you are going for, since you allow adding keys via a public interface on MyClass, but if it were, you would just need to define your dictionary types as well as a corresponding Union of Literal types to annotate the name parameter in your methods. This amounts to a pretty verbose setup, but it works:
from typing import Any, Literal, TypeAlias, TypedDict, Union

class A:
    ...

class B(A):
    def method_B(self) -> Any: ...

class C(A):
    def method_C(self) -> Any: ...

class DicT(TypedDict, total=False):
    A_obj: A
    B_obj: B
    C_obj: C

KeyT: TypeAlias = Literal["A_obj", "B_obj", "C_obj"]

class MyClass:
    dic: DicT = {}

    def add_B_obj(self, name: KeyT) -> None:
        self.dic[name] = B()

    def add_C_obj(self, name: KeyT) -> None:
        self.dic[name] = C()

if __name__ == '__main__':
    m = MyClass()
    m.add_B_obj('B_obj')
    m.dic['B_obj'].method_B()

This passes mypy --strict with no issues.
Note that total=False on your TypedDict is necessary, since you want to allow any number of the supported keys to be present.
I also used TypeAlias just for better readability here.

In conclusion, I would recommend going the assert route as mentioned in the beginning. This not only satisfies some type checkers (don't know about Pylance), but it also adds an additional sanity check for you. Additional assertions are rarely a bad idea in my opinion.
Hope this helps.


text:
Q: trying to understand zeromq high water mark behaviour I have been playing around with pyzmq and simple load balancing using HWM, and I don't quite understand the behaviour I am seeing.
I have set up a simple multithreading test, with a DEALER client connected to two workers via a ROUTER to DEALER pattern. HWM is set to 1. One of the worker is very fast and the other is very slow, and all the client does is spam 100 messages to the server. This generally seems to work and the faster worker processes many more messages than the slow worker.
However, even if I set the slow worker to be so slow, such that the fast worker should be able to process 99 messages before the slow worker finished even one, the slow worker still seems to receive at least 2 or 3 messages.
Are high water mark behaviour inexact or am I missing something?
The server code is as follows:
import re, sys, time, string, zmq, threading, signal

def worker_routine(worker_url, worker_id, context=None):
    # socket to talk to dispatcher
    context = context or zmq.Context.instance()
    socket = context.socket(zmq.REP)
    socket.set_hwm(1)
    socket.connect(worker_url)

    print "worker ", worker_id, " ready ..."
    while True:
        x = socket.recv()

        if worker_id==1:
            time.sleep(3)

        print worker_id, x
        sys.stdout.flush()

        socket.send(b'world')

context = zmq.Context().instance()
# socket facing clients
frontend = context.socket(zmq.ROUTER)
frontend.bind("tcp://*:5559")
# socket facing services
backend  = context.socket(zmq.DEALER)
url_worker = "inproc://workers"
backend.set_hwm(1)
backend.bind(url_worker)

# launch pool of worker threads
for i in range(2):
    thread = threading.Thread(target=worker_routine, args=(url_worker,i,))
    thread.start()
    time.sleep(0.1)

try:
    zmq.device(zmq.QUEUE, frontend, backend)
except:
    print "terminating!"

# we never get here
frontend.close()
backend.close()
context.term()

The client code is as follows:
import zmq, random, string, time, threading, signal

#  prepare our context and sockets
context = zmq.Context()
socket = context.socket(zmq.DEALER)
socket.connect("tcp://localhost:5559")

inputs = [''.join(random.choice(string.ascii_lowercase) for x in range(12)) for y in range(100)]

for x in xrange(100):
    socket.send_multipart([b'', str(x)])

print "finished!"

Example output:
...
0 81
0 82
0 83
0 84
0 85
0 86
0 87
0 88
0 89
0 90
0 91
0 92
0 93
0 94
0 95
0 96
0 97
0 98
0 99
1 1
1 3
1 5

A: Apparently ZeroMQ send messages asynchronously from your send() call. That is to say, when send() returns, the message has not yet been sent, or added to the internal queue. If you send fast enough, the next time you call send, the message still hasn't been added to the queue, and thus the watermark has not been reached. You may add tens or hundreds of messages before some make it on the queue, the watermark is reached, and the blocking send behaviour kicks in.
In other words, try sleeping for a fraction of a second after send() and see what happens, it should give enough time for the message to be added to the queue, so by the time of the next send, it is able to see the watermark has been reached.

A: There are buffers on both sides of the connection.
Therefore:

*

*one message is queued on the backend socket

*one message is queued on the worker socket

*one message has been already taken out from the worker socket

So the total is 3 messages for the slow worker which is what your are seeing in the output.


text:
Q: Entrusting third party components in your projects How do you guys go about entrusting third party packages, libraries, etc. into your projects?  In other words, what steps, if any, do you take before incorporating an outside component into your project?  Does the sheer number of downloads satisfy your assurance that it is safe?  Is it considered safe if you downloaded it from github simply because it was github?  What about updates?  How can you be assured that the component will be kept up to date when you go back years from now to update your application?
**If this is not the right forum to post this - please tell me which one would be appropriate.

A: Doing your due diligence is part of the job when selecting third party components, hiring consultants or assigning internal project members for that matter.
Every project will have its balance between security (paranoia), cost and development speed.
When building critical bank applications Ive been in projects that always pair program and never include any external dependencies.
Most projects I work in suffice with checking component popularity and check we dont see obvious external connectivity during development and testing.
But end of the day this is a business decision, not a technical one.

A:
what steps, if any, do you take before incorporating an outside component into your project?

Some companies and language workflows are very reluctant to incorporate any components that don't come from the OS or platform vendor. Usually the first consideration is not so much reliability as licensing. Obviously you can't use GPL'd software in proprietary software, but many firms are wary of the non-viral open licenses too.

Does the sheer number of downloads satisfy your assurance that it is safe?
   Is it considered safe if you downloaded it from github simply because it was github?

Lots of people in the Open Source and Javascript communities regard those as reasonable assumptions. Others are more wary. Signed (GPG etc) commits are one way of tracing back source changes to specific developers.

What about updates? How can you be assured that the component will be kept up to date when you go back years from now to update your application?

Well, you can't really, unless you have a guarantee from the vendor. And that will usually come with an intended or implied end-of-life. You may be forced to rewrite a chunk of your application because a component has become obsolete.
That leads to the choice between copying the source into your application (stable, but not automatically updated) or downloading it as part of the build process (automatically updated but not stable).


text:
Q: Is it possible to change the URL of custom post types to hide the post type slug? I would like to turn /{custom-post-type}/{post-name} to /{post-name}, is this possible?
If this is not possible, can I change the labels/terminology in Pages or Posts so that they could be called "Clients" or "Projects" etc?

A: 'rewrite' => array('slug' => '/', 'with_front' => false)

This will get the url correctly formed for you, but it will 404 unless you handle it in your theme.

A: I just changed a slug for a custom post type (in this case, I changed it from "best-practices" to "bestpractices"). I had copied some code that had a blank slug, like so:
'rewrite' => array('slug' => ''),

Since it was originally left blank, Wordpress was just using the name of the custom post type ("best-practices") as the slug. I changed my line of code to
'rewrite' => array('slug' => 'bestpractices'),

I just wanted to note here that you'll need to reset your permalinks to get the change to take effect, if you're changing slugs on pre-existing custom post types.

A: You need to use option 'rewrite' in your custom post type registration.
E.g.
'rewrite' => array('slug' => 'products'),
From the codex

When you namespace a URL and still want to use a "clean" URL
  structure, you need to add the "rewrite" element to the array. For
  example, assuming the "ACME Widgets" example from above:
add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'acme_product',
      array(
          'labels' => array(
              'name' => __( 'Products' ),
              'singular_name' => __( 'Product' )
          ),
          'public' => true,
          'has_archive' => true,
          'rewrite' => array('slug' => 'products')
      )
  );
}

The above will result in a URL like
  http:/example.com/products/%product_name% (see description of
  %product_name% above.) Note that we used a plural form here which is a
  format that some people prefer because it implies a more logical URL
  for a page that embeds a list of products, i.e.
  http:/example.com/products/.
Also note using a generic name like "products" here can potentially
  conflict with other plugins or themes that use the same name but most
  people would dislike longer and more obscure URLs like
  http:/example.com/acme_products/foobrozinator and resolving the URL
  conflict between two plugins is easier simply because the URL
  structure is not stored persistently in each post record in the
  database in the same way custom post type names are stored.

A: yes, we can change the slug. Please follow the steps:
Step 1: Change the slug name from the option "rewrite". (located at Theme Functions (functions.php))
'rewrite' => array('slug' => 'products')
Step 2: Reset the permanent link. Otherwise, it will give 404 error.
1> goto wp dashboard.
2> Setting --> Permalinks
Under the common setting section---
1st change it to plain and save it.
After that, again change the setting as your preferred format.


text:
Q: An alternative way of displaying the negative values on the column chart I wonder if there's an alternative way of displaying the negative values on the column chart.
The bottom most value on the y axis should be the lowest value. The columns on the graph should grow from the bottom and upward to their corresponding values.
See images below with the current and expected behavior.
Current
Expected

A: It will be best if you use threshold property:
series: [{
    ...
    threshold: -20
}]

Live demo: http://jsfiddle.net/BlackLabel/0moe5q2y/
API Reference: https://api.highcharts.com/highcharts/series.column.threshold

A: I'm not into highcharts really, but I've lurked a bit and figured out this little, lets call it, hack ;p
Check this out please: https://jsfiddle.net/4goq1x6c/
If you want the min value to be set dynamically you could calculate it based on some condition and update every 0 element of the data's arrays and the min value of yAxis. (i.e. you could use some variable for simplification)
It's dirty (but not as much when I've looked again on it) I know it, but I haven't found anything native in highcharts docs. I hope it will be useful :)


text:
Q: Integration of an infinitesimal part In my EMF lecture, the professor first formulated the equation below for an infinitesimal part of a force and then integrated it. I can't explain this step with what I know from my math lectures. When integrating an equation, I would expect a '$\int_a^b dx$' (or some vectorial form of that) to be added to both sides but he just added the integral sign (no additional differential!). Furthermore, I would expect a change of dimension as a result of the integration (like e.g. acceleration integrated results in velocity) - accordingly, an integration of a force would not result in a force again. How can I explain what he did? I suspect that it is probably shorthand for some other integration.
$$d\vec{F}_{PP'}=\frac{1}{4\pi\varepsilon_0}\varrho(\vec{r}')\varrho(\vec{r})\frac{\vec{r}'-\vec{r}}{\lvert\vec{r}'-\vec{r}\rvert^3}dVdV'=-d\vec{F}_{P'P} \\ \implies \vec{F}=\frac{1}{4\pi\varepsilon_0}\int_V\int_V\varrho(\vec{r})\varrho(\vec{r}')\frac{\vec{r}-\vec{r}'}{\lvert\vec{r}-\vec{r}'\rvert^3}dV'dV=\vec{0}$$
Edit To simplify the question, essentially what I am asking is:
I know that
$$
f(x) = g(x)
\implies
\int_a^b f(x) \,dx = \int_a^b g(x) \,dx.
$$
But how do I explain that is valid:
$$
df = g(x)\,dh
\implies
f = \int_a^b g(x) \,dh
$$


text:
Q: What is the alternative for String.format() in GWT? While GWT is not emulate all java's core, what can be used as alternative for:
String.format("The answer is - %d", 42)?

What is the ellegant and efficient pattern to inject arguments to message in GWT?

A: You can simply write your own format function instead of doing brain storm.
public static String format(final String format, final String... args,String delimiter) {
    String[] split = format.split(delimiter);//in your case "%d" as delimeter
    final StringBuffer buffer= new StringBuffer();
    for (int i= 0; i< split.length - 1; i+= 1) {
        buffer.append(split[i]);
        buffer.append(args[i]);
    }
    buffer.append(split[split.length - 1]);
    return buffer.toString();
 }

A: Because most (as in 99.999%) message formats are static, known at compile-time, the way GWT approaches it is to parse them at compile-time.
You'll generally use a Messages subinterface for its ability to localize the message, but you'll sometimes rather need SafeHtmlTemplates.

A: In the 0.001% when template is not known at compile time you can use Javascript sprintf (see: http://www.diveintojavascript.com/projects/javascript-sprintf) as in:
public static native String format (String format, JsArrayMixed values) /*-{
  return vsprintf(format, values);
}-*/;

A: One elegant solution is using SafeHtml templates. You can define multiple such templates in an interface like:
public interface MyTemplates extends SafeHtmlTemplates {
  @Template("The answer is - {0}")
  SafeHtml answer(int value);

  @Template("...")
  ...
}

And then use them:
public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class);

...
Label label = new Label(TEMPLATES.answer(42));

While this is a little bit more work to set up, it has the enormous advantage that arguments are automatically HTML-escaped. For more info, see https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml
If you want to go one step further, and internationalize your messages, then see also https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages

A: You can write your own.
I wrote a version that just work with Strings(%s):
public static String format(final String format, final Object... args)
{
    checkNotNull(format);
    checkNotNull(args);

    final String pattern = "%s";

    int start = 0, last = 0, argsIndex = 0;
    final StringBuilder result = new StringBuilder();
    while ((start = format.indexOf(pattern, last)) != -1)
    {
        if (args.length <= argsIndex)
        {
            throw new IllegalArgumentException("There is more replace patterns than arguments!");
        }
        result.append(format.substring(last, start));
        result.append(args[argsIndex++]);

        last = start + pattern.length();
    }

    if (args.length > argsIndex)
    {
        throw new IllegalArgumentException("There is more arguments than replace patterns!");
    }

    result.append(format.substring(last));
    return result.toString();
}

A: why not writing a method like:
String appendAnswer(int result) {
    return "The answer is - "  + Integer.toString(result);
}

is resolving your problem because you do nothing like formatting in your code.
if you ever face the problem like converting integer/byte to Hex String you should use:
Integer.toString(int, 16);

A: I don't know GWT much but I am working on a GWT project and I needed this. While trying some alternatives, I have found that this is working;
import java.text.MessageFormat;

MessageFormat.format("The answer is - {0}", 42);

I don't know if the project's developers added something special to make this work or it is working by default.


text:
Q: Is there a way to set PYTHONPATH permanently? Every day, when I open an Ubuntu terminal and want to run a python project, I have to run previously export PYTHONPATH=$(pwd). Is there a way to avoid doing this every time I switch on my computer? Is there a way to set my PYTHONPATH permanently for that project?

A: Have you try adding the line you mention
export PYTHONPATH=$(pwd)

to ~/.bashrc or ~/.profile?

A: Put the following line in your ~/.bashrc file:
export PYTHONPATH=/the/location/of/the/path

A: You should be able to set it permanently through the ~/.bashrc file or ~/.profile file for your user. Just enter the line you showed into either of those files.


text:
Q: strcmp function return value in another function I  know what strcmp returns but I don't know what it returns in this code.
firstly I have this function:
static int match_str(const void *str1, const void *str2)
{

  return !strcmp((const char *)str1, (const char *)str2);
//if not equal return 1.
}

and then I have this
if (match_str) return 1; // not equal so return
else{  my code goes on} // equal so continue

What I don't understand is if str1 equals to str2, the match_str should returns 0. and then the code moves on.
but it adds a '!' operater. it seems like if they are equal strcmp=0, it returns to "!0 " which means"!0=1 " . but if returns to 1. it seems like if they are equal, it will stop.
Actually, it continues if they are equal.
I really confused why " return !strcmp " works rather than "return strcmp", what is the purpose of using '!' here.
thanks

A: From C Standard##6.5.3.3p5

5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

>> What I don't understand is if str1 equals to str2, the match_str should returns 0. and then the code moves on.
Because of use of ! operator with strcmp in return statement (return !strcmp(.....)), the match_str() will return 1 if string matches and 0 if they don't match.
>> I really confused why " return !strcmp " works rather than "return strcmp", what is the purpose of using '!' here.
The strcmp() returns 0 if string matches and non zero value if they do not match because it compares two null-terminated strings lexicographically.  The author of function match_str() actually wanted to return 1 if string matches and seems that, having this thought in mind, s/he has given name (match_str) to the function. The caller of match_str() function should be aware of this while using match_str() function.
if (match_str(str1, str2)) {
    //strings are equal
} else {
    //strings are not equal
}


text:
Q: C# WPF - Alternate blank row in datagrid I will like to add alternate blank row on my datagrid when data fetch from database.
(Although AlternationCount="2" AlternatingRowBackground="LightGray" was used and it do help to visually segregate row to row, it will better if the row to row data, it will having blank row to have greater visual experience)
Thanks

A: I is not a good idea to change visual expirience by adding some waste data. Probably you just need to modify style of your datagrid rows adding some extra space which you may fill as you wish.
For example, add new style to your resources:
<Style x:Key="MyDataGridRowStyle" TargetType="{x:Type DataGridRow}">
    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
    <Setter Property="ValidationErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <TextBlock Foreground="Red" Margin="2,0,0,0" Text="!" VerticalAlignment="Center"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridRow}">
                <Border x:Name="DGR_Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                    <SelectiveScrollingGrid>
                        <SelectiveScrollingGrid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </SelectiveScrollingGrid.ColumnDefinitions>
                        <SelectiveScrollingGrid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Name="ExtraRow" Height="20"/>
                        </SelectiveScrollingGrid.RowDefinitions>
                        <DataGridCellsPresenter Grid.Column="1" ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        <DataGridDetailsPresenter Grid.Column="1" Grid.Row="1" SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Visibility="{TemplateBinding DetailsVisibility}"/>
                        <DataGridRowHeader Grid.RowSpan="2" SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                        <TextBlock Grid.Row="2" Grid.Column="1" Text=" *** Extra space *** " FontSize="8" VerticalAlignment="Center" Margin="100,0"/>
                    </SelectiveScrollingGrid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsNewItem" Value="True">
            <Setter Property="Margin" Value="{Binding NewItemMargin, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
        </Trigger>
    </Style.Triggers>
</Style>

Then use it in your DataGrid:
<DataGrid RowStyle="{StaticResource MyDataGridRowStyle}">

You will get something like:

ADDED:
And template
<ControlTemplate TargetType="{x:Type DataGridRow}">
    <Border x:Name="DGR_Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
        <SelectiveScrollingGrid>
            <SelectiveScrollingGrid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </SelectiveScrollingGrid.ColumnDefinitions>
            <SelectiveScrollingGrid.RowDefinitions>
                <RowDefinition Name="ExtraRow1" Height="10"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Name="ExtraRow2" Height="10"/>
            </SelectiveScrollingGrid.RowDefinitions>
            <Border Grid.Row="0" Grid.Column="1" BorderThickness="0,0,0,1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" BorderBrush="Black"/>
            <DataGridCellsPresenter Grid.Column="1" Grid.Row="1" ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            <DataGridDetailsPresenter Grid.Column="1" Grid.Row="2" SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Visibility="{TemplateBinding DetailsVisibility}"/>
            <DataGridRowHeader Grid.RowSpan="4" SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
        </SelectiveScrollingGrid>
    </Border>
</ControlTemplate>

looks like

A: If you are binding a collection with your datagrid then it will not be possible because datagrid is filled by looking at the source of its items. I have a solution in mind but I don't think it will be appreciated.
In your collection enter an empty object at each alternating index. It will create an empty row in datagrid.


text:
Q: an integral estimate from Stein's book, Singular Integral I am reading the Stein's book Singular Integrals and Differentiability Properties of Functions. In the text (page 40), he states that
$$
\int_{|x|\geq 2|y|}\Big|\frac{1}{|x-y|^n}-\frac{1}{|x|^n}\Big| dx\leq C
$$
where $x,y\in \mathbb{R^n}$ and $C$ is a constant only depending on the dimension $n$.
Could you please explain me how to get this estimate?
Thanks in advance.

A: The estimate $\left|x\right|\geq2\left|y\right|$ implies
$$
\left|x-y\right|\geq\left|x\right|-\left|y\right|\geq\frac{\left|x\right|}{2}
$$
as well as $\left|\left|x\right|-\left|x-y\right|\right|\leq\left|y\right|$
and by the mean value theorem, we have
$$
\left|x\right|^{n}-\left|x-y\right|^{n}=n\cdot\left[\left|x\right|-\left|x-y\right|\right]\cdot\xi^{n-1}
$$
for some $\xi$ between $\left|x-y\right|$ and $\left|x\right|$.
In particular, $$0\leq\xi\leq\max\left\{ \left|x-y\right|,\left|x\right|\right\} \leq\left|x\right|+\left|y\right|\leq2\left|x\right|.$$
Thus,
$$
\left|\left|x\right|^{n}-\left|x-y\right|^{n}\right|\leq n\cdot\left(2\left|x\right|\right)^{n-1}\cdot\left|y\right|.
$$
This leads to
$$
\left|\frac{1}{\left|x-y\right|^{n}}-\frac{1}{\left|x\right|^{n}}\right|=\frac{\left|\left|x\right|^{n}-\left|x-y\right|^{n}\right|}{\left|x\right|^{n}\left|x-y\right|^{n}}\leq2^{n}n\cdot\left|y\right|\frac{\left|x\right|^{n-1}}{\left|x\right|^{2n}}=2^{n}n\cdot\left|y\right|\cdot\left|x\right|^{-n-1}.
$$
Now calculate (using integration in polar coordinates)
\begin{eqnarray*}
\int_{\left|x\right|\geq2\left|y\right|}\left|x\right|^{-n-1}\, dx & = & \int_{2\left|y\right|}^{\infty}r^{n-1}\int_{S^{n-1}}\left|r\xi\right|^{-n-1}\, d\xi\, dr\\
 & = & C\cdot\int_{2\left|y\right|}^{\infty}r^{-2}\, dr\\
 & = & \frac{C'}{\left|y\right|}
\end{eqnarray*}
and hence
\begin{eqnarray*}
\int_{\left|x\right|\geq2\left|y\right|}\left|\frac{1}{\left|x-y\right|^{n}}-\frac{1}{\left|x\right|^{n}}\right|\, dx & \leq & 2^{n}n\cdot\left|y\right|\cdot\int_{\left|x\right|\geq2\left|y\right|}\left|x\right|^{-n-1}\, dx\\
 & \leq & \frac{2^{n}n\cdot C'}{\left|y\right|}\cdot\left|y\right|=C''.
\end{eqnarray*}


text:
Q: Errata on Rezk's paper I am reading this paper of Rezk's http://arxiv.org/abs/0901.3602 A cartesian presentation of weak n-categories, and as it is pointed out in the introduction, it contained a wrong statement (2.19 in the old version) and now there is a new proof for the main result, which is 6.6.
Now, section 6.9 of the new proof refers to Prop. 6.4, which uses 2.19 towards the end.
Am I missing something? How is this apparent circularity resolved?
Thanks in advance!

A: It looks like I completely missed this.
Here's what I guess happens: although the original 2.19 was wrong, there is a weaker version that is true (I'll just state it for simplicial sets):  If $X$ is a simplicial set, and $\mathcal{P}$ a finite collection of subobjects of $X$ which is closed under intersections, and the $\bigcup_{K\in\mathcal{P}} K=X$, then $\mathrm{hocolim}_{\mathcal{P}} K \approx X$. I think the original non-proof of 2.19 that I gave was really trying to prove this weaker version (I'll try to get that straight when I have some time).
Now the weak version of 2.19 applies to the poset $\mathcal{P}_K$.  Almost: $\mathcal{P}_K$ isn't necessarily closed under intersection (finite limits), but only because it fails to contain an initial object, corresponding to $\varnothing \to K$.  If you append this object to $\mathcal{P}_K$, the argument seems to go through (note that $V_\varnothing(A_1,\dots,A_m)$ is itself empty).
Working this out ...
Let $\{S_i\}_{i\in I}$ be an indexed collection of (distinct) subsets of a set $S$, implicitly making $I$ into a poset by set-inclusion, whence a functor $F\colon I\to Set_{/S}$.  Suppose (*) every element of $S$ is contained in a minimal $S_i$, i.e., for each $x\in S$, there exists $i(x)\in I$ such that $x\in S_j$ iff $S_{i(x)}\subseteq S_j$.  (This holds in particular if the indexed collection is closed under intersection, but is a weaker condition in general.)
Condition (*) implies that the functor $F$ is a coproduct of free functors: $F\approx \coprod_{x\in X} \mathrm{Hom}_I(i(x),-)$.  In particular, $\mathrm{colim} F \approx S$.
Now suppose $\{S_i\}_{i\in I}$ is an indexed collection of subobjects of a simplicial set $S$, satisfying (*) in each degree.  Using the above observation (applied inductively by degree to non-degenerate simplicies of $S$), we see that the functor $F\colon I\to sSet$ is cofibrant in the projective model structure.  As a consequence, $\mathrm{hocolim} F \xrightarrow{\sim} \mathrm{colim} F\approx S$.  We can extend the claim to replace $sSet$ with $Fun(C,sSet)$, since hocolims in functor categories are computed termwise.
This gives a version of 2.19 which is true, and which should apply to the $\mathcal{P}_K$ of 6.4.  I think.


text:
Q: Convert Binary String to Binary in c# How do I convert a String written as Binary, to binary (in byte array)?
EDIT: I want to write on textBox a binary data as (0101111100010101..), and when I want to take it I use textBox.text (this way give me binary string "0101111100010101...") therefore when I convert it to byte array it give me: (48 it means "0") and (49 it means "1") which is ASCII, now I want to convert each 8 bits from binary string: "0101111100010101" to byte (create a byte array)