Help me conclude a statement about two points given the following....

Question: Two points on the graph of $y=kx^p$ are labeled $A$ and $C$.  Point $A$ has coordinates $(a,b)$, where $0<a<1$ and point $C$ has coordinates $(c,d)$, where
$1<c$. If we are told that that the product
$k\cdot p$ is negative, what can be concluded about the points $A$ and $C$?
Defend your answer.
I can't figure this out. I have tried multiple times. The hint in the book that I have to prove y is decreasing so I figured then $a<b$ and $c>d$. How would I prove this.
Comment: There are two cases : $k > 0$ and $p <0$ or $k <0$ and $p>0$.  Try to break down what happens in each.
Answer: Note that
$y' = kpx^{p-1}$
so,
for $x > 0$,
$y'< 0$.
Therefore
$y$ is decreasing for $x > 0$.
Since $0 < a < 1 < c$,
$y$ is decreasing at both
$A$ and $C$.
Since $a < 1 < c$,
$A$ is to the left of $C$.
Since $y$ is decreasing,
$A$ is above $C$.
Answer: Note first that $0<a<1<c$, and keep that in mind. Note also that $b=ka^p$ and $d=kc^p$, so that $A$ is the point $(a,ka^p)$, and $C$ is the point $(c,kc^p)$.
If $pk<0$, then one of $p$ and $k$ is positive, and the other is negative. Consider the two cases separately.

Suppose that $p>0$ and $k<0$. You should know that when $p>0$, the function $f(x)=x^p$ is increasing on the positive reals; that is, if $0<x_0<x_1$, then $0<x_0^p<x_1^p$. Since $0<a<c$, that means that $a^p<c^p$. But you're not interested in $a^p$ and $c^p$: you want $ka^p$ and $kc^p$, where $k$ is negative. When you multiply an inequality by a negative number, you must reverse the direction of the inequality, so $ka^p>kc^p$. In other words, the point $C$ is to the right of $A$, because $c>a$, but it's also below $A$, because $d=kc^p<ka^p=b$. To get from $A$ to $C$, you must go to the right and down, so the graph of $y=kx^p$ has dropped from $A$ to $C$: the function is decreasing.
Now suppose that $p<0$ and $k>0$. You should know that when $p<0$, the function $f(x)=x^p$ is decreasing on the positive reals: if $0<x_0<x_1$, then $x_0^p>x_1^p$. (If you're not sure, draw graphs for a few negative values of $p$.) Since $a<c$, this means that $a^p>c^p$. Multiplying an inequality by a positive number doesn't change the direction of the inequality, so what can you say about $ka^p$ and $kc^p$? And what does that tell you about the relative positions of $A$ and $C$?
Comment: it means that $ka^pc^p$, so $ka^p>dc^p$. In other words, $A$ and $C$ are related in this case exactly as they were in the first case: $C$ is to the right of and below $A$.


Special properties of matrices of rank r, where any r lines are linearily independent

Question: Let $M$ be a square complex-valued $n \times n$ matrix of rank r ($r < n$). Suppose that any r lines are linearly independent.
1) Do such matrices exist? They exist for rank 0, and trivially for rank 1, but I haven't been able to find non trivial examples.
2) Does this imply that any r columns are linearly independent?
Also, any such documentation would be helpful.
(Motivation: I'm trying to solve the following problem: find all $n \times n$ complex-valued matrices A with rank $< n$ such that $rank(AB) = rank(BA)$ for any $B$ that is $n\times n$. I have been able to show that $A$ must have the property discussed above.)
Answer: By "lines" I assume you mean rows.
If $r$ rows of matrix $M$ are linearly dependent, it means there is a nonzero row vector $v$ with at most $r$ nonzero entries such that $v M = 0$.  Now if $M$ has rank $r$, the space $N$ of row vectors $v$ such that $vM =0$ (the left null space of $M$) has dimension $n-r$.  For a given subset $S$ of $[1\ldots n]$ with cardinality $r$, the space $R_S$ of row vectors whose nonzero entries are restricted to positions in $S$ has dimension $r$, so "generically" its intersection with
$N$ will be $\{0\}$.    Thus a randomly chosen matrix $M$ of rank $r$ will have the desired property with probability $1$.
It's not equivalent to the same property for columns, but again both will be true generically.


Getting Drupal 8 to use an external index?

Question: I have two sites one is maintained by us in drupal 8 and the other is maintained by another company that does the news updates etc for our company. I'm trying to figure out the best way to get a combined search in drupal. So set up a Solr instance and setup a web crawler to crawl the other site, set up drupal 8 to use the search api and solr search. But now i'm not sure what's the best way to integrate the index created by the web crawler with drupal 8. Any ideas?
Answer: What you could do is use the Migrate module to migrate content from one site to the other. What you need to do is:

Build a custom source plugin for it so that it fetches its data from an external source (i.e. the other site) and map it to a content type in your Drupal install.
Then set up a cron job to run the migration periodically to update the data on your end. Make sure you set the migration to "update" since by default, migrations won't happen on already-migrated content.
Create your search however you want in your site (Views, Search API, etc.) using that content type.

In D7, this was a job for the Feeds module but they don't appear to have a D8 version yet.
Comment: This may work, somewhat, but Migrate and the D8 API were not built to sync content that has been deleted for example -- so what you're describing will work for new content, or updated content on the external site ... but will not necessarily "delete" the drupal copy of content should the external item be deleted from the other site.
Comment: I don't have any access to the other site, it's not drupal 8, it's some other CMS, hence the web crawler.
Comment: You don't want to migrate content in, Solr and Solarium can solve this. I just did it for three sites sharing one core. The practical way to do this is to create a custom search controller and leverage the Solarium client to query Solr, so you get all the Drupal items and non drupal items. Search API and Views will limit it only to what it's aware of in Drupal - I have yet to see a federated approach not done with some custom code. On the upside, it does not take a lot. Just have the other company index their content to your solr instance.


Python regular expression to match and replace gradle dependencies output

Question: I am super novice to regular expressions and Python, but want to achieve that.
I have this input:
\--- org.projectlombok:lombok:1.+ -> 1.16.6

+--- org.springframework:spring-aspects: -> 4.1.7.RELEASE
|    \--- org.aspectj:aspectjweaver:1.8.6
+--- org.springframework.boot:spring-boot-starter-web: -> 1.2.6.RELEASE
|    +--- org.springframework.boot:spring-boot-starter:1.2.6.RELEASE
|    |    +--- org.springframework.boot:spring-boot:1.2.6.RELEASE
|    |    |    +--- org.springframework:spring-core:4.1.7.RELEASE
|    |    |    \--- org.springframework:spring-context:4.1.7.RELEASE

Need to get a Python script, regular expression to remove "\" "-" "+" and space in the beginning of the line and replace word or space before "->" with the one after "->"
So the output should be:
org.projectlombok:lombok:1.16.6
org.springframework:spring-aspects:4.1.7.RELEASE
org.aspectj:aspectjweaver:1.8.6
org.springframework.boot:spring-boot-starter-web:1.2.6.RELEASE
org.springframework.boot:spring-boot-starter:1.2.6.RELEASE
org.springframework.boot:spring-boot:1.2.6.RELEASE
org.springframework:spring-core:4.1.7.RELEASE
org.springframework:spring-context:4.1.7.RELEASE

By the way This is output from gradlew dependencis for a project. Maybe there is a way to get this output from gradlew?
OK, this code does it in Python:
#!/usr/bin/env python

import re

with open('testfile') as infile, open('testout', 'w') as outfile:
    for line in infile:
      line = line.replace("\\","")
      line = line.replace("-","")
      line = line.replace(" ","")
      line = line.replace("+","")
      line = line.replace("|","")
      line = re.sub(r'(:[0-9.+]+)>', r':', line)
      line = re.sub(r':>', r':', line)
      outfile.write(line)

Output:
org.projectlombok:lombok:1.16.6

org.springframework:springaspects:4.1.7.RELEASE
org.aspectj:aspectjweaver:1.8.6
org.springframework.boot:springbootstarterweb:1.2.6.RELEASE
org.springframework.boot:springbootstarter:1.2.6.RELEASE
org.springframework.boot:springboot:1.2.6.RELEASE
org.springframework:springcore:4.1.7.RELEASE
org.springframework:springcontext:4.1.7.RELEASE

Comment: Can you show us what you have tried so far?
Comment: [Should "Give me a regex that does X" questions be closed?](http://meta.stackoverflow.com/questions/285733/should-give-me-a-regex-that-does-x-questions-be-closed/285739#285739)
Comment: Also, why don't you write a gradle task that will print out what you need?
Comment: Well, if you can point me to the resource that describe that I would be grateful. I need to get the list in the form as I mentioned in the output example (with version used, without "->" symbols). Please don't hate me :), I am just a beginner in this area, figured out this would be the great place to start my research
Comment: Have you thought about `line.lstrip(' -\+')`?
Comment: I updated my question with the latest version of Python code. It seem to be doing what I wanted. It is a ditry version :) Python experts, feel free to update it with clean and better version.
Answer: Not sure why you would want to use python for this when gradle is designed with dependency management built-in.  A simple gradle task could write the file for you.  The below would be executed by running gradle writeDependencyFile
task writeDependencyFile << {
    File output = new File("$project.rootDir.absolutePath/dependencies.txt")
    configurations.compile.each { File file ->
        output.append("${file.name.substring(0, file.name.lastIndexOf('.'))}\n")
    }
}

Answer: Not sure if you still need solution or not but today found regex pattern for that hope it will help.
\w.*\S:\w.*


Showing that $f_n:[0,1]\to\mathbb{R}$ when $f_n=nx(1-x)^n$ converges pointwise but not uniformly

Question: Suppose $f_n:[0,1]\to\mathbb{R}$ such that $f_n=nx(1-x)^n$, then I need to show that $f_n$ converges pointwise but not uniformly. I can see that since $f$ is defined on $[0,1]$, the part $(1-x)^n$ is smaller than $1$ and therefore will converge, but what about $nx$? This will go to infinity...
Therefore, I can't even see that it converges pointwise, but let's suppose it converges to some function, how do I show that it doesn't converge uniformly? I should find an $\epsilon$ such that it's not valid for all $n>n_0(\epsilon)$ that $|f_n-something|<\epsilon$, right?
Comment: Hint: fix an $x$ and consider the limit of $nx(1-x)^n$. It is a limit of the form $\infty\cdot 0$, but there are many ways to evaluate it (l'Hospital for example). This will let you find the function $f$ it converges to. Now consider $f_n-f$. What is the maximum of this difference?
Comment: Exponential decay always beats out polynomial growth.
Answer: $f_n$ converges pointwise to the $0$ function. It is trivial to see it for $x=0,1$ so let $x\in(0,1)$ be fixed and notice that $$f_n(x)=nx(1-x)^n=xe^{n\log(1-x)+\log n}.$$
As $x>0$ we know that $\log(1-x)$ is a negative number, so $n\log(1-x)+\log n\to-\infty$ as $n\to\infty$; i.e. $f_n(x)\to0$ as $n\to\infty.$
So we know that $f_n$ converges pointwise to $0$ as $n\to\infty$.
To see that this convergence is not uniform let's first find the maximum of $f_n$. This polynomial is positive in $(0,1)$ and $0$ in $x=0,1$ so it must attain its maximum at some $x_n\in(0,1)$. As $\log x$ is an increasing function we can maximize $\log f_n$ instead of $f_n$. As
$$
\frac{d}{dx}\log f_n(x)=\frac{d}{dx}\left[\log n+\log x+n\log(1-x)\right]=\frac{1}{x}-\frac{n}{1-x}=\frac{1-x-nx}{x(1-x)}
$$
equals zero only for $x=\frac{1}{1+n}$, this is the only critic point of $f_n$ and therefore $x_n=\frac{1}{1+n}$. Now we are done because
\begin{align}
\sup_{0\leq x\leq1}f_n(x)=f_n(x_n)=&\frac{n}{1+n}\left(1-\frac{1}{1+n}\right)^n\\ =&\frac{n}{1+n}\underbrace{\left(1-\frac{1}{1+n}\right)^{-1}}_{=(1+n)/n}\left(1+\frac{-1}{1+n}\right)^{1+n}\underset{n\to\infty}{\to}e^{-1}>0.
\end{align}
Answer: Clearly $f_n(x)\to f(x)=0$ as $n\to\infty$ in [0,1]. Let $f_n'(x)=0$ and then $x=\frac{1}{n+1}$. It is easy to see that $f''_n(\frac{1}{n+1})<0$ and hence $f_n(x)$ reaches the maximum $f(\frac{1}{n+1})=(\frac{n}{n+1})^{n+1}$ at  $x=\frac{1}{n+1}$.
Thus
$$ \max |f_n(x)-f(x)|=(\frac{n}{n+1})^{n+1}\to\frac1e\neq0$$
as $n\to\infty$. Thus $f_n(x)$ does not converge uniformly to $0$.


my keras cannot load a model. "Invalid input_shape argument" Error message

Question: I want to load a model I trained before.
my code is as bellows.
top3_acc = functools.partial(tf.keras.metrics.top_k_categorical_accuracy, k=3)
top3_acc.__name__ = 'top3_acc'

modelName = "/root/workspace/cc_classifier/generatedModels/whole_model.pb"
sdi_model = keras.models.load_model(modelName, custom_objects={'top3_acc': top3_acc})

then, my keras return a error message like as bellows.
File "/root/workspace/cc_classifier/scripts/tester/modeltester.py", line 28, in <module>
sdi_model = keras.models.load_model(modelName, custom_objects={'top3_acc': top3_acc})
File "/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py", line 492, in load_wrapper
  return load_function(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py", line 584, in load_model
 model = _deserialize_model(h5dict, custom_objects, compile)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py", line 274, in _deserialize_model
      model = model_from_config(model_config, custom_objects=custom_objects)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py", line 627, in model_from_config
      return deserialize(config, custom_objects=custom_objects)
File "/usr/local/lib/python3.6/dist-packages/keras/layers/__init__.py", line 168, in deserialize
      printable_module_name='layer')
File "/usr/local/lib/python3.6/dist-packages/keras/utils/generic_utils.py", line 147, in deserialize_keras_object
      list(custom_objects.items())))
File "/usr/local/lib/python3.6/dist-packages/keras/engine/network.py", line 1075, in from_config
      process_node(layer, node_data)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/network.py", line 1025, in process_node
      layer(unpack_singleton(input_tensors), **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py", line 506, in __call__
      output_shape = self.compute_output_shape(input_shape)
    File "/usr/local/lib/python3.6/dist-packages/keras/engine/network.py", line 612, in compute_output_shape
      str(len(self._input_layers)) + ' tensor inputs.')
    ValueError: Invalid input_shape argument [(None, 1500), (None, 400)]: model has 1 tensor inputs.

I don't know the reason.
How can I fix it?
add
I trained my model with multi-gpu option.
model = keras.utils.multi_gpu_model(model, gpus=[0,1,2,3])

This option can make this error?
Comment: looks like `top3_acc` does not have the proper shape for `modelName`. Would it be possible for you to print the *shape* of `top3_acc`. Isn't the detected `[(None, 1500), (None, 400)]` supposed to be `(400,1500)` or something of this vein?
Comment: Are you running this code as root? That is a very bad idea.
Comment: Thanks @MatiasValdenegro, but I use a scale container for only this task. In physical server, I run my code with low power account.
Comment: @zar3bski with this line "print (top3_acc.shape())", I've got a mesage,  "AttributeError: 'functools.partial' object has no attribute 'shape'". How can I print that?
Comment: my bad, `custom_objects` accepts functions
Comment: Still its  bad idea, anyways, did you train this model using tf.keras?
Comment: @MatiasValdenegro no, just keras. So I modified my code like, "top3_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=3)". But still I've got a same message.
Answer: I'm sorry. It was my fault.
I designed two input layers, syllable and morpheme.
cnnModelInput = keras.layers.Input(shape=(self.lexicalMaxLength,), name="syllable_input")
posModelInput = keras.layers.Input(shape=(self.morphemeMaxLength,), name="morphemePos_input")

inputFormat = [cnnModelInput, posModelInput]

I input "cnnModelInput" in the position of "posMudelInput"
In spec, this model has two input layers, but the model never used "posModelInput".
So that error message was emerged.
Thank you!!


Concatenar strings em Javascript

Question: Tenho a seguinte função, que altera o valor numérico de uma string quando encontrado:
var original = "Este aqui é o valor do cliente 000.000.00 01";
var original = str.match(/\d\d\d\.\d\d\d\.\d\d \d\d/)
var novo = "129.000.000 02";
original = original.replace(/\d\d\d\.\d\d\d\.\d\d \d\d/g, novo);

O que eu preciso fazer é que quando ele encontrar e alterar o valor numérico os 2 números finais ele mantenha o da string original. No caso ai de cima, seria assim:
Resultado = 129.000.000 02
O que eu preciso:
Resultado = 129.000.000 01 (esse 01 seria os 2 últimos dígitos da string original)
Comment: Juro que eu tentei, mas nao consigo entender o que tu precisa, tenta contextualizar mais
Comment: rsrssrs @FelipeKM essa foi boa. Vamos lá, vou ser prático.
Comment: @FelipeKM, editei a pergunta, veja se entendeu.
Answer: Utilize essa expressão /\d{2}$/ para capturar os dois últimos números de uma string.
var foo = "Este aqui é o valor do cliente 000.000.00 01";
var number = foo.match(/\d\d\d\.\d\d\d\.\d\d \d\d/); // 000.000.00 01
var to_replace = "129.000.000 02";
var lastnumber = foo.match(/\d{2}$/); // 01
to_replace = to_replace.replace(/\d{2}$/, lastnumber);

alert("Valor original: " + number); // 000.000.00 01
alert("Novo valor: " + to_replace); // 129.000.000 01

Demo

Concatenar strings em Javascript


How to create a user listing page with a tpl.php

Question: I would like to create a listing page of users of a particular role.
Inside this view, there should be another view which shows the related content for each user.
When I try to create a view the system gives me the option to use just fields, but I need to be created like a node so I can use a tpl.php file.
How can I get a tpl.php file for this?
If I create a view for the users and one with the contents(contextual filter uid), can I embed  the second view inside the view-unformatted.tpl.php?
Answer: Here I create similar page with views: http://cgart.ir/en/members
as you can see there is a list of users and 5 last uploaded image. the page created with views and latest artworks is another views.
to do that:

create first view for list users and in Format select Show:Rendered entity | Settings
create second view and configure CONTEXTUAL FILTERS and add Content: Author uid

edit user-profile.tpl.php and render second view there:
$account = $variables['elements']['#account'];
<?php print views_embed_view('second_view', 'page_1', $account->uid); ?>

Comment: Hi Mohammad, thanks for you answer, it does almost what I want. If you cloud tell me just the last thing. If i want to not affect the profile page it-self, in temrs of views and style, should I manage it through css? For example a want a box to be shown on the listing page but not in the profile page. How can I do this?
Comment: you can add new `view mode` to profile via `hook_entity_info_alter()` and with `$view_mode = $variables['elements']['#view_mode'];` you can make difference in `full` and `list` mode of user profile... let me know if it's not enough...
Comment: $view_mode is like $page? It makes differences beetwen listing and node? Now I will do some research. If I need suggestions, I will write it here.
Comment: go to views setting and in `Show:Rendered entity | Settings` select another `view mode` for list


File always save with underscore

Question: I have a custom form where admin users upload a CSV file. Everything is working fine, but the file is saved with an underscore. For example, I upload callLog4127_Lorem_20170701.csv but the file is saved as callLog4127_Lorem_20170701_1.csv.
I checked the database, but I don't find any reference to callLog4127_Lorem_20170701. I also deleted the temp folder, and ran cron, but I am still getting the same problem.
It happens just with this file; when I upload another file it's working correctly, which means the filename is not changed.
This is my form validation handler. Is there anything wrong with it that could cause the behavior I am seeing?
function upload_rtap_validate($form, &$form_state) {
  $file = file_save_upload('calllogrtap_file', array(
    'file_validate_extensions' => array('csv'), // Validate extensions.
    'public://mrtap/', FILE_EXISTS_REPLACE
  ));

  if ($file) {
    $file = file_move($file, 'public://mrtap/', FILE_EXISTS_REPLACE);
    $file->status = 1;
    file_save($file);
    $form_state['storage']['filename'] = $file->uri;
  }
}

If I print the content of $file with print_r($file), after file_save_upload(), I get the following.
stdClass Object(
  [uid] => 1
  [status] => 0
  [filename] => callLog4127_GentleDental_20170701.csv
  [uri] => temporary://callLog4127_GentleDental_20170701_4.csv
  [filemime] => text/csv
  [filesize] => 48429
  [source] => calllogrtap_file
  [destination] => temporary://callLog4127_GentleDental_20170701_4.csv
  [timestamp] => 1501309335
  [fid] => 235
 )

Comment: As side note, that code is moving the file twice: once with `file_save_upload()`, and once with `file_move()`.
Comment: What you are showing is the form validation handler, but what does the form submission handler do?
Comment: In submit just insert data in custom table
Answer: The main error is that you aren't passing the last two arguments of  file_save_upload() to that function, since you are putting them in the array you pass as second argument. The code you are using is the following one; see the comments I added.
  $file = file_save_upload('calllogrtap_file', array(
    // First line of the array
    'file_validate_extensions' => array('csv'),
    'public://mrtap/', FILE_EXISTS_REPLACE
    // Last line of the array
  ));

As you aren't passing the last two arguments to file_save_upload(), the function is using the default values for those parameters, which are:

$destination = FALSE
$replace = FILE_EXISTS_RENAME

The first values is making Drupal save the uploaded file in temporary://; the second value is telling Drupal to rename the file if there is already a file with that name.
The function call should be the following one.
  $file = file_save_upload('calllogrtap_file', array('file_validate_extensions' => array('csv')), 'public://mrtap/', FILE_EXISTS_REPLACE);

If you change the code in this way, then the following code line is not necessary, since the uploaded file is already moved in public://mrtap/ from the call to file_save_upload().
$file = file_move($file, 'public://mrtap/', FILE_EXISTS_REPLACE);

If filename is the ID of the form element for uploading the file, the following code probably needs to be changed.
$form_state['storage']['filename'] = $file->uri;

Probably, the correct line is the following one.
$form_state['values']['filename'] = $file;

I would also keep the code to validate the user input in upload_rtap_validate(), and the code saving the file as managed file in upload_rtap_submit().
For example, see the code used from the form handlers for system_theme_settings(), system_theme_settings_validate() and system_theme_settings_submit(). (I replaced the comments with mine.)
  // system_theme_settings_validate()
  $file = file_save_upload('logo_upload', $validators);
  if (isset($file)) {
    // The user upload the logo file.
    if ($file) {
      // The uploaded file passed the validation in $validators.
      $form_state['values']['logo_upload'] = $file;
    }
    else {
      // The file upload failed.
      form_set_error('logo_upload', t('The logo could not be uploaded.'));
    }
  }

  // system_theme_settings_submit()
  // If the user uploaded a new logo, save it to a permanent location.
  if (!empty($values['logo_upload'])) {
    $file = $values['logo_upload'];
    unset($values['logo_upload']);
    $filename = file_unmanaged_copy($file->uri);
    $values['default_logo'] = 0;
    $values['logo_path'] = $filename;
    $values['toggle_logo'] = 1;
  }

In your case, you could use file_copy() instead of file_unmanaged_copy(), or file_save() as your code is doing.
Comment: Basically this, and also one of my main issues with the core file field. But since this is in custom code, FILE_EXISTS_REPLACE is the way to go.

File always save with underscore


How to write ElementTree to a file object in Python?

Question: I have a XML-file that I need to send to some URL. I do that this way:
data = { 'file' : open('test.xml', 'rb') }
req = requests.post(URL, files=data)

This works, but problem is that first I need to generate XML, then I need to do this:
et = etree.ElementTree(root)
et.write('test.xml', encoding='utf8')

and then after that I do this:
data = { 'file' : open('test.xml', 'rb') }
req = requests.post(URL, files=data)

But I don't like this, I have XML-file, then I write it to disk, just to read it again from disk.
Is there a way to write that XML directly to file object (equivalent of open('test.xml', 'rb')) without writing it to file first?
Answer: Try using tostring
Ex:
et = etree.ElementTree(root)
req = requests.post(URL, data=etree.tostring(et.getroot()))


For $G=\{\text{upper triangular matrix} \in GL(n,F)\}$, find Z(G)

Question: $G =  \left\{ \begin{pmatrix}1 & a & b\\0 & 1 & c\\0 & 0 & 1\end{pmatrix} \middle|a,b,c \in F \right\} $
$H =  \left\{ \begin{pmatrix}1 & 0 & d\\0 & 1 & 0\\0 & 0 & 1\end{pmatrix} \middle|d \in F \right\} $
Prove that $Z(G) = H$. I've managed to show that $ H \subseteq Z(G)$, but beside of taking a general matrix $x$, and checking its constraints by demanding $\forall g\in G,\ x=gxg^-1$ by multiplying and comparing the two matrices, I can't see how to finish this. It supposes to be a small "understanding" question, so I doubt if that's the writer's meaning.
Is there any more elegant way?
Answer: A matrix with $a \ne 0$ does not commute with the matrix with $a=b=0$, $c=1$,  whereas a matrix with $c \ne 0$ does not commute with the matrix with $a=1$, $b=c=0$. In both cases, the two products differ in their $(1,3)$ entry.
Answer: Do you already know about root subgroups? They are (in your case) given by $E_{12}=\{b=0, c=0\}$, $E_{23}=\{a=0,b=0\}$, $E_{13}=H$. Can you compute the commutator map $[,]: E_{12}\times E_{23}\to G$? Once you have done this, show that each element $g\in G$ can be written as the product $g_{12}g_{23}g_{13}$ where $g_{ij}\in E_{ij}$. Now, check that if, say, $g_{12}\ne 0$ then compute the value of $[g, g_{23}]$.
Comment: I'm not familiar with it , and on google I found mostly questions about root subgroups on stackexchange. Does it have an alternative term?


prototype update method to COPY vs MOVE

Question: i am using prototypes update method.  what i notice is that when it updates the receiving element with the providing elements innerHtml, the providing elements innerHtml is removed.  not only the innerHtml, but the entire element.
is it possible to retain both the element AND the innerHtml?
so basically i just want to COPY the innerHtml to the other element, instead of essentially MOVING the entire element.
is there a prototype function for this?
Answer:
is there a prototype function for
  this?

<code>$('targetelement').update($('copyelement').clone());
</code>

prototype update method to COPY vs MOVE


Here my singing. What should I focus on improving?

Question: Here are two short examples of my singing from two months and two weeks ago. What should I focus on improving?
http://myeasywebaddress.com/Stage/MusicTheory/YesterdayBeforeAfter.mp3
Comment: I think you'll do much better to find a teacher than try to use music.SE as your teacher.
Comment: ?...  Mr. Payne seems to offer a useful answer. (How can a question be good enough to get an answer with +2 votes but the question is -4?)
Comment: "Add details and clarify the problem you're solving."
(What should I focus on improving? What do you suggest?)
Answer: You're improving!  Better tone, and you're no longer clipping off the ends of your notes.  Well done.
What will you be doing with your singing?   I'd like to hear you singing with music.  Several songs, in different styles.   Work on preparing those recordings.
Comment: Good. Thank you. I am presently focused on Yesterday (picking in the same style as Paul) and also Luka, Knights in White Satin and Fly Me to the Moon ... singing while playing guitar (I must say that has not been easy to combine with good awareness of both.)  I may also add bass.
Comment: When you add bass, try songs sung by bassists - that will give you 'limb' independence. Roxanne [even if you have to sing it an octave down], Boys are Back in Town...
Comment: I may also add bass (GUITAR).


A question on time taken in different frames of reference .

Question: Let us say , a swimmer has to swim upstream and downstream a river , between two points which are at distance $L$ from each other . The swimmer can swim in still-water at velocity  $V_s$ , and the velocity of the river is $V_r$.
Now in the frame or reference of the river bank (or,ground) , his velocity upstream is $V_s-V_r$, and downstream is $V_s+V_r$, so the total time taken is
$$T_1=L \Bigg[\frac{1}{V_s+V_r} + \frac{1}{V_s - V_r}\Bigg]$$
Now if we observe the motion in the frame of reference of the river , the swimmer's velocity is Vs only , and as the distance is same , the time taken in this case is
$$T_2=\frac{2L}{V_s}$$
But shouldn't the time come the same ,regardless of the frame of reference ? I've tried putting in some values of $V_s$ and $V_r$ also and they are certainly not equal .
Please help me out , and point out where am I making a mistake and what should be the correct way of solving in different frames if references .
Thank you .
Comment: The problem is you're not considering that from the reference frame of some point moving in the river, the point you're measuring to is moving with velocity $V_r$ against the river. This accounts for the difference between the two perspectives.
Comment: Can you please elaborate using equations , or any other tool ? I am having difficulty understanding ,@StephenDonovan
Comment: The distance covered _by the swimmer_ in the frame of reference of the river is not $L$, both in upstream / downstream.
Comment: Why ? @MathLover
Comment: In the frame of reference of the river, the swimmer is still moving, but so are both the starting point and the finish line.
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format math on this site. To begin with, enclose all math expressions (including numbers) in `$` signs. For example, `$x_1^2$` will give you $x_1^2$. You'll get a much better response if your posts are easy to read.
Comment: Assume swimmer starts from point $A$ downstream and the time $t$ when the swimmer is at point $B$, at distance $L$ from $A$. In reference to the river, the distance covered by the swimmer downstream is $V_s \times t$, which is not $L$. But $V_s \times t + V_r \times t = L$.
Answer: Let's label the starting point $O$, the goal $A$, the swimmer $S$, and the reference frame of the river $R.$ Let's also define the positive direction as being downstream, so that $V_{R/O} = V_r.$
If we accept that the river has some velocity with respect to $O$ and $A$, then points $O$ and $A$ have an equal and opposite velocity in the $R$ reference frame. So, let $V_{A/R} = -V_r$. Also, the swimmer is swimming upstream, which is the negative direction, so let $V_{S/R} = -V_s.$
Now, the distance between the swimmer and $A$ can be written as $X_{A/S} = X_{A/R} - X_{S/R},$ where $X_{A/R}$ and $X_{S/R}$ are the positions of $A$ and $S$ with respect to $R.$ If you're confused where this comes from, I suggest drawing a diagram.
Taking derivatives with respect to time on both sides gives us $V_{A/S} = V_{A/R} - V_{S/R} = -V_r - (-V_s) = V_s - V_r,$ matching our result when measuring from the fixed frame.
Now, after the swimmer turns around they will have a new velocity $V_{S/R} = V_r,$ as they are now moving in the positive direction.
Now we can do $X_{O/S} = X_{O/R} - X_{S/R},$ so $V_{O/S} = V_{O/R} - V_{S/R} = -V_r - V_s,$ which matches our result when measuring from the fixed frame. (the sign is negative here because from the swimmer's perspective $O$ is travelling upstream, which is negative)
Comment: Thank you so much !!
Comment: No problem, have a nice day


sifr 2.0.7 only working when font is installed on user's computer?

Question: Hey all.  I am using sifr 2.0.7 and here's the deal. The sifr is working (I can see it in the DOM) however, the font is wrong.  It doesn't pick up my swf font (DIN) unless you have it installed on your computer?  The css font style is: HelveticaNeue which is what the sifr seems to render if you don't have DIN installed.  I see it on my computer but my friend see DIN.  Am I doing something wrong?
Thanks!
Answer: Make sure you've properly embedded DIN inside the sifr swf.  If the font isn't embedded there, Flash will fallback to a font installed on the user's system.
The sifr docs have some more details on this.
Comment: Would this cause Flash to fallback to using DIN?  Even though it isn't defined in the stylesheet?  Thanks.


How to hide header and footer from 404 page?

Question: I create a 404 page on D7 site ( ie. mysite.com/404), which is a Basic Page. I am trying to hide the header and footer from this page. The header and footer are blocks, and they are placed in every page using Context. I tried tweaking the Context so that if Path = 404, hide the header and footer.
It works when I go to mysite.com/404. However I try to hit an alias that doesn't exist (ie. mysite.com/asdf), instead of redirecting to /404, Drupal pulls the node body of the 404 page and stay at /asdf. The rule in the Context therefore doesn't apply.
I don't want to use the Visibility control in the Block module because migrating the configuration between sites can be troublesome. How would you go about it?
Answer: I do this by overriding the template used by the theme. In the template.php:
<code>/**
 * Set path to page-error.tpl if http error is returned.
 */
function yourtheme_preprocess_page(&$vars) {
  // Set custom error template:
  $http_status = drupal_get_http_header("status");

  if (isset($http_status)) {

    switch ($http_status) {
      case "403 Forbidden":
      case "404 Not Found":
      case "500 Internal Server Error":
        $vars['theme_hook_suggestions'][] = 'page__error';
        $vars['http_status'] = "Error: " . $http_status;
        $vars['error_message'] = drupal_get_messages();
        break;
    }
  }
}
</code>
Then you can create page--error.tpl.php in your templates directory using whatever regions you want to display. This has added the benefit of automating error pages, so you don't have to set a path in the site config.
Comment: Hi Adam, The "page--error.tpl.php" solution didn't work for me, but altering templates.php did the trick. Thank you very much!!
Comment: Glad you got it working- fyi you can get the page--error.tpl working by adding:

    if (isset($vars['node']->type)) {
        $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }


Inserindo dados de um datagridview c# em outro datagridview dando 2 cliques

Question: Estou criando um sistema de vendas.
Na tela de vendas possuo 2 datagridview
Sendo o  1º (pesquisa de produtos) onde recebo os dados da pesquisa do produto, e o 2º(produtos selecionados) será preenchido com os produtos selecionado no primeiro.
Quero que quando o usuário clicar duas vezes em cima da linha do produto o 2º datagridview seja preenchido com o produto selecionado, criando assim a lista de produtos que foram escolhidos pelo usuário.
Fiz o seguinte código:
 private void dataGridPesquisaProdutos_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        ProdutoColecao produtoColecao = new ProdutoColecao();
        Produto produtoSelecionado = (dataGridPesquisaProdutos.SelectedRows[0].DataBoundItem as Produto);
        produtoColecao.Add(produtoSelecionado);

        dataGridProdutosSelecionado.DataSource = null;
        dataGridProdutosSelecionado.DataSource = produtoColecao;
        dataGridProdutosSelecionado.Update();
        dataGridProdutosSelecionado.Refresh();

    }

Porém não estou conseguindo preencher o segundo datagridview com mais de um produto, sempre substitui pelo ultimo que foi selecionado.
Answer: Não consegue adicionar mais do que um produto porque de cada vez que evoca o evento de DoubleClick da célula está a criar uma nova instância do objeto produtoColecao.
Desta forma já deve conseguir:
ProdutoColecao produtoColecao = new ProdutoColecao();

private void dataGridPesquisaProdutos_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    Produto produtoSelecionado = (dataGridPesquisaProdutos.SelectedRows[0].DataBoundItem as Produto);

    if (!produtoColecao.Contains(produtoSelecionado))
        produtoColecao.Add(produtoSelecionado);

    dataGridProdutosSelecionado.DataSource = null;
    dataGridProdutosSelecionado.DataSource = produtoColecao;
    dataGridProdutosSelecionado.Update();
    dataGridProdutosSelecionado.Refresh();
}

Parte-se do princípio que a classe ProdutoColecao extende de uma lista.
Answer: Acontece que toda vez que você cai nesse método você tem uma nova instância de ProdutoColecao, assim você não está persistindo os dados que ela já possuia.
A solução para o problema é você inicializar esse objeto fora do método e apenas utilizá-lo quando der o duplo clique:
public class Pagina
{
    ProdutoColecao produtoColecao = new ProdutoColecao();

    private void dataGridPesquisaProdutos_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        Produto produtoSelecionado = (dataGridPesquisaProdutos.SelectedRows[0].DataBoundItem as Produto);
        produtoColecao.Add(produtoSelecionado);

        dataGridProdutosSelecionado.DataSource = produtoColecao;
        dataGridProdutosSelecionado.Update();
        dataGridProdutosSelecionado.Refresh();
    }
}


RRAS on WIndows Server 2019 with DHCP

Question: I have the following setup:
A Windows Server 2019 VM, which is also the AD Domain Controller. It has a public IP. I want to set up a VPN (RRAS) where the users can connect to so they are in the local network.
I made a new private Virtual Switch for that in the Host.
So the DC has 2 Network interfaces, one with a public IP and one with a private range, where I set a static IP 10.20.30.1 with a netmask of 255.255.255.0.
Then I set up a DHCP server there on the same machine.
I told the DHCP Server to offer addresses in the range 10.20.30.2-254
The DHCP Server is working fine (I tested it with another VM which I plugged into the Virtual Switch, it got a lease without problem).
Now I want the RRAS to get leases from the DHCP to use for the clients.
It was working fine one time (the RRAS got 10 leases, clients could connect, everything fine), but after a server reboot it is broken.
It's like the RRAS can no longer talk to the DHCP.
In the Remote Acces window it says that it could not get addresses for the VPN from the DHCP Server.
I am also a bit unsure about the configuration here.
I disabled the DHCP Relay Agent, because the DHCP is on the same machine - correct?
In the IPv4 Tab of the RRAS Settings where I have the choice between DHCP and static pool, I set it to DHCP. Does that automatically assume there is a DHCP up and running on the local machine? I suspect it might be asking the wrong interface - the DHCP is of course configured to only use the private Virtual Switch, so 10.20.30.1
As said - the DHCP seems to work fine, but the RRAS cannot communicate with it after the reboot.
Note: i do not want the network to route any traffic outside, so i don't want an internet connection over the VPN.
I am not even sure why it fails.
Answer: Can you try the work around to change below registry key value and restart DHCP Client service?

Path:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dhcp
Key name: RequiredPrivileges
Value:
(change from)
SeChangeNotifyPrivilege
SeCreateGlobalPrivilege

(to)
    SeChangeNotifyPrivilege
    SeCreateGlobalPrivilege
    SeImpersonatePrivilege
Thanks!
Comment: What would this do and why would it help?
Answer: I tried the registry fix and it worked for me.
<code>reg add "HKLM\SYSTEM\CurrentControlSet\Services\Dhcp" /v RequiredPrivileges /d "SeChangeNotifyPrivilege"\0"SeCreateGlobalPrivilege"\0"SeImpersonatePrivilege"\0 /t REG_MULTI_SZ /f
</code>
Comment: Do you have an explanation what that does?
Comment: reg add "HKLM\SYSTEM\CurrentControlSet\Services\Dhcp" /v RequiredPrivileges /d "SeChangeNotifyPrivilege"\0"SeCreateGlobalPrivilege"\0"SeImpersonatePrivilege"\0 /t REG_MULTI_SZ /f Doing this worked for me as well.
Answer: I have fought with server 2019 RRAS for about a week before I gave up and put server 2016 on and all my problems went away.  I had an issue where DHCP would not relay sometimes and after a reboot it started working again. I also had an issue after an update where the RRAS service would not start and would fail with error 8007042a. Removing KB4480116 fixed the problem for a while but eventually the problem came back.
Your really have 2 options here.
1) Pay Microsoft for a support call and see how that goes. (Good luck)
2) Install server 2016 and revisit the issue in about 6 months after microsoft fixes the problems with server 2019.  You can also monitor the Update History Website and see if they say something about RRAS in the release notes.
Here is the link to my problem: Windows Server 2019 VPN Error 8007042a After KB4480116
Here is a link to others with the DHCP problem: https://social.technet.microsoft.com/Forums/en-US/0270d377-be3a-4b63-82a0-9df076c5e3b3/upgrade-from-2016-to-2019-breaks-dhcp-relay-agent-when-using-rras
Comment: Okay... that is not what i wanted to hear ;-) but thanks anyways...
But one thing is still confusing me - the DHCP is on the same machine for me (which is also the AD DC), so i would not need a DHCP relay in this setup, correct?
The RRAS should be able to communicate with the DHCP.

You do assume the error is with the RRAS, so i could make a second VM with a Windows Server 2016 inside and just set the RRAS there, and then relay to the DHCP on the 2019 machine.
Comment: You do not need to relay DHCP unless your DHCP server is on another VLAN than your clients. DHCP relay is similar to a DHCP-Helper address that cisco uses. As far a the issues with server 2019, I am had setup several RRAS servers in 2016 and never had a problem.  The issues you are seeing are from my experience all from problems with RRAS and server 2019.  I would go ahead and build a server 2016 as a test and see if your problems are resolved.  Won't hurt anything to give it a try. In my case, server 2016 resolved both issues.
Answer: You could make the workaround trick.
Configure static address pool on the RRAS and configure a static pool in RRAS instead of the DHCP option, remember to exclude the range from your DHCP.
I have not tested this with server 2019 but I have tested this configuration with Server 2016, the configuration is the same as your configuration.
Answer: this problem is still on, in 2022 .The fix does not work for me. Static pool is working but I cannot set gateway for clients.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

RRAS on WIndows Server 2019 with DHCP


Closed subset of metric space $M$

Question: How would I prove that any finite subset of a metric space $M$ is closed? I would assume it would start with a sequence converging to a limit point,  but from there?
Answer: Hint: Let $S \subset M$ be a finite set. Show that $S$ has no limit points.
Answer: Let $M=\{m_1,m_2,\cdots,m_{n}\}$ and $\{a_1,a_2,\cdots\}$ be a converging sequence in $M$. Let:
$$\epsilon=\min_{1 \leq i < j \leq n} d(m_i,m_j)$$
Now $\{a_1,a_2,\cdots\}$ converges, so it's Cauchy sequence, so:
$$\exists N \; \forall i,j \geq N \; d(a_i,a_j)<\frac{\epsilon}{2}$$
So for all $i,j \geq $ you must have $a_i=a_j$ (if not $d(a_i,a_j) \geq \epsilon$).
Finally there exists $m_k$, that for $i>N$ we have $m_k=a_i$, so sequence $\{a_1,a_2,\cdots\}$ converges to $m_i \in M$.
Answer: Let $S$ be a finite subset of metric space $M$.
For $a\in M\setminus S$, we have that $r:=\min\{\,d(a,s)\mid s\in S\,\}$ is positive. Hence the $d$-ball around $a$ is disjoint from $S$. We conclude that $M\setminus S$ is open, hence $S$ is closed.

Closed subset of metric space $M$


Drupal configuration on non root url (how to change $base_url)?

Question: sorry for my english, I'm french
ok, that's I want to do is to install my drupal site on a url like :
www.mymachine.fr/mydrupal/
and the problem is that when I go this url,
he dispatch me to www.mymachine.fr/core/install.php
instead of www.mymachine.fr/mydrupal/core/install.php
so the install doesn't work
My conf is like this : debian server
in drupal file "sites.php", I have this :
$sites['mymachine.fr.mydrupal'] = 'mydrupal';
on /etc/hosts, I add this line  :
    127.0.0.1    mymachine.fr.mydrupal
on /etc/apache2/sites-available/000-default.conf :
<VirtualHost *:80>
    ServerName mymachine.fr.mydrupal
    DocumentRoot /var/www/mydrupal/CORE-DRUPAL8-WEB/web

    ServerAdmin webmaster@localhost

    # Log configuration
    ErrorLog ${APACHE_LOG_DIR}/drupal-error.log
    CustomLog ${APACHE_LOG_DIR}/drupal-access.log combined

    <Directory "/var/www/mydrupal/CORE-DRUPAL8-WEB/web">
            Options FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>

</VirtualHost>

SO I don't know if it's drupal configuration or apache configuration to change $base_url from drupal site ...
thanks a lot
Answer: If your drupal installation resides on the webserver in a subfolder of the webroot for www.mymachine.fr, you can set the base path in the drupal site's .htaccess file.

Find the line that reads # RewriteBase /drupal
Uncomment it by deleting the "#" RewriteBase /drupal
Edit it to reflect your subpath/subfolder # RewriteBase /mydrupal

That block should look like this after the edits.
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /mydrupal

Then, reset your .conf (vhost entry) to reflect just the top level website (code sample below resets to default .conf setup):
<VirtualHost *:80>
  ServerName mymachine.fr.mydrupal
  DocumentRoot /var/www

  ServerAdmin webmaster@localhost

  # Log configuration
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory "/var/www">
      Options FollowSymLinks
      AllowOverride All
      Require all granted
  </Directory>
</VirtualHost>

This setup presumes that your top level domain does not have any redirection rules that forward/process all requests (such as the rules in an out-of-the-box Drupal or Wordpress .htaccess for processing requests with index.php)  If your top level domain has such a redirect rule in place, you may need to add another rule to exclude your mydrupal subdirectory.


Como posso mudar a classe da div que o usuário clicou, sendo que tenho várias divs com o mesmo nome

Question: Eu tenho uma lista de card com a mesma classe. Eu queria saber como posso fazer para que quando alguem clicar no card, o card que ele clicou mude para a classe "active" e seja selecionado o checkbox.
HTML:

       <input type="checkbox" id="debitCheckbox" />

12x de R$144,50

       <input type="checkbox" id="debitCheckbox" />

12x de R$144,50

       <input type="checkbox" id="debitCheckbox" />

12x de R$144,50

JQUERY:
$('.sideFlex').find('.card').click(function () {
    $('.sideFlex').find('.card').toggleClass('active');
})

Comment: se passar o `this` como parametro do click, vai saber exatamente qual elemento foi clicado. O `this` nesse caso vai ser o elemento quem disparou o click
Comment: Show de bola, funcionou!

Agora, como posso fazer para que quando ele clicar nesse card, o input[checkbox] ficar como checked?
Comment: Eu queria também fazer um script para que ele possa selecionar apenas um card, tipo um input[radio] mesmo. Se ele clicar em 1 card, o outro que ele tinha selecionado é desmarcado
Comment: Fala Amigo. Minha estratégia seria através de uma função, capturar o event.target e setar nele a nova classe.
Answer: Aqui um exemplo.
Ao adicionar um handler para o evento click, é passado para a função o elemento que disparou o evento, que pode ser acessado com $(this).
No exemplo abaixo, usei o seletor $(".card"), que vai retornar todos os elementos com a class "card", ou seja, quando entrar na function, $(this) vai retornar o elemento clicado, dentre os elementos com a classe "card".
A partir daí é só usar esse elemento para aplicar a class, veja abaixo:

$(".card").click(function() {
  $(".card").removeClass("selecionado");
  $(this).addClass("selecionado");
});
.selecionado {
   background-color: cyan !important;
   color: red;
}

<link rel="stylesheet" href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

       <input type="checkbox" id="debitCheckbox" />

12x de R$144,50

       <input type="checkbox" id="debitCheckbox" />

12x de R$144,50

       <input type="checkbox" id="debitCheckbox" />

12x de R$144,50

Comment: Opa, funcionou!!
Agora, como posso fazer para que quando ele clicar nesse card, o input[checkbox] ficar como checked?
Comment: Ah já consegui!

`$(".sideFlex").find(".card").click(function () {
        $(".card").removeClass("active");
        $(".card").find('input[type="checkbox"]').prop('checked', false);
        $(this).addClass("active");
        $(this).find('input[type="checkbox"]').prop('checked', true);
      });`
Comment: ia comentar isso, precisava "deselecionar" todos e usar um find pra selecionar o input filho na div :)


Receive new value by two Class constructors

Question: I have Two Class:
public class ClassA {

String NewName;

public ClassA() {
    System.out.println("new name in A constructor: " + NewName);
}

public static void main(String[] args) {
    ClassA aM = new ClassA();
    aM.action();
    aM.displayNewName();
}

public void displayNewName() {
    System.out.println("new name in display method:" + getNewName());
}

public void action() {
    ClassB bA = new ClassB();
    System.out.println("new name in Action:" + getNewName());
}

public String getNewName() {
    return NewName;
}

public void setNewName(String newN) {
    NewName = newN;
    System.out.println("new name in A Set Method: " + getNewName());
}
}

And:
public class ClassB {

String newName = "jack";
ClassA a;

public ClassB(){
    a.setNewName(newName);
}
}

I can not receive jack value on my ClassA methods (like displayNewName() and action methods.
Update
    public class ClassB {

String newName = "jack";
ClassA a = new ClassA();

public ClassB(){
    a.setNewName(newName);
}
}

Output:
new name in A constructor: null
new name in A constructor: null
new name in A Set Method: jack
new name in Action:null
new name in display method:null

Comment: *"I can not receive"* << please detail (error, exception?)
Comment: @m0skit0 i receive `nullPointerException` or `Null` value occasionally
Comment: No offense meant: sincerely, you should get a good Java book and start reading. This is no place to learn how to program, but to ask specific questions. Your question is ever changing.
Answer: variable a is not initialized. it will throw nullpointerexception.
you need to initialize it in constructor by adding this line : a = new ClassA();
Edit1:
from what I understood, you need to do this:
public class ClassB {

String newName = "jack";

public ClassB(ClassA a){
    a.setNewName(newName);
}
}

and then in ClassB, modify action()
public void action() {
    ClassB bA = new ClassB(this);
    System.out.println("new name in Action:" + getNewName());
}

Comment: Well, Now i received this: `new name in A constructor: null
new name in A constructor: null
new name in A Set Method: jack
new name in Action:null
new name in display method:null`
Comment: @Sajjad check it again
Comment: where was my mistake?!
Comment: @Sajjad there were 2 objects of same ClassA, you were assigning to one but accessing from the other.
Answer: Change your ClassB
public class ClassB {

String newName = "jack";
ClassA a=new ClassA();  // Initialize a

public ClassB(){
    a.setNewName(newName);
}
}

Edit:
public void action() {
        ClassB bA = new ClassB();
        System.out.println("new name in Action:" + bA.newName);
    }

Comment: I want to see `jack` in my `action()` or `display()` method
Comment: @Sajjad check my edited `Action()`. In this way you can have it
Answer: a is not initialized. Try a=new ClassA(); in the constructor


Erro: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Question: No meu projeto coloquei uma barra de pesquisa, na qual o usuário informa um valor a ser pesquisado e seleciona a coluna na qual ele quer pesquisar.
O que vai ser pesquisado vem de um campo input type="text" e a coluna de um input type="radio", ambos no mesmo formulário.
 O problema é que, quando insiro as variáveis com os valores trazidos do formulário, o php me retorna um erro:

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\CRUD\php\listar_cliente.php on line 178

  <?php
  //Início da listagem

  $coluna = $_POST['coluna'];
  $pesquisa = $_POST['pesquisa'];

  $servidor = 'localhost';
  $usuario = 'root';
  $senha = '';
  $banco = 'portfolio';

if( $pesquisa == "")
{
    if( ($coluna == "") or ($coluna == "tudo"))
    {
        $COMANDO_SQL = "SELECT * FROM cliente ";
    }
}
else
{
    $COMANDO_SQL = "SELECT * FROM cliente WHERE '".$coluna."' LIKE '%'".$pesquisa."'%' ";
}

$link = mysqli_connect($servidor,$usuario,$senha,$banco);
$resultado_listagem = mysqli_query($link,$COMANDO_SQL);
?>

Php para a listagem:
<?php
        while( $linha = mysqli_fetch_assoc($resultado_listagem) )
        {
    ?>

                <?php echo $linha['CPF_CNPJ']; ?>
                <?php echo $linha['NOME_COMPLETO_RAZAO_SOCIAL']; ?>
                <?php echo $linha['NOME_FANTASIA']; ?>
                <?php echo $linha['TELEFONE'];     ?>
                <?php echo $linha['RUA']; ?>
                <?php echo $linha['BAIRRO']; ?>
                <?php echo $linha['CIDADE'];; ?>
                <?php echo $linha['ESTADO']; ?>

                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"
                        data-cpf="<?php echo $linha['CPF_CNPJ']; ?>"
                        data-nome="<?php echo $linha['NOME_COMPLETO_RAZAO_SOCIAL']; ?>"
                        data-nomefantasia="<?php echo $linha['NOME_FANTASIA']; ?>"
                        data-telefone="<?php echo $linha['TELEFONE']; ?>"
                        data-rua="<?php echo $linha['RUA']; ?>"
                        data-bairro="<?php echo $linha['BAIRRO']; ?>"
                        data-cidade="<?php echo $linha['CIDADE']; ?>"
                        data-estado="<?php echo $linha['ESTADO']; ?>" >
                        Editar
                    </button>

                <button type="button" class="btn btn-danger">Excluir

    <?php
        }
    ?>

Código do formulário HTML:

            <form action="listar_cliente.php" method="post">

                    <input type="text" class="form-control" name="pesquisa" id="pesquisa" placeholder="Pesquisar por..." >
                    <button class="btn " type="submit">

                    </button>

                <input type="radio" name="coluna" id="coluna" value="tudo" > Todos os dados
                <input type="radio" name="coluna" id="coluna" value="CPF_CNPJ" > CPF/CNPJ
                <input type="radio" name="coluna" id="coluna" value="NOME_COMPLETO_RAZAO_SOCIAL"> Nome
                <input type="radio" name="coluna" id="coluna" value="NOME_FANTASIA"> Nome Fantasia
                <input type="radio" name="coluna" id="coluna" value="TELEFONE"> Telefone
                <input type="radio" name="coluna" id="coluna" value="RUA"> Rua
                <input type="radio" name="coluna" id="coluna" value="BAIRRO"> Bairro
                <input type="radio" name="coluna" id="coluna" value="CIDADE"> Cidade
                <input type="radio" name="coluna" id="coluna" value="ESTADO"> Estado
            </form>

Comment: Qual erro ele te retorna? Cola a mensagem inteira.
Comment: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\CRUD\php\listar_cliente.php on line 178
Answer: Então pelo o que eu pude perceber você está fazendo de forma errada
tenta isso aqui. utilizo praticamente a mesma coisa em uma das minhas aplicações,
como o comando que você está passando para o banco já esta dentro do php não tem o porque concatenar basta você chamar a variável normalmente.
Utilize o seguinte comando 'sql':
$COMANDO_SQL = "SELECT * FROM cliente WHERE '$coluna' LIKE '%$pesquisa%' ";
Comment: Continua nem retornando o mesmo erro
" mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\CRUD\php\listar_cliente.php on line 178"
Answer: Primeiramente, as colunas não podem ficar entre aspas simples:
... WHERE '".$coluna."'

Segundo ao fazer isto:
LIKE '%'".$pesquisa."'%'

É provavel que esteja gerando algo como:
LIKE '%'exemplo'%'

Ou seja a pesquisa não esta dentro do LIKE, tem aspas a mais.
O correto provavelmente seria algo como:
"SELECT * FROM cliente WHERE ".$coluna." LIKE '%".$pesquisa."%'"

Agora o mais importante, faça sempre a checagem do mysqli_query, pode usar die, por exemplo:
else
{
    $COMANDO_SQL = "SELECT * FROM cliente WHERE ".$coluna." LIKE '%".$pesquisa."%'";
}

$link = mysqli_connect($servidor,$usuario,$senha,$banco);
$resultado_listagem = mysqli_query($link, $COMANDO_SQL) or die(mysqli_error($link));

Assim evita de entrar no while acaso ocorra alguma falha.
Comment: De fato, cometi um baita engano. Grato por tudo cara.
Comment: Os problema estava nas apas mesmo. Achei que a sintaxe estivesse correta, pois sempre usei essa forma ' ".$variavel." ' para concatenar variáveis em comando sql.
Comment: Tanto é que na função que uso para salvar os dados, o comando sql apresenta aspas simples na coluna

$COMANDO_SQL_CLIENTE = "INSERT INTO cliente (
        CPF_CNPJ,
        TELEFONE,
        NOME_COMPLETO_RAZAO_SOCIAL,
        NOME_FANTASIA,
        CIDADE,
        RUA,
        ESTADO,
        BAIRRO)
         values(
         '".$CPF_CNPJ."',
         '".$TELEFONE."',
         '".$NOME_COMPLETO_RAZAO_SOCIAL."',
         '".$NOME_FANTASIA."',
         '".$CIDADE."',
         '".$RUA."',
         '".$ESTADO."',
         '".$BAIRRO."')";
Comment: @Igor não, isso não são as colunas, são os "valores" das colunas, as colunas são a parte que esta sem aspas: `CPF_CNPJ, TELEFONE, NOME_COMPLETO_RAZAO_SOCIAL, NOME_FANTASIA, CIDADE, RUA, ESTADO, BAIRRO`. Resumindo: Valores usam aspas, colunas não usam ;)


Has the Lambeau Leap been banned at all NFL stadiums except Lambeau Field?

Question: The Lambeau Leap is a celebration started by Green Bay Packers players who leap into the stands after scoring a touchdown at Lambeau Field.  The celebration has spread across the NFL though, because I've seen players on other teams leap into the stands after scoring a touchdown at their home stadiums.
During the September 28, 2017 game between the Bears and Packers at Lambeau Field, Green Bay running back Aaron Jones scored a touchdown in the second quarter.  He celebrated by doing a Lambeau Leap.  Jim Nantz and Tony Romo commented on the Lambeau Leap during the CBS broadcast, and they said that the Lambeau Leap had been banned at every stadium except Lambeau Field, where it had been grandfathered in:

Nantz: First and goal at the 2.  Aaron Jones, he's in for the touchdown.  Running right behind Jahri Evans.  And there is your first career Lambeau Leap, Aaron Jones.
Romo: Just a normal handoff, and a really good jump cut right there by Jones getting in the end zone, and you see that right there, right behind Evans, and then he does the Lambeau Leap.  By the way, have you noticed Jim?  The Lambeau Leap?
Nantz: It's been outlawed everywhere...
Romo: No, no.
Nantz: ...but one place.
Romo: It's not outlawed here.
Nantz: It's grandfathered in here.
Romo: Grandfathered in, exactly.
Nantz: Everyplace but here.
Romo: It's like oh you know we like it, we're gonna keep it.
Nantz: You can't take that away.
Romo: No, it's too big a deal.

Is that true?  Has the Lambeau Leap been banned at every NFL stadium except Lambeau Field?  If so, when did that happen?
Answer: In the early 2000s, the NFL felt that touchdown celebrations had gotten out of control, delaying the game and promoting unsportsmanlike behavior.  Some of the top "offenders" included Steve Smith (who "diapered and wiped" the football), Randy Moss (who mooned Packers fans at Lambeau) and Chad Johnson (who put on a hall of fame jacket and proposed to a cheerleader).  So in 2006, the NFL outlawed "excessive celebration."  Specifically, players were prohibited from any prolonged, excessive, or premeditated celebration, from using any type of prop while celebrating, from going to the ground during a celebration, and from engaging in a group celebration.
However, they clarified that the Lambeau Leap would still be allowed, as long as it was one player only that jumped.*  Essentially, the Leap was grandfathered in as a celebration.  The goal post dunk was also grandfathered in at the time, but in 2014 that was banned as well.
The 2006 celebration ban was not popular with the players or fans.  And many players and fans were upset that the Packers were the only ones with a celebration that was still allowed, while their players were prohibited from celebrating.
This year (2017), the NFL has made a rule change again; this time, it has relaxed the excessive celebration rules.  Players are now once again allowed to use the football as a prop, to celebrate on the ground, and to engage in group demonstrations.  Offensive or prolonged celebrations, or demonstrations directed at an opponent, are still against the rules and will result in a penalty.
Before this year, it was debatable whether or not a Lambeau Leap-style celebration was within the rules at other stadiums.  Players have attempted it in other stadiums, and it is usually not flagged, as long as it follows all the other rules (no props, no groups).  With the new rule changes, a Lambeau Leap-style celebration should be allowed now in any stadium without question.

* Interesting side story: Several years ago I attended the annual "Packers Family Night" pre-pre-season scrimmage at Lambeau Field.  Although it was strictly a practice scrimmage, there were referees there, treating it as if it was a real game (for their own practice).  Early in the scrimmage, the offense scored, and the entire offense team did a Lambeau Leap.  The refs, of course, threw the flag for excessive celebration.
Comment: I would take [Alvin Kamara's TD celebration](https://www.youtube.com/watch?v=gM8GRoCpMBE) during the Saints' win against the Redskins in Week 11 as proof that the Lambeau Leap is legal in other stadiums.  Not only did he do a Lambeau Leap after his TD, but he went completely into the stands and was not penalized.


Find $1+\ln 2+\frac{1}{2} \ln^2 2+\frac{1}{6} \ln^3 2+\dotsb$

Question: I'm stuck in finding the following sum
$$1+\ln 2+\frac{1}{2}\,\ln^2 2+\frac{1}{6}\,\ln^3 2+\dotsb$$
Need some hint.
Comment: Substitute $x = \ln 2$. Does the series now look familiar?
Comment: Was just about to suggest that... :D
Answer: Hint: Substituting $x = \ln 2$ gives
$$
 1 + \frac{x}{1!}  + \frac{x^2}{2!}  + \frac{x^3}{3!} + \ldots
$$
which is a well-known series for an even more well-known function.


How to interpret p=0 in ncvTest?

Question: I have constructed a linear model (model3) and I'm trying to check the model's assumptions. As far the assumption of constant variance is concerned I have written the following piece of code
#constant variance
stud.residuals<-rstudent(model3)
yhat<-fitted(model3)
par(mfrow=c(1,2))
plot(yhat,stud.residuals)
abline(h=c(-2,2), col=2,lty=2)
plot(yhat,  stud.residuals^2)
abline(h=4,col=2, lty=2)
ncvTest(model3)
yhat.quantiles<-cut(yhat, breaks=quantile(yhat, prbs=seq(0,1,0.25)), dig.lab=6)
table(yhat.quantiles)
leveneTest(rstudent(model3)~yhat.quantiles)

The output of the above is:
> ncvTest(model3)
Non-constant Variance Score Test
Variance formula: ~ fitted.values
Chisquare = 2999.046    Df = 1     p = 0

> table(yhat.quantiles)
yhat.quantiles
(30917.2,128460]  (128460,167611]  (167611,216345]
             374              375              375
 (216345,607215]
             375

> leveneTest(rstudent(model3)~yhat.quantiles)
Levene's Test for Homogeneity of Variance (center = median)
        Df F value    Pr(>F)
group    3  52.424 < 2.2e-16 ***
      1493
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

I'm confused about how to interpret p=0 from ncvTest. At first I thought it would be a matter of representation  but ncvTest(model3)$p gives also zero.
Answer: pchisq(2999.046, 1, lower.tail = FALSE) gives numerically a 0. You can check pchisq(2999.046, 1, lower.tail = FALSE, log.p = TRUE) to see that the p-value is actually  $exp(-150.752) = 3.4e-66$, i.e., a very small probability. However, the exact value is not interesting at all. What this tells you is that there is extremely high significance which means that the zero-hypothesis of constant error variance must be rejected.
Levene's test agrees but formats the printed p-value using format.pval, i.e., shows it as smaller than a value roughly corresponding to precision of floating point numbers.
Finally, formal tests are nice, but it's usually recommended to focus on the diagnostic plots. And those show you heterogeneity and hint at systematic underestimation for lower fitted values and overestimation for the middle range.
Comment: Thank you very much but how did you concluded that there is " systematic overestimation for lower fitted values and underestimation for the middle range. "??
Comment: Sorry, I mixed that up. You can see it in the left plot.

How to interpret p=0 in ncvTest?


Classification of/Formulas for reinterpretation of harmony

Question: In a previous question, I asked about sources of harmonic ambiguity in tonal music. (Sources of harmonic ambiguity in tonal music)
While the question was closed as being too broad, I did receive an excellent answer in which the answerer claimed that "anything is uncertain if what follows will cause the ear to reinterpret it."
This of course begs the question: is there a classification of types of instances  or a list of chord-progressions or more abstract formulas where what was previously heard is reinterpreted as something else?
Comment: Could you add a link to the question you are referring to?
Comment: Link was added!
Comment: See also https://music.stackexchange.com/questions/47788/punning-chord and https://music.stackexchange.com/questions/64575/can-i-use-the-german-sixth-chord-to-modulate-to-another-key
Answer: If I understood what you are talking about, I think you are making more a big deal of it then it really is. I personally have never heard of such classifications nor formulas and I don't believe they exist.
As I see it, reinterpretation is a natural part of music and it probably happens more than we can even notice. Our brain tends to make assumptions about everything that we see or hear, based on patterns and previous experience, and this assumptions are often wrong and constantly changing.
For example, let's say you begin a song with the C chord. By playing this alone it sounds like a tonic, right? If then you play D7, you realize C was a subdominant, and the tonic is probably G (witch you hope is coming next). But if instead you play D#º, now you see C was VIb, D was VIIb, and Em will probably be the tonic. I could go on forever with this example and by each new chord you would reinterpret every previous chord.
As an exercise, you could take any song you like and pause it on every chord. Think over it, think what it sounds like, think what you hope is coming next. I bet you will find yourself reinterpreting things several times.
Answer: If by ambiguity you mean that chords are perceived differently in context, an example of a specific formula might simply be cadence. Especially when chord progressions mixes different cadences to screw with our expected perception of a chord. The concept of cadence describes why chords in any progression are perceived as having different characteristics.


Qt SQL - ERROR (42601): syntax error at or near

Question: Atualmente estou desenvolvendo um programa para auxiliar no gerenciamento de um quartel em minha cidade, estou utilizando Qt para criar a interface gráfica e outras bibliotecas necessárias como as de manipulação de bancos de dados, para o servidor estou utilizando o postgres, ao tentar criar uma tabela eu recebo o seguinte erro:
Falha ao criar a tabela va_atiradores:  QSqlError("42601", "QPSQL: Unable to create query", "ERROR:  syntax error at or near \"(\"\nLINE 4: cpf integer(11) NOT NULL UNIQUE,\n                   ^\n(42601)")

Além disso ao encerrar o programa a runtime do visual studio me acusa um erro de corrupção da heap:

Eis o trecho do código responsável por criar a tabela:
bool Atirador::insert(QStringList &data)
{

    QSqlDatabase db = QSqlDatabase::database();

    const QString sqlTable = "CREATE TABLE IF NOT EXISTS sch_tg.va_atiradores(\n"
                       "id SERIAL PRIMARY KEY,\n"
                       "nome varchar(1000) NOT NULL UNIQUE,\n"
                       "cpf integer(11) NOT NULL UNIQUE,\n"
                       "rg integer(20) NOT NULL UNIQUE,\n"
                       "ra integer(30) UNIQUE,\n"
                       "nPai varchar(1000) NOT NULL UNIQUE,\n"
                       "nMae varchar(1000) NOT NULL UNIQUE,\n"
                       "dataNasc date NOT NULL,\n"
                       "estdCvl integer NOT NULL,\n"
                       "cidade varchar(250) NOT NULL,\n"
                       "cep integer(10) NOT NULL,\n"
                       "estado varchar(250) NOT NULL,\n"
                       "uf varchar(2) NOT NULL,\n"
                       "rua varchar(500) NOT NULL,\n"
                       "nCasa integer,\n"
                       "bairro varchar(500) NOT NULL,\n"
                       "cel integer(30) UNIQUE,\n"
                       "tel integer(30) UNIQUE,\n"
                       "tipoAtr integer NOT NULL,\n"
                       "status integer NOT NULL,\n"
                       "cadPor varchar(250) NOT NULL,\n"
                       "ultServ date,\n"
                       "pontos integer,\n"
                       "servicos integer)\0";

    QSqlQuery createTableQuery(db);

    if(!createTableQuery.exec(sqlTable)){

        qCritical() << "Falha ao criar a tabela va_atiradores: " << createTableQuery.lastError();

        createTableQuery.finish();

        return true;
    }

    createTableQuery.finish();

    db.close();

    return true;
}

Em primeiro momento pensei ser algum erro de algum caractere não escapado, mas ao testar o código sql na ferramenta de query do pgAdmin 4 eu recebo o mesmo erro:
ERROR:  syntax error at or near "("
LINE 4:                        cpf integer(11) NOT NULL UNIQUE,
                                          ^
SQL state: 42601
Character: 189

Comment: Não seria melhor utilizar um `StringBuilder` para construir a _query_ e utilizar o `AppendLine()` para dar _line feeds_?
Answer: A mensagem de erro apresenta erro de sintaxe na montagem da query na linha cpf integer(11) NOT NULL UNIQUE; você está querendo um inteiro mas está definindo um tamanho para ele, o que não é necessário.
const QString sqlTable = "CREATE TABLE IF NOT EXISTS sch_tg.va_atiradores(\n"
                   "id SERIAL PRIMARY KEY,\n"
                   "nome varchar(1000) NOT NULL UNIQUE,\n"
                   "cpf integer NOT NULL UNIQUE,\n"
                   "rg integer NOT NULL UNIQUE,\n"
                   "ra integer UNIQUE,\n"
                   "nPai varchar(1000) NOT NULL UNIQUE,\n"
                   "nMae varchar(1000) NOT NULL UNIQUE,\n"
                   "dataNasc date NOT NULL,\n"
                   "estdCvl integer NOT NULL,\n"
                   "cidade varchar(250) NOT NULL,\n"
                   "cep integer NOT NULL,\n"
                   "estado varchar(250) NOT NULL,\n"
                   "uf varchar(2) NOT NULL,\n"
                   "rua varchar(500) NOT NULL,\n"
                   "nCasa integer,\n"
                   "bairro varchar(500) NOT NULL,\n"
                   "cel integer UNIQUE,\n"
                   "tel integer UNIQUE,\n"
                   "tipoAtr integer NOT NULL,\n"
                   "status integer NOT NULL,\n"
                   "cadPor varchar(250) NOT NULL,\n"
                   "ultServ date,\n"
                   "pontos integer,\n"
                   "servicos integer)\0";

Removi essas definições, agora não deve ter mais problemas


Gravar nomes de arquivos do input em xml

Question: Gostaria de gravar arquivos de um input em um documento xml
<code>    public function do_upload()
    {

    $this->load->library('upload');

    $len = count($_FILES['files']['name']);

    $nomes = array();

    for($i = 0; $i < $len; $i++) {
        $fileSize = $_FILES['files']['name'][$i];
        $string = str_replace(' ', '-', $fileSize);
        $nomes[] = convert_accented_characters($string);
    }

    $this->load->library('xml_writer');

    // Initiate class
    $xml = new Xml_writer();
    $xml->setRootName('playlist');
    $xml->initiate();

    // Start branch 'track'
    $xml->startBranch('track');

    $xml->addNode('title', 'exemple 1'); //Queria fazer um loop aqui para o valor exemple 1, ser o nome dos arquivos

    $xml->endBranch();

    // End branch 'track'
    $xml->endBranch();

    $data = array();
    $data['xml'] = $xml->getXml(FALSE);
    $this->load->view('xml', $data);

    $this->upload->initialize(array(
        "file_name"     => $nomes,
        "upload_path"   => "./uploads/",
        "allowed_types" => "mp3",
        "max_size"  => "30000"
    ));

}
</code>
Estou usando a class https://github.com/bcit-ci/CodeIgniter/wiki/Xml-Library
Answer: Conseguir resolver
<code>foreach ($nomes as $value) {
        // Start branch 'track'
        $xml->startBranch('track');
        $xml->addNode('title', $value);
        // End branch 'bikes'
        $xml->endBranch();
    }
</code>


Cross-browser dropshadows on boxes

Question: I am building a new site which has drop shadows on various page elements (boxes, inputs etc). The site as a whole needs to be the same across all browsers (back to IE7).
My issue lies with the best way to implement these drop shadows on many different elements on new and old browsers.

I am aware of the css3 solution with no images: box-shadow: 1px 1px #333 - but this won't degrade well.
I don't really want to use images for every element as we would be looking at 4 images per element and requests to the server and page load time would get ridiculous just for a simple effect.
Is it possible to even create a fallback say: If the browser doesn't support box-shadow, use images? Only issue I see with this is lots of extra mark up which can make it harder to manage.
I guess the difficulty here is the requirement "I want it modern but to degrade nicely".
What solution is best for me when implementing drop shadows (is there an alternative) ?
Answer: You can use http://modernizr.com to detect if the current user using browser with css3 support but I think you better use the old way to make a box with drop shadow.
You can make it with the "Sliding doors" technique for the top and bottom of the box and use another background image for the box itself.
Anyway you can use CSS3 pie ( http://css3pie.com/) but I usually don't like this plugin because it's a little buggy sometimes and raise the browser performance needed.
Comment: css3pie looks good, I didn't realise there was a `.htc` file for this. Does it *"raise the browser performance needed."* for all browsers or just IE?
Comment: I read on their documentation: `the .htc file loads asynchronously.` and `the .htc behavior applies itself while the page is still loading.`. This sounds great, but do you know if it makes a noticeable difference?
Answer: You can try to use css
filter: progid:DXImageTransform.Microsoft.Shadow(...);

but this shadows are terrible. I think the best solution is to show shadows only in modern browsers, which allow box-shadow.
Comment: Yes, I agree. I just don't know much about the alternative solutions for box-shadows except the old school stuff. I want to be able to say *other implementations are terrible* with the knowledge they are instead of just assuming.
Comment: I agree, I'd love to say "for any old browser, dont worry about the drop shadow". Unfortunately I need some ammunition as to why, and to understand all my options instead of saying "just because".
Comment: Unfortunately I am a developer, the requirement comes from a client and I cannot simply send them that link (as much as I would love to). The response I expect from them in regards to that link is "**Why?**
Comment: Fortunately, as a developer, you have the knowledge and expertise that your clients want (and are, presumably, paying for). This includes the ability to say things like "Old browsers won't render fancy cool effects like drop shadows. It's going to *look better* if we don't use their terrible implementation."
Answer: Hey you can check it with Javascript
var supports = (function() {
   var div = document.createElement('div'),
      vendors = 'Khtml Ms O Moz Webkit'.split(' '),
      len = vendors.length;
   return function(prop) {
      if ( prop in div.style ) return true;
      prop = prop.replace(/^[a-z]/, function(val) {
         return val.toUpperCase();
      });
      while(len--) {
         if ( vendors[len] + prop in div.style ) {
            // browser supports box-shadow. Do what you need.
            // Or use a bang (!) to test if the browser doesn't.
            return true;
         }
      }
      return false;
   };
})();
if ( supports('textShadow') ) {
   document.documentElement.className += ' textShadow';
}

And then put in the else statement that you want to use images or You can use an library called Modernizer http://www.modernizr.com/ so older browser know how they have to implement css3 tags
Link to source for the code: SOURCECODE
Comment: +1 for modernizr. I have looked at it briefly before. Definitely a solution if I was worried about more cross-browser issues other than just box-shadows. That code you posted is useful too, but what alternative would you recommend?
Comment: You can use images or you can use the code from ManseUk like this `.shadow {

 -moz-box-shadow: 3px 3px 4px #000;

 -webkit-box-shadow: 3px 3px 4px #000;

 box-shadow: 3px 3px 4px #000;

 /* For IE 8 */

 -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";

 /* For IE 5.5 - 7 */

 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');
}`
Answer: You can use the following for older versions of IE :
/* For IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
/* For IE 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');

MSDN Details here and Example here

Cross-browser dropshadows on boxes


Isolating $x$ from $y = (x-1)^2$

Question: (Yeah I deleted an earlier question about this, I had everything wrong in it)
I'm trying to find the value of $x$
$$y = (x-1)^2$$
Can I
$$\sqrt{y} = (x-1)$$
?
Comment: There is no "the value of x": the first equation above gives you a parabola pointing upwards with the vertex at $(1,0)$, so there are infinitely many solution pairs.
Comment: @Lost: It seems reasonable to assume that $y$ is given.
Comment: @HenningMakholm Possibly, just wanted to make sure that was clear.
Comment: Don't delete the question, just correct it. This is identical to the other one, no need for that.
Answer: Almost. When you take the square root of $(x-1)^2$ you get $|x-1|$, not $x-1$ itself. So now you have to solve
$$ \sqrt y = |x-1| $$
There will be solutions corresponding to $x-1$ being either positive or negative.
Comment: Thanks, I ask because if I have $\int_{0}^{1}(-5y+1)$, I would have to do it twice (one in which $y$ is positive and another when it is negative), right?
Comment: Omega: Do you mean $\int_0^1 (-5y+1)\,dy$? In the case $y$ is explicitly never negative.
Comment: Not to be overly pedantic, but this assumes we're talking about real variables here. Of course, this is probably the case, so you're right.
Comment: @HenningMakholm: If I had $\int_{0}^{1}(x)dy$, I would need to isolate the $x$ from my $y = (x-1)^2$ - if I did that, $x$ could be either $-\sqrt{y}+1$ or $\sqrt{y}+1$ and I'd have to do both cases?
Comment: @Omega: $\int_0^1 x\,dy$ is just $x$, no squares involved. I don't see what that integral has to do with your question.

Isolating $x$ from $y = (x-1)^2$


same number of observations but not significant?

Question: If we two time series (x,y)with the same number of observations.
We then computed the Pearson correlation with z, which has the same number of observations as x and y (corr between x and z ,corr between y and z)
   Is it possible to encounter this case:
    - there is a significant (p<0.05)correlation between x and z
     - there is NO significant (p<0.05)correlation between y and z

even if they the have same number of observations!
Comment: Yes, of course it is possible, what is the reason for the surprise? Take x=z and random y, for example. The equal number of observations doesn't mean much.
Answer: Answered in comments:
Yes, of course it is possible, what is the reason for the surprise? Take $x=z$ and random $y$, for example.  The equal number of observations doesn't mean much. – psarka


Extract the last word from a string using C#

Question: My string is like this:
string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";

Here actually I want to extract the last word, 'API', and return.
What would be the C# code to do the above extraction?
Comment: Is "STRIP" a word, or is the first word "STRIP," ?
Comment: What's your pattern? Last 3 letters? last thing appeared after +? last thing appear after last operator?
Answer: Well, the naive implementation to that would be to simply split on each space and take the last element.
Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator.
End result:
string lastWord = input.Split(' ').Last();

If you don't have LINQ, I would do it in two operations:
string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];

While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.
string input = ".... ,API";

Here, the comma would be part of the "word".
Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules:

Will always contain at least one space
Does not end with one or more spaces (in case of this you can trim it)

Then you can use this code that will allocate fewer objects on the heap for GC to worry about later:
string lastWord = input.Substring(input.LastIndexOf(' ') + 1);

However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.
Comment: @Shimmy `.LastIndexOf` doesn't return "last index of entire string" (which would actually be `0`) if it cannot find the string match, it returns `-1` which of course then becomes `0` when adding `1` which happens to give you the whole string in this instance.
Comment: The `Substring(input.LastIndexOf(' ') + 1)` is surely best choice for performance, why would anyone on earth split an entire string to get the last word???
And BTW, **you're wrong** about missing chars; the substring will return last index of ' ' or last index of entire string, which means same result. Check it out yourself: http://rextester.com/IFEGJ69776
Comment: Check this link, I'm testing an empty string and it gives the same result. [Check it out](http://rextester.com/CXJYN16822).
Answer: First:
using System.Linq; // System.Core.dll

then
string last = input.Split(' ').LastOrDefault();

// or

string last = input.Trim().Split(' ').LastOrDefault();

// or

string last = input.Trim().Split(' ').LastOrDefault().Trim();

Comment: @Pradeep: Use the namespace System.Linq
Comment: @Pradeep: Verify that System.Core assembly is present in the project references.
Comment: what if after the last word if it is having some space like "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API       ";
Comment: I am unable to use Last(), it is saying system.array does not contain definition for Last. My class is implementing an interface, i think that is the reason i cannot use last(), so please tell me how to use it
Comment: Last() is an extension (LINQ) method, you need .NET 3.5 or higher.
Comment: If i try to use System.Linq in my class file it is saying namespace name Linq does not exists in namespace system.
Comment: I think I cannot use Linq because, i am using vs 2008 IDE and my application runs on .net framework 2.0. Please tell me is there any alternatives to this.
Comment: can't we use Linq in class library
Comment: If you do not want to use Linq, then you need to modify @Taz's code a bit as suggested by @Lasse V. Karlsen
Answer: var last = input.Substring(input.LastIndexOf(' ')).TrimStart();
This method doesn't allocate an entire array of strings as the others do.
Comment: Do you need to +1 to LastIndexOf()? Or have I done my answer wrong? :)
Comment: @El Ronnoco Yeah, You do, but your answer will fail if the string ends in a space. (index beyond end of string = exception). TrimStart is safer. :)
Answer: string workingInput = input.Trim();
string last = workingInput.Substring(workingInput.LastIndexOf(' ')).Trim();

Although this may fail if you have no spaces in the string. I think splitting is unnecessarily intensive just for one word :)
Answer: static class Extensions
{
    private static readonly char[] DefaultDelimeters = new char[]{' ', '.'};

    public string LastWord(this string StringValue)
    {
        return LastWord(StringValue, DefaultDelimeters);
    }

    public string LastWord(this string StringValue, char[] Delimeters)
    {
        int index = StringValue.LastIndexOfAny(Delimeters);

        if(index>-1)
            return StringValue.Substring(index);
        else
            return null;
    }
}

class Application
{
    public void DoWork()
    {
        string sentence = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
        string lastWord = sentence.LastWord();
    }
}

Comment: Default behavior should be to return StringValue is index == -1. Also, you should return StringValue.Substring(index + 1).
Answer: var lastWord = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Last();

Answer: string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
var a = input.Split(' ');
Console.WriteLine(a[a.Length-1]);


Can my Class Factory use less code with Unity?

Question: I have put this kind of pattern in my code for instantiating business objects:
// UI or Business level code
public class SomeClass
{
    IOrderFactory orderFactory;

    public SomeClass(IOrderFactory orderFactory)
    {
        this.orderFactory = orderFactory
    }

    public void SomeMethod()
    {
        var newOrder = orderFactory.CreateOrder();
        // Do stuff with new object
    }
}

// In an interfaces only project
public interface IOrderFactory
{
    Order CreateOrder();
}

// In an implementation project (not seen by most other modules)
public class OrderFactory
{
    public Order CreateOrder()
    {
        return new Order();
    }
}

We currently use Unity to create the IOrderFactory object, but i am wondering if Unity (IOC) can be used to to generate the Order object itself.
Something like unityContainer.Resolve<IOrder>() and have it make a new one each time?
Would that work?  We use unity for our services and functional (ie ViewModels, Helpers) classes.  But we have never used it to to create business objects (like Customer or Order.)
Comment: You should typically not resolve business objects from your container, and it is even questionable whether you would even need a factory for this. Here's a related question: http://stackoverflow.com/questions/4835046/why-not-use-an-ioc-container-to-resolve-dependencies-for-entities-business-objec
Answer: In my opinion, this all depends on how complex it is to build an instance of a given object (ie. WizBang), and how often it will change.
If the implementation of IWizBang will always be WizBang, or if creating a WizBang instance just involves calling the default constructor, then introducing an IOC container is overkill ... you can easily make a factory method to generate the method for you. Developers often forget that configuration complexity can burden developers who are new to a project, or even developers who don't often have to add a new entity which needs to be configured.
Comment: Good point.  (Note: I changed my example from WizBang to Order to show that this was a domain object.)
Answer: New answer
Indeed, you'll reduce builerplate code. Domain classes are no different from any other class. Instead of having a factory class you could register the mapping from the interface to the concrete type and provide ctor parameters if needed. See http://msdn.microsoft.com/en-us/library/ff648211.aspx
Old answer
Resolving an object through any container will always be slower than invoking a virtual method and invoking a constructor. It is not in raw performance where you'll get a benefit from a DI container.
Comment: Sorry, by efficient, I meant use less code.  I have changed my title to reflect that.
Answer: I would keep the IOrderFactory. DI containers are fabulous at giving you services, but when you need an entity (something where the specific object identity is important) using the container often gets problematic.
There are a couple reasons I would do this:

Creating entities tends to require the data for that entity (order
ids, line items, etc), which are different for each time you create
it. This gets difficult and awkward to do with the container.
In order to do this will require that you give the container instance to your business logic. You really don't want your code depending directly on the container except at the composition root. In my experience, seeing lots of IUnityContainer dependencies is a warning sign.

However, you can take advantage of the container - keep the IOrderFactory as a dependency, and then inject the factory into the container. You can then inject whatever services needed to create an order into the factory itself to hold onto. You could also inject the container into the factory.
Another option, if it really is the case that you can create an order with no special parameter values beyond what you've configured, would be to inject a Func - a factory function. This will be generated by the container at runtime and will call back into container.Resolve when invoked. Perhaps you can start there and build up the IOrderFactory if you find you need more parameters or control?


Pyomo CBC solver error: Solver (cbc) returned non-zero return code (3221225781); Solver (cbc) did not exit normally

Question: I'm working on an optimization problem on PyCharm using the CBC solver and I keep having this error:
ERROR: Solver (cbc) returned non-zero return code (3221225781)
and
pyutilib.common._exceptions.ApplicationError: Solver (cbc) did not exit normally
I've added the "keepfiles=True" argument but I can't finde the solver log and solution file, although I can finde the problem files on the path the program returns.
It is worth nothing that this program runs properly on my colleague's computer, (he has 16Gb RAM and I have 8)
Comment: Try adding the option `tee=True`, this will print the solver output to the screen
Comment: I've already done that, still doesn't work:

opt.solve(model, tee=True, keepfiles=True)
Answer: I've found a solution by myself and I'll post it here in case is usefull for anyone in the future:
When installing a solver, you must add the solver.exe file into the system PATH or just place the file in the folder where the python file is placed
Answer: I was facing the same problem with the ipopt solver.
It was solved by adding the solver to the system PATH, but it only worked after restarting the computer!
Answer: in addition to @Camunatas's solution (if that doesn't work) do add all the DLLs and exe's which are the package of COIN OR(blis,bonmin,cbc,clp,couenne,ipopt,OSSolverService,symphony) package in the same directory/folder where the python files are.as these exes are the only installers for windows and they should always be with their DLLs to work.


From docker containers to Google Kubernetes

Question: This one is a little theoretical but please bear with me.
Currently I have a server running a few Docker containers (4 or 5, depending on day and time). I plan to add another one, just like the first, and maybe even a third one.
Now, my question is this: Should the time come that I have 15 containers to manage, instead of 5, is there any merit in using Google Kubernetes?
Also, is there an 'official', or at least 'definitive', workflow to migrate from Docker containers to 'pods', the native unit of Kubernetes. Before you ask, I do know that pods are made of containers (some times even one). My primary issue here is that 'dockerfiles' are completely different from pod configs.
Any ideas?
Answer:
Should the time come that I have 15 containers to manage, instead of 5, is there any merit in using Google Kubernetes?

If you run containers on a single server using the Docker daemon and its Remote API sounds appropriate.
If you need to run containers on more than one server, that's where orchestration solutions like Kubernetes, Docker swarm, Fleet, Mesos, Geard becomes useful.

My primary issue here is that 'dockerfiles' are completely different from pod configs.

Because they have different purposes:

Dockerfile specifies how to build a container image from a tree of sources
pod.yaml defines how to schedule (image, command line, volumes, port) a set of co-located containers (sharing network namespace, and volumes) on one of the node of your cluster.

You can see pods as a way to declarative specify a set of docker run --net=container:... -v ... -p ... commands.

Also, is there an 'official', or at least 'definitive', workflow to migrate from Docker containers to 'pods', the native unit of Kubernetes.

There is a small tool in kubernetes/contrib called podex that allow you to generate a pod manifest from image metadata stored in the public registry.
$ go get github.com/GoogleCloudPlatform/kubernetes/contrib/podex
$ podex google/nodejs-hello
id: nodejs-hello
kind: Pod
apiVersion: v1beta1
desiredState:
  manifest:
    version: v1beta2
    containers:
    - name: nodejs-hello
      image: google/nodejs-hello
      ports:
      - name: nodejs-hello-tcp-8080
        containerPort: 8080

Answer: @proppy's answer is correct: One is only working for single server.
I had the same initial reaction, however you can actually have multiple Services and Pods in a single file (separated by ---). This way you still have 1 service + 1 pod per container in general, but that's not too bad.
You also have to name a bunch of things more than in docker-compose (sometimes I feel it's more than necessary). Once you passed learning which name matter where, you'll be fine and maintenance of the files won't be much harder.
Deployment is a lot heavier IMO but again it's distributed, and also a Deployment Pod type is coming which should simplify upgrades (currently as beta extension in v1.1).