How to see what the standard simplices of a topological space are?

Question: I am studying algebraic topology from Allen Hatcher´s book.
I understand the theory, but have trouble computing simplicial homology for spaces.
The problem for me is to see how the standard simplices look, based on a picture of the given space.
Definitions: A simplex $\Delta_n$ is defined (in Hatcher´s book) as the join of $n$ points is a convex polyhedron of dimension n − 1.
$\Delta_n(X)$ is then defined as the free abelian group with basis the open $n$-simplices $e^n_\alpha$ of $X$ . Elements of $\Delta_n(X)$ are called n-chains and can be written as finite formal sums $\sum_\alpha n_\alpha e^n_\alpha$ with coefficients $n_\alpha \in \mathbb{Z}$.
For example, calculating simplicial homology of $S^1$, we need to describe $\Delta_0(S^1)$ and $\Delta_1(S^1)$. As far as I understand, $\Delta_0(S^1)$ should be a discrete set of 0-cells (points) and $\Delta_1(S^1)$ should be a set of lines. But I don´t see how they are equal to $\mathbb{Z}$?
This is the example in Hatcher´s book I am referring to:
Comment: Do you understand the formal definition of $\Delta_i(X)$? "Set of points" or "set of lines" is not what the definition says.
Comment: $\Delta_0(X)$ is the free abelian group with basis the open $0$-simplices. In the example, there is one $0$-simplex, $v$, and so $\Delta_0(X)$ is free abelian of rank 1 generated by $v$, hence is isomorphic to $\mathbb{Z}$.
Comment: I mean, do you know the definition of the group of simplicial $i$-chains of the given simplicial complex? You defined a single simplex, not a group.
Comment: @MoisheKohan Added the definition
Comment: @MoisheKohan Yes, added also that definition (if thats what you mean)
Answer: Hatcher is a bit misleading in the chapter 2.1. What he considers are not "raw" simplices. In fact the circle $S^1$ contains no "raw" simplices of dimension above $0$ (e.g. no straight line is a subset of a circle). Instead he considers a $\Delta$-complex structure on $X$ (which is defined at the begining of the chapter), that is a collection of maps $\Delta^n\to X$ which satisfies certain properties. This can be seen when he says:

Example 2.2. $X=S^1$ with one vertex $v$ and one edge $e$.

He means one $0$-dimensional simplex $\Delta^0\to S^1$ and one $1$-dimensional simplex $\Delta^1\to S^1$ (the latter is a glueing of its endpoints). Both together form a $\Delta$-complex on $S^1$. Of course this depends on the choice of those maps, so these are fixed implicitly. Also Hatcher will use the word "simplex" or "vertex" or "edge" for such maps, and sometimes even for images of those maps as well. Yeah, it can be confusing.
He then builds $\Delta_n(X)$ chain complexes. Those complexes can be built on top of the $\Delta$-structure. Hatcher describes how it is done in the chapter as well.

$\Delta_0(S^1)$ should be a discrete set of 0-cells (points) and $\Delta_1(S^1)$ should be a set of lines

No. $\Delta_0(S^1)$ is a free group generated by all $0$-simplexes. But not all $0$-simplexes taken from thin air. All $0$-simplexes taken from a fixed $\Delta$-complex structure. In our case this is the single $\Delta^0\to S^1$ map. Hence it is $\mathbb{Z}$. Analogously $\Delta_1(S^1)$ is a free group generated by all $1$-simplexes. In our case this is the single $\Delta^1\to S^1$ map. Thus again $\mathbb{Z}$.
Comment: Typo in sentence 3: "no simplices of dimension above 0" should instead say "above 1".
Comment: @JohnPalmieri that's not a typo. I've updated the answer.
Comment: @freakish Thank you! I think my confusion comes from a lot of different uses of words "simplex", "complex" etc. in Hatcher. So $\Delta_0(S^1)$ is $\mathbb{Z}$, because it is generated by a point? And similarly $\Delta_1(S^1)$ is $\mathbb{Z}$ because it is "genreated" by a line circulating around again and again? (The circle)


Laravel app()->getLocale() inside routes always print the default "en"

Question: I encountred a problem when trying to prefixing my routes with new set locale.
When I return app()->getLocale() from a controller or a route closure it returns new set locale correctly, but when I put it inside Route prefix I get the default one 'en'. In my case the new locale is 'ar'.
This is my code inside web.php
<?php

//Request to put the choosen locale into the session
Route::get('locale/{locale}', function($locale) {

    session()->put('userLocale', $locale);
    return redirect(app()->getLocale());
});

//Group of routes that are supposed to be prefixed with new set locale 'ar'
Route::group(['prefix' => app()->getLocale(), 'middleware' => 'locale'], function() {

    Route::get('/', function() {
        return app()->getLocale();
    });
});

And this is the middleware:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

class Locale
{
    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->app->setLocale(session('userLocale'));
        return $next($request);
    }
}

Note the statement "app()->getLocale()" inside Route prefix, this statement's value always is "en". But when I return it from within the closure it prints the new set locale "ar".
What I'm trying to say is that, inside prefix, app()->getLocale()'s value is always "en", but inside the Closure its value is "ar".
So when I run "localehost:8000/locale/ar" in the browser the output is "ar" and that is correct but the url becomes "localehost:8000/en" and that should be "localehost:8000/ar" isn'it ? When I run "localehost:8000/ar" in the browser I get a 404 page.
I tried to set the prefix from within RouteServiceProvider's mapWebRoutes methode but It doesn't work because I think that the service provider is executed before the middlware so It can't recognize the new locale that is set by the middlware.
I hope to get help or another approach to prefix the routes with new locale because maybe I'm doing somthing wrong.
Answer: Your locale is not going to be set from the session until your middleware runs.  Your routes would have to be defined before the middleware runs, otherwise, the system would have no idea which middleware are supposed to be run on which routes.
Since app()->locale() is going to return 'en' before your middleware runs, all your code is doing is defining a prefix of 'en'.
It seems maybe you want to define a variable for the locale, in that case, you would do something like:
Route::group(['prefix' => '{locale}', 'middleware' => 'locale'], function() {
   ...
});

Or you could use a package that handles localized urls for you like https://github.com/mcamara/laravel-localization
Comment: Thank you. I'll give it a try
Comment: What can I do to get routes defined before middleware runs ?
Answer: Make a middleware named SetLocale like below and also register it in kernel.php file:
public function handle($request, Closure $next)
{
    $desiredLocale=$request->segment(1);
    in_array($desiredLocale, ["en", "ar"]) ? app()->setLocale($desiredLocale) : app()->setLocale('en');

    return $next($request);
}

In kernel.php add in $routeMiddleware array like this:
'local.set'=>\App\Http\Middleware\SetLocale::class,

Now, you can apply it on all the routes like this:
Route::group(['prefix' => '{locale}','middleware' => 'local.set'], function () {
......
});


Relógio em Action Script

Question: Criei um relógio em Action Script para usar como conteúdo para Digital Signage com o horário de 6 países, mas estou com um problema com o horário de verão.
Usei o getHours para pegar os horários e apliquei a diferença do fuso com matemática simples, mas o gethours pega o horário do sistema.
Como posso fazer para pegar um horário online ou de cada pais separado ou pelo menos um horário sem fuso nenhum e trabalhar melhor o horário de verão ? Tem algum lugar onde eu possa pegar horário online ou até mesmo criar algo no meu servidor para fazer isso ?
Comment: Este site pode te ajudar: http://www.horacerta.com.br/, possui o horário de diversos países, talvez possa utilizar como fonte.
Answer: Se o seu Flash estiver em um sistema com conexão a internet você pode consumir esta API -> http://timezonedb.com/api ela permite você obter o tempo de qualquer lugar do mundo (esteja normal ou em horário de verão) além de escolher o formato de resposta (entre XML ou JSON).
Estou considerando que você tem internet baseado na forma como você deve distribuir conteúdo para o digital signage.
Caso não tenha ai seria o caso de pedir via rede ou de configurar de acordo com o relógio da maquina em um arquivo externo.
Comment: Putz era exatamente isso que eu precisava, eu estava fazendo com o relógio da maquina. Obrigado.

Relógio em Action Script


Let $T:\mathcal{P}(\mathbb{R})\to \mathcal{P}(\mathbb{R})$ such that $T(p)=p-p'$. Find all eigen values and eigen vectors of $T$.

Question: Let $T:\mathcal{P}(\mathbb{R})\to \mathcal{P}(\mathbb{R})$ such that $T(p)=p-p'$. Find all eigen values and eigen vectors of $T$.
Please someone help me with this problem. Thank you
Comment: Forgive me if this is a dumb question, but what is $\mathcal{P}(\mathbb{R})$? Is it the set of polynomials in one variable with real coefficients?
Comment: what have you got so far?
Comment: Your question was put on hold, the message above (and possibly comments) should give an explanation why. (In particular, [this link](http://meta.math.stackexchange.com/a/9960) might be useful.) You might try to edit your question to address these issues. Note that the next edit puts your post in the review queue, where users can vote to reopen this. (Therefore it would be good to avoid minor edits and improve your question as much as possible with the next edit.)
Answer: I will assume $\mathcal{P}(\mathbb{R})$ is the set $\mathbb{R}[x]$ of polynomials with real coefficients. Then if $p$ is an eigenvector of $T$, we have $T p = p - p' = \lambda p$. By comparing the leading coefficients, we have that $\lambda =1$, so that $p'=0$, and $p=c$ for some constant $c$. Thus there is only one eigenvalue, $\lambda=1$, with corresponding eigenspace $\langle 1 \rangle$.
Comment: What about $p=\alpha p'$?
Comment: @celtschk by comparing degrees, that is impossible unless $p=0$, in which case it is not an eigenvector.
Comment: I don't see anything stating a specific degree of $p'$.
Comment: @celtschk We are working over the reals which is characteristic 0, since $p$ is nonzero, if $p$ has degree $n$, then $p'$ has degree $n-1$, and hence $p$ cannot be a scalar multiple of $p'$.
Comment: Ah, I understand, you interpret "$p'$" as "derivative of $p$". I interpreted it as some constant value independent of $p$ that is also a polynomial. Which shows how important it is to properly specify the problem. :-)
Comment: @celtschk Indeed, that hadn't occurred to me, I see. Yes, that would certainly change things. :)
Comment: The notation $p'$ is pretty standard.


A Fibonacci identity and $f(Av)=\det(A)f(v)$

Question: Given a diagonalizable linear transformation $A:V\to V$ over an algebraically closed field $k$, and an eigenbasis $v_1,\ldots v_n$ with $Av_i=\lambda_i v_i$, consider the following procedure to define a function $f_A$.
Given a vector $v\in V$, express it as as $v=\sum a_i v_i$.  Let $f_A(v)=\prod a_i$.  This satisfies the nice property that $f_A(Av)=\det(A)f_A(v)$.
I came across this construction when trying to find invariants for generalized Fibonacci sequences.  In particular, define $G_0=a, G_1=b, G_{n+1}=G_n+G_{n-1}$ for $n>1$.  Applying this construction to the equation
$$ \pmatrix{1 & 1\\ 1 & 0}^n\pmatrix{b \\ a} =\pmatrix{G_n \\ G_{n-1}}$$
yields that $G_{n}G_{n+2}-G_{n+1}^2=(-1)^n(G_0G_2-G_1^2)=(-1)^n(a(a+b)-b^2)$.  In particular, $|G_{n}G_{n+2}-G_{n+1}^2|$ is independent of $n$, so if one wanted to determine whether $(c,d)=(G_n,G_{n+1})$ for some $n$, then a necessary condition is that $c(c+d)-d^2=(-1)^n(a(a+b)-b^2)$.
This identity is similar to but more general than the classical identity $F_{n-1}F_{n+1}-F_n^2=(-1)^n$
My question: Has this construction been studied before? Is there a cleaner approach to it?  Does it generalize?  Are there other, better ways to generate functions that satisfy $f(Av)=\det(A)f(v)$?

Update: The construction can be rephrased (up to a constant) as $\det(M(v))$ where $M(v)$ is the matrix whose columns are the $A$-eignevectors which sum to $v$.  The property $f(Av)=\det(A)f(v)$ comes from the property that $M(Av)=AM(v)$.  Therefore, this question could be answered by a classification of the maps $V\to \hom(V,V)$ which commute with $A$. I feel like this kind of tensor construction has a better chance of having been studied.
Comment: Sorry, I was confused. Can you write down the definition of the sequence $G_n$, and in particular where the constant $C$ occurs in it?
Comment: @QiaochuYuan Ok, I have clarified the discussion of the $G_n$.
Comment: If the eigenvalues are $2$ and $4$, then $f(v) = a_1^3$ works too. If $0$ is an eigenvalue, then any function $f$ that vanishes on the column space of $A$ works. For nonsingular $A$, I strongly expect that if you insist on a function being sufficiently nice (I'm not sure exactly how), then the only options look something like $f(v) = \prod a_i^{e_i}$, where $\prod \lambda_i^{e_i} = \det(A)$.
Answer: This is an answer to your motivational question, not your asked question: in an earlier edit you claimed that you did not know how to prove the identity for $G_n$ using only determinants. Actually it is straightforward to do so: take determinants of both sides of the identity
$$\left[ \begin{array}{cc} 1 & 1 \\ 0 & 1 \end{array} \right]^n \left[ \begin{array}{cc} b & a + b \\ a & b \end{array} \right] = \left[ \begin{array}{cc} G_n & G_{n+1} \\ G_{n-1} & G_n \end{array} \right].$$
Comment: Actually, this suggests taking the matrix whose columns are $A^iv$ and taking the determinant. If that aligns with the construction, it would answer some other questions I had too.
Comment: Thank you again. This gave me the insight I needed to come up with the answer to the question I wanted to ask (not just where the construction came from, but why the formula was so nice). I will write up a solution when I have a chance.
Answer: There is a nice alternative to the construction which yields the same function (up to a constant), works if $A$ is not diagonalizable (although is zero if $A$ is diagonalizable with repeated eigenvalues), and always has coefficients in the base field/ring.  We define $M_{A,v}$ to be the matrix whose $j$th column is $A^{j-1}v$, i.e.,
$$M_{A,v}=\pmatrix{v & Av & A^2v & \cdots & A^{n-1}}.$$
It is straight forward that $AM_{A,v}=M_{A,Av}$, and so if we define $f_A(v)=\det(M_{A,v})$, then by the observation in the question update, $f_A(Av)=\det(A)f_A(v)$.
Moreover, we can directly compare this construction to the one in the question. Assume $A$ is diagonalizable, with eigenbasis and eigenvalue in the question.  Let $P$ be the matrix whose columns are the eigenvectors.  If $v=\sum a_i v_i$, then $P^{-1}v$ is the vector whose $j$th component is $a_j$.  $P^{-1}M_{A,v}$ will have $ij$ entry $a_i \lambda_i^{j-1}$. Taking the determinant, factoring out each of the $a_i$'s from the $i$th row and noting that we are left with a Vandermonde matrix, we have
$$\det(M_{A,v})=\det(P)\left( \prod_i  a_i \right)\prod_{i<j}(\lambda_j-\lambda_i).$$
Thus, up to a constant depending on our choice of eigenbasis and our eigenvalues, this construction agrees with the one in the question.
Unfortunately, this construction is automatically zero if we have repeated eigenvalues (which is not an issue with the original construction), so it is unclear if there is an equally nice construction for those cases.


"Uncaught TypeError: Cannot read property 'getAttribute' of undefined"

Question: There are some posts about this error for Drupal 7, but I'm using Drupal 8.1 and those solutions don't work for D8.
I tried this patch (coded for D7) and doesn't work.
The effect of the error is that QuickEdit doesn't work: sometimes the quick edit link doesn't appears, sometimes it appears but when edit some fields I get error.
Can anybody help?
UPDATE for neograph:
I haven't changed anything about the loading of the javascript. The only thing I did is edit the my_theme.libraries.yml for adding JS plugins:
global-css:
  css:
    theme:
      #css/style.css: { }
      dist/css/style.css: { }

global-js:
  js:
    #js/script.js: { }
    bower_components/slick-carousel/slick/slick.min.js: { }
    bower_components/slicknav/dist/jquery.slicknav.min.js: { }
    bower_components/superfish/dist/js/superfish.min.js: { }
    dist/js/script.js: { }
  dependencies:
    - core/jquery

Comment: Do you have changed anything in the loading of the javascript? Modules like [Advanced CSS/JS Aggregation](https://www.drupal.org/project/advagg) can cause this if configured incorrectly.
Comment: @Neograph734: could you check the Update on my question post? Thanks
Comment: I am still on D7 so I might not be the right person for this, but it does seem to have something to with JavaScript loading in the wrong order, or a missing dependency. Or perhaps your plugins are conflicting with each other.
Answer: The problem is in panels module, upgrade to latest version to fix the issue.
For more details see https://www.drupal.org/node/2713123
Answer: add defer to js files. When present, it specifies that the script is executed when the page has finished parsing.
global-css:
 css:
 theme:
   #css/style.css: { }
   dist/css/style.css: { }

global-js:
 js:
   #js/script.js: { }
   bower_components/slick-carousel/slick/slick.min.js: { attributes: { defer: true } }
   bower_components/slicknav/dist/jquery.slicknav.min.js: { attributes: { defer: true } }
   bower_components/superfish/dist/js/superfish.min.js: { attributes: { defer: true } }
   dist/js/script.js: { attributes: { defer: true } }
dependencies:
 - core/jquery


Where should I store 3rd Party external js libraries?

Question: This is a follow up to Define JavaScript library in Drupal 8
I have a third party library that I don't want to bundle with a module. In Drupal 7 I could just ask the user to extract to sites/all/libraries what is the best practice in Drupal 8?
Answer: One option is to do it exactly like in D7. Put it in /libraries or /sites/all/libraries and use the libraries module to detect the location.
location.module itself unfortunately doesn't work that well in 8.x yet, so you have to define an 8.x-1.x library and then use the libraries API to get the location and dynamically alter. Or I guess you could also do that part yourself.
I'm doing that in the JW Player project, see jw_player_libraries_info() + jw_player_library_info_alter(). It unfortunately still requires a bit of code, maybe that will improve in the future when libraries.module works better in 8.x.
Comment: I think this is the closest to an answer I'll find at the moment, fwiw I'm going with /libraries and will provide drush integration to download the file.
Answer: If we follow what symfony2 uses, we have to use then: /vendor/libraryname/lib/Libraryname/src/libraryname.js


How to place all form buttons on top of the page, before the form, in all forms?

Question: Since these forms can get quite big sometimes, especially with a lot of files attached and default preview for them.
Related, but not the same: How can I display a form button on top of the form?
Answer: You can do that using hook_form_alter() and setting the weight of $form['actions'] to a very small negative number.  Note that this applies only those buttons wrapped in $form['actions']. For other buttons that they aren't, you should add them manually.
function YOURMODULE_form_alter(&$form, &$form_state) {
  $form['actions']['#weight'] = -1000;
  // a button that is not wrapped in actions.
  // assuming it's id is 'submit'
  $form['submit']['#weight'] = -1000;
}

Comment: It's the answer for and from the related question I've mentioned. I'm not asking about my module, the question is about affecting all forms.
Comment: This answer IS for all forms. You should place this code in your module.
Comment: Guess I was distracted and didn't pay enough attention at the time.
Answer: The module for that is part of the Util package and is called, unsurpsingly, Top Buttons.
Drush:
drush dl util
drush en -y top_buttons

Answer: Adding to the answer above, #weight needs to be accessed with a preceding #. Also, you should check if the form elements exist before modifying them to avoid getting warnings in your logs.
Something like the below might work:
function YOURMODULE_form_alter(&$form, &$form_state) {
  if (isset($form['actions'])) {
    $form['actions']['#weight'] = -1000;
  }
  if (isset($form['submit'])) {
    $form['submit']['#weight'] = -1000;
  }
}

Also, this solution assumes you have a custom module for your site. If you don't, you'll need to research how to set one up first.
Comment: This code would go in your own module, but would effect forms from any module. hook_form_alter() runs on every form.


How to find out which components share duplication via the SonarQube api?

Question: I'm using SonarQube to detect duplication and want to use the api to find out for each block of duplication which components have that block. The api provides for getting the amount of duplication and which components have duplication. For example:
http://nemo.sonarqube.org/api/resources?resource=jquery&metrics=duplicated_blocks&depth=-1
This shows me which components have duplication and how many blocks. But I'd like to see which other components the components share duplication with. For example, I'd like to be able to retrieve information like this:
<code><duplicated_block>
    <length>100</length>
    <resource>
        <id>323</id>
        <key>org.my_org.project:component:org.my_org.project.comp.DateUtil</key>
        <scope>FIL</scope>
        <start_line>45</start_line>
    </resource>
    <resource>
        <id>456</id>
        <key>org.my_org.project:component:org.my_org.project.comp.DateTimeUtil</key>
        <scope>FIL</scope>
        <start_line>78</start_line>
    </resource>
</duplicated_block>
</code>
Is it possible to get information like that from SonarQube via the api?
Answer: Since SQ 4.4, you have a WS to get this information: "/api/duplications".
See its documentation on Nemo.


Disable one angle of rotation

Question: I'd like to disable one angle of rotation of an object rotating in 3D space. Imagine a camera rotating around and displaying objects as they are in space. I'd like this object to be fixed on the horizontal axis (always in the center of the camera view) and follow the camera rotation on other two angles ( yaw and pitch).
Before multiplying the position matrix with the view matrix, I tried to anull the roll rotation by extracting Euler angles from the view matrix and then recreating it with roll value of zero. Something along these lines:

Take view matrix and extract Euler angles
Create the same matrix by replacing roll with zero

It's giving somewhat strange results, and there must be a better way to do this.
Comment: So in other words, if there was a horizontal line across the camera viewer, it would always appear to be parallel to the horizon, correct? Is it critical you do this with Euler angles or would you be willing to do it with quaternions?
Answer: A quaternion solution which can compute a rotation quaternion as a composition of first a yaw turn then a pitching turn:
I'm thinking of the usual right-handed $i,j,k$ axes in three space. We suppose that the camera begins looking along the $i$ axis, and that the $i,j$ plane is horizontal.
To accomplish a yaw turn through an angle of $\psi$ radians, we can apply the transformation $x\mapsto qxq^{-1}$ where $q=\cos(\psi/2)+\sin(\psi/2)k$.
At that point, we could rotate around $qjq^{-1}$ to perform a pitch turn. Set $h=qjq^{-1}$.  A pitch up by $\theta$ radians is accomplished by the transformation $x\mapsto pxp^{-1}$ where $p=\cos(\theta/2)+\sin(\theta/2)h$.
The composition would just be given by $R=pq$, mapping $x\mapsto RxR^{-1}$. One would have to multiply out what $pq$ is in terms of $\psi$ and $\theta$, but that isn't too hard.
Unfortunately I am not adept at converting this solution to Euler angles or rotation matrices, but fortunately there is a wiki devoted to that subject.
Comment: Thanks, but my quaternion knowledge is rather limited, unfortunately.
Comment: @user1304844 Yeah, sorry if it doesn't directly help. It's the least complicated theoretical solution that I'm handy with. What texts do you have to help you solve the problem?
Comment: Actually you did help. I ended up reading your solution over and over again and studying quaternions for a day. What I did was: 1.Take rotation matrix and convert to quaternion; 2. Set Y component to zero (since the y component get multiplied with the Y axis of the vector. If there is no rotation, y is 0); 3. Normalize the quaternion; 4. OPTIONAL: Convert it back to a matrix4f (since openGL works very well with matrices) and set translation values from the original matrix ( the last column of the original matrix gets copied)
Comment: @user1304844 Awesome! Good luck with your studies!
Comment: For those of you who need to read up on quaternions like me, better explained has a fabulous tutorial: https://betterexplained.com/articles/a-visual-intuitive-guide-to-imaginary-numbers/

Disable one angle of rotation


How to attach browser-specific stylesheets in D8?

Question: In D7 it's possible to attach a css file based on browser sniffing, like this:
drupal_add_css(
  $path_to_css,
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

Drupal 8 does away with drupal_add_css in favour of #attached => array('css' => array( $path_to_css )) but how, in that situation, can you achieve the same thing.
(Nb. I'm not actually using D8 yet, but where things can be done the D8 way in D7, I'm adopting them to ease the learning curve to come!)
Answer: I think this'll do it in Drupal 7, it should be the same for Drupal 8:
$build['#attached']['css'][] = array(
  'type' => 'file',
  'data' => $path_to_css,
  'options' => array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE,
    ),
  ),
 );


monitoring Amazon EC2 instances without cloudwatch

Question: I would like to monitor the following on Amazon ec2 instances loaded with amazon linux, every X minutes :
disk statistics
process stats (similar to what top does)
ram usage
check if my scripts are running fine
should I use my own scripts and things or are there any tools that already achieve this ?
I searched and there was a suggestion about munin
what seems to be the better approach ?
Comment: can any of the mentioned softwares give me number of open handles in linux ?
Answer: you can use zabbix with mikoomi will get all result the same.
Answer: I've done it with Munin.. It's easy.  Just allow port 4949 through the firewall/Security Group to your munin server, and everything just works. (Remember to add the munin server to munin-node.conf on the EC2 node)
Comment: seems good to me too... was searching if there was anything better :)
Answer: Can I ask why you do not want to use Cloudwatch?
It has a free level (15 monitoring interval).
Comment: It doesn't give process statistics like,
how much memory a particular process is using,
is the system running absolutely fine,
is my application stack i.e scripts and other services are running fine,
etc..
And then, I guess we can do better by running our own scripts or third party tools like munin or nagios.


CSS responsivo não é lido pelo site

Question: O arquivo responsive.css não está sendo lido pelo meu site.
Estou chamando assim:
   <link type="text/css" rel="stylesheet" href="css/responsive.css">

Dentro dele há o seguinte código:
@media screen and (max-width: 640px) {
.right-side { width: 100%; }}

No caso, o right-side está definido como 50%.
O qual não está sendo aplicado quando eu emulo o navegador na versão mobile.
Galaxy S5 (360*640)
O que pode ser?
Comment: Já usou a ferramenta de dev do seu navegador (**[F12]**) pra verificar se o script foi carregado corretamete e se nenhum outro *style* está conflitando com a regra? Ainda pode ser que o `@media` está adequado pra resolução que está testando
Comment: Sim, é aqui que não chama. Se eu colocar o caminho do arquivo diretamente no navegador, ele abre normalmente. Qual resoluções você indica usar no **@media**?
Comment: As do *bootstrap* me parecem boas e bem aceitas: https://getbootstrap.com/docs/3.3/css/#grid-media-queries
Comment: Nesse projeto não usarei Bootstrap. Quais vocês costuma usar?
Comment: Não sei como está a navegação do site nem as pastas, mas se não estiver carregando o `css`, talvez possa tentar forçar buscar da raiz do site com a barra: `href="/css/responsive.css"`
Comment: Entendi, mas se olhar no link, vai ver que tem as resoluções usadas no *bootstrap*: Extra small devices Phones (<768px), Small devices Tablets (≥768px), Medium devices Desktops (≥992px), Large devices Desktops (≥1200px). Tento copiar as mesmas :)
Comment: Vc coloca o seu código completo HTML/CSS inclusive com a `` da página que ajuda. Sobre as larguras de tela acho que essa resposta pode te ajudar. https://pt.stackoverflow.com/questions/272494/qual-o-tipo-de-medida-utilizada-na-hora-da-constru%C3%A7%C3%A3o-de-um-site-para-largura-a/272537#272537
Answer: Adicionou as seguintes meta tags no ?
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

Comment: Eu não estava chamando. Agora está funcionando.

CSS responsivo não é lido pelo site


Envio de formulário para banco de dados com Mysql e php

Question: Alguém pode me ajudar a saber onde estou errando?! esta dando este erro nas linhas de identificação dos campos.
Answer: Como seu POST ainda não foi inicializado(está vazio), aparece essa notificação. Para resolver você pode esconder o erro ou utilizar a condição is set
if(isset($variavel)){
// True se tiver conteúdo na variável e false se não tiver
}
Exemplo:
if(isset($_POST['nome')){
    $nome = $_POST['nome']
} else {
    $nome = NULL;
}

Se preferir pode inicializar as variáveis como por exemplo $nome = "";
Ou então desabilitar as mensagens de erro/aviso como já foi sugerido.
Comment: seria uma boa opção também colocar ele dentro do IF ?
Comment: Quando diz "ele" se refere a oque exatamente?
Answer: As mensagens são notificações de que suas variáveis não foram declaradas anteriormente, isso não é um erro e sim notificação, você pode desabilitá-las definindo display_errors como 0 ou usar a função error_reporting().
Como fazê-lo.
<?php
// Adicionar no começo do seu código PHP.
error_reporting(0);
?>

Outras opções interessantes para essa função:
<?php

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL & ~E_NOTICE);
// For PHP < 5.3 use: E_ALL ^ E_NOTICE

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

Conteúdo extraído da uma resposta no SOen. How do I turn off PHP Notices?
Answer: Olá, porque você não tenta isso aqui:
<?php

if ($_POST) {

 -- seu script --

}
?>


Java- how to get the validator to check if input is a double and a whole number

Question: my question really just pertains to where I should put the bit of code that checks to make sure the input is a whole number. Thanks to anyone who helps.
public static String getQuantity(String aQuantity){
    while (isValidQuantity(aQuantity)== false ){
        errorMessage += "Enter Valid quantity\n";
    }
    return aQuantity;
    }
    private static boolean isValidQuantity(String aQuantity){
    boolean result = false;
    try{
        Double.parseDouble(aQuantity);
     //here?//
        result = true;
    }catch(Exception ex){
        result = false;
    }

    return result;
}

Comment: How about a simple regex? Provoking an `Exception` is definitly not an option and considered bad style.
Comment: You are already wrapping it in a try catch.  parseDouble will throw and NumberFormatException.  You can exit there or do something else like set a default.
Comment: Regex is a best feature which can easily identify your string and validate the string..
Programs flow should be first validate the string against the regex and then try to parse it..
Advantage of this flow is no exception handling is needed while parsing it to the double or float what ever you want..
Comment: I'm going to say that lots of developers see it both ways.  Performance wise regular expressions tend to be more expensive.  I use them more for filtering rather than validation.  You can [read a bit more here](http://stackoverflow.com/questions/5227633/regex-or-exception-handling) for lots of opinions..  I prefer to fail fast and cheap when it makes sense.
Comment: @TheUnfortunateNudist `Exception`s should be exceptional (as already the name suggests), not a way of controlling the flow of a program. And throwing and afterwards catching an exception definitely costs more than setting up a simple check for an input with a valid format.
Comment: [Per the spec](http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12)  __Looking more closely, the **try block is compiled just as it would be if the try were not present**...If no exception is thrown... it behaves as though the try were not there.__  If your data is good more often than bad, try/catch is cheaper.  User input is always more susceptible to being bad but the general case where you are dealing known data a regular expression is overkill IMO.  Especially when you still have to create additional error handling if data doesn't match.  Differing opinions :D
Comment: @Paul. I apologize for my ignorance but what about this situation makes Exception a bad option?
Answer: You can do it easily using regex. For double use this:
Pattern.compile("\\d+\\.\\d+")

If you want to take care of doubles in the scientific notations (e.g. like 3.4-e20), use this:
Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")

For whole number, you can simply use the parts before the . in each of the regex above. Like
Pattern.compile("\\d+")

For numbers that may have sign,
Pattern.compile("[-+]?[0-9]+")

Note the + at the end of the last one. There has to at least one digit for it to qualify as a number, hence you can not use *, which means zero or more occurrence.
Javadocs for regex here.
Test the double's pattern in regexr.
Answer: Your solution should work, because any integer will parse as a double as well. You could make it more verbose, and have 0 represent invalid 1 represent an int and 2 represent a double.
private static int isValidQuantity(String aQuantity){
    int result = 0;
    //first try int
    try{
        Integer.parseInt(aQuantity);
        result = 1; //the parse worked
    }catch(NumberFormatException ex){
        result = 0;
    }

    if(result == 0)
    {
        //if it's not an int then try double
        try{
            Double.parseDouble(aQuantity);

            result = 2; //the parse worked
        }catch(NumberFormatException ex){
            result = 0;
        }
    }

    return result;
}


If every row in a square grid corresponds to a column, then every column corresponds to a row.

Question: I am looking for a proof of the following:

A square grid is filled out with symbols from some alphabet, with one symbol in each square of the grid. Each row of the grid is the same as some column (i.e. the sequence of symbols obtained from reading across any row from left to right is the same as the sequence of symbols obtained from reading (at least) one of the columns from top to bottom).
Show that every column is also the same as some row.

I am asking because I run a site which is creating an archive of Enigma puzzles that were originally published in New Scientist magazine between 1979 and 2013. Mostly I focus on programmatic solutions, but some problems need a more analytic approach.
This question is part of Enigma 1248 -https://enigmaticcode.wordpress.com/2015/03/16/enigma-1248-rows-and-columns/
Comment: @GerryMyerson: The magazine publishes the answer (so they said it was not possible to find a grid for part 2 of the puzzle), but not a full solution.
Comment: The New Scientist didn't publish solutions?
Answer: Here's a sketch of a solution.
If all the rows are distinct, then it's clear that each column must be the same as some row. So, assume rows $i$ and $j$ are identical ($i\ne j$).
Now consider row $k$. It must be identical to some column, say, column $\ell$. Since rows $i$ and $j$ are identical, the $(i,\ell)$ and $(j,\ell)$ entries must be equal. Since row $k$ is identical to column $\ell$, the $(k,i)$ and $(k,j)$ entries must be equal. Since $k$ was arbitrary, columns $i$ and $j$ must be identical.
So, we have proved that if rows $i$ and $j$ are identical, then columns $i$ and $j$ are identical.
More generally, if the rows in any collection are identical, then the columns in the corresponding collection must be identical.
It follows that the number of distinct rows equals the number of distinct columns, and then that each column must be identical to some row.
Comment: Thanks for that. I have fleshed it out on the Enigmatic Code site to give a full solution to the second part of the problem.


Instantiating Fields: via UI, API or Drush?

Question: Are there any benefits of using one method of instantiating over another?
From what I'm guessing, creating field instances via the API (programatically) has benefits over the UI since you get to version control the changes.
Drush commands can be put into a script as well and then version controlled.
Are there any other pros/cons to doing things programatically versus the UI?
Answer: You can use Features to export your UI-created field configurations and version control the result. It's much faster to create and modify field instances in the UI unless you're extremely familiar with the Field API. I used to create fields programmatically but I feel like my time would have been better spent using the UI and occasionally exporting with Features for VCS/simpletesting.
Comment: Feature exports all field and content type settings including definitions and instances
Comment: Can features export field definitions as well? Or only field instances?


Animação em JavaScript (hover) para Touch

Question: Como eu posso fazer uma animação em JavaScript que possui CSS hover evento, funcionar para quando o usuário usar o touch em um mobile, por exemplo.
Meu código da animação não funciona para Touch (Mobile). Qual minha opção?
Comment: Java ou JavaScript?
Comment: Editei sua pergunta deduzindo através das informações fornecidas que não se trata de [Java](http://www.oracle.com/br/technologies/java/overview/index.html) e sim de [Javascript](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript). Em caso de discordância desfaça a edição.
Answer: O comportamento de mouse hover não é um evento esperado para entradas de Touch na Web.
Como citado aqui, os eventos esperados para entradas de Touch são:

touchstart;
touchend;
touchmove;
touchcancel;

Não contendo nenhuma referência a eventos de hover (que em tradução literal seria: "pairar sobre", que não é um recurso disponível na maior parte das tela Touch) e para outros eventos específicos de mouse.

Conclusão: esse não é um comportamento esperado por usuarios que utilizam Touch, sendo assim se sua funcionalidade baseada no evento mouse hover for essencial para sua aplicação e ela tem como target dispositivos moveis e/ou com recursos de Touch, reveja a funcionalidade para adequa-la a esse novo cenário.

Referências e sugestões de leitura:

Há essa discussão a respeito a alternativas ao evento hover em dispositivos touch-based (Em Inglês);
Aqui temos um exemplo de implementação de uma solução alternativa a dispositivos touch-based, que apresenta uma solução alternativa a menus com submenus baseados em hover (Em Inglês);
Uma de minhas principais referências para afirmar "Não isso não é possível" (Em Inglês);
Comment: Realmente, porque se tu for parar para analisar no touch tu não tem como colocar nada em cima de um botão, por exemplo, e deixar ele la. Tu pode pressionar ele somente, e nisso entram os eventos citados na resposta do @Fernando


Copying BIG Data To And From GPU Using CUDA

Question: I am new to CUDA and I am trying a very simple task myself -- copying memory to the graphic card and then copy back. Here is the simplified version of the code that I wrote.
const int arraySize = 100;

int* data1 = NULL;
int* data2 = NULL;
// Initialized both data1 and data2
// ...

int* dev_data1 = NULL;
int* dev_data2 = NULL;
// Initialized both dev_data1 and dev_data2
// ...

// copy data1 to device
cudaMemcpy(dev_data1, data1, arraySize*sizeof(int), cudaMemcpyHostToDevice );

// copy dev_data1 to dev_data2 with gpu
gpuCopy<<<1, arraySize>>>( dev_data1, dev_data2 );

// copy dev_data2 to data
cudaMemcpy(data2, dev_data2, arraySize*sizeof(int), cudaMemcpyDeviceToHost );

And gpuGopy is as the following:
__global__ void gpucopy( int* src, int* dst )
{
    int i = threadIdx.x;
    dst[i] = src[i];
}

I found that if arraySize is small, the above function works. But if arraySize reach a specific size, data2 will become all zeros. My guess is that there is some sort of limitation when running the gpu functions. But is there a way to find that out? If I have a very big array, how can I copy it to GPU (and back)?
Comment: The code as posted would have a kernel launch failure (resulting in no modified output) at either 513 (and above) or 1025 (and above) for `arraySize`, depending on the specific GPU and compilation commands being passed.
Comment: Pleas post a full compileable sample! With the snippets you've posted it's not possible the help you with your Problem about the 0's. Also plese do [proper cuda error checking](http://stackoverflow.com/questions/14038589/what-is-the-canonical-way-to-check-for-errors-using-the-cuda-runtime-api)
Comment: How large is "a specific size"?
Comment: @maxywb. Just tested on my machine. The specific size is 512. But based on the following answers, this number should vary between different machines.
Answer: First of all you should be doing proper cuda error checking
Secondly, you may be under the impression that threadIdx.x gives a globally unique thread ID.  It does not.
So modify your kernel line from:
int i = threadIdx.x;

to:
int i = blockIdx.x * blockDim.x + threadIdx.x;

Finally, your threads per block parameter cannot exceed 512 or 1024 depending on the GPU.  We launch larger grids by specifying both a threads per block and blocks per grid parameter:
#define nTPB 512
gpuCopy<<<(arraySize + nTPB - 1)/nTPB, nTPB>>>( dev_data1, dev_data2 );

Coupled with this grid sizing approach, we usually include a thread-check in the kernel, to prevent out of bounds accesses for arbitrary grid/problem sizes:
__global__ void gpucopy( int* src, int* dst, int size )
{
    int i = threadIdx.x + blockDim.x * blockIdx.x;
    if (i < size)
      dst[i] = src[i];
}

And likewise we have to tell that kernel the problem size:
gpuCopy<<<(arraySize + nTPB - 1)/nTPB, nTPB>>>( dev_data1, dev_data2, arraySize );

You might want to review the CUDA programming guide
Answer: The threadIdx index is architecture-dependent and you cannot just set it at whatever you like.
The following code works until arraySize == 1024 on my system, but then at arraySize == 1025 I get undefined values
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <iostream>
using namespace std;

__global__ void gpucopy( int* src, int* dst )
{
  int i = threadIdx.x;
  dst[i] = src[i];
}

int main()
{
  const int arraySize = 500; // >= 1025 will fail on my system!

  int* data1 = new int[arraySize];
  int* data2 = new int[arraySize];
  // Initialized both data1 and data2
  // ...
  for(int i=0; i<arraySize; i++)
    data1[i] = 2*i;

  int* dev_data1 = NULL;
  int* dev_data2 = NULL;
  // Initialized both dev_data1 and dev_data2
  // ...
  cudaMalloc(&dev_data1, arraySize*sizeof(int));
  cudaMalloc(&dev_data2, arraySize*sizeof(int));

  // copy data1 to device
  cudaMemcpy(dev_data1, data1, arraySize*sizeof(int), cudaMemcpyHostToDevice );

  // copy dev_data1 to dev_data2 with gpu
  gpucopy<<<1, arraySize>>>( dev_data1, dev_data2 );

  // copy dev_data2 to data
  cudaMemcpy(data2, dev_data2, arraySize*sizeof(int), cudaMemcpyDeviceToHost );

  for(int i=0; i<arraySize; i++)
    if(data2[i] != data1[i])
      cout << "Error: data is different - data2[" << i << "] is " << data2[i] << endl;

      return 0;
}

You can find out this value by either looking at the documentation or with the deviceQuery() function
C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.1\C\bin\win64\Release\deviceQuery.exe Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Found 2 CUDA Capable device(s)

Device 0: "Tesla C2050"
  CUDA Driver Version / Runtime Version          4.2 / 4.1
  CUDA Capability Major/Minor version number:    2.0
  Total amount of global memory:                 2688 MBytes (2818572288 bytes)
  (14) Multiprocessors x (32) CUDA Cores/MP:     448 CUDA Cores
  GPU Clock Speed:                               1.15 GHz
  Memory Clock rate:                             1500.00 Mhz
  Memory Bus Width:                              384-bit
  L2 Cache Size:                                 786432 bytes
  Max Texture Dimension Size (x,y,z)             1D=(65536), 2D=(65536,65535), 3D=(2048,2048,2048)
  Max Layered Texture Size (dim) x layers        1D=(16384) x 2048, 2D=(16384,16384) x 2048
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 32768
  Warp size:                                     32
  Maximum number of threads per block:           1024 <-----

Comment: I think you'll get an error with your kernel call, because depending in compute capability it's only possible to launch up to 1024 threads per block. When you're usw error checking you'll see that.
Comment: That's correct, in fact I can only launch it with <= 1024. 1025 will fail


.Net 6 unit test project not able to load project references

Question:
I am using Visual Studio 2022 Enterprise on Windows 10.
I have a C# class library project targeting .Net standard 2.0 (let's call this Project1). This project has project reference to other C# class librabry where there are also targeting .Net standard 2.0.
I created a .Net 6 unit test project (let's call this UnitTestProject) to test Project1.
All of the projects are in the same solution.

The UnitTestProject has these package reference
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="MSTest.TestAdapter" />
<PackageReference Include="MSTest.TestFramework" />

Microsoft.NET.Test.Sdk 17.5.0
MSTest.TestAdapter 3.0.2
MSTest.TestFramework 3.0.2

The UnitTestProject is referencing Project1 using project reference because there are in the same solution.
<ProjectReference Include="..\Project1\Project1.csproj">
  <Private>False</Private>
</ProjectReference>

This is the folder structure
C:\myapp\myapp.sln
C:\myapp\sources\Project1\Project1.cspoj
C:\myapp\sources\UnitTestProject\UnitTestProject.csproj

The build output
C:\myapp\sources\bin\Project1.dll
C:\myapp\sources\unittest\net6.0\UnitTestProject.dll

I am using a .runsettings file for the unit test project located in C:\myapp\.runsettings
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <MSTest>
    <MapInconclusiveToFailed>True</MapInconclusiveToFailed>
    <CaptureTraceOutput>False</CaptureTraceOutput>
    <DeleteDeploymentDirectoryAfterTestRunIsComplete>False</DeleteDeploymentDirectoryAfterTestRunIsComplete>
    <DeploymentEnabled>True</DeploymentEnabled>
    <AssemblyResolution>
      <Directory path="..\..\" includeSubDirectories="true"/>
    </AssemblyResolution>
  </MSTest>
</RunSettings>

I can Clean and Rebuild all related projects without error, all succeeded.
But when I tried to execute any test method in UnitTestProject, the result shows

Test run finished: 0 Tests (0 Passed, 0 Failed, 0 Skipped) run in < 1 ms

When I check the Test pane, with logging level set to Diagnostic. I see this message

[Warning] [MSTest][Discovery][C:\myapp\sources\unittest\net6.0\UnitTestProject.dll] Unable to load types from the test source 'C:\myapp\sources\unittest\net6.0\UnitTestProject.dll'. Some or all of the tests in this source may not be discovered.
Error: System.IO.FileNotFoundException: Could not load file or assembly 'Project1, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Also in the Test output pane, the runsetting is displayed with RunConfiguration.
<RunSettings>
  <MSTest>
    <MapInconclusiveToFailed>True</MapInconclusiveToFailed>
    <CaptureTraceOutput>False</CaptureTraceOutput>
    <DeleteDeploymentDirectoryAfterTestRunIsComplete>False</DeleteDeploymentDirectoryAfterTestRunIsComplete>
    <DeploymentEnabled>True</DeploymentEnabled>
    <AssemblyResolution>
      <Directory path="..\..\" includeSubDirectories="true" />
    </AssemblyResolution>
  </MSTest>
  <RunConfiguration>
    <ResultsDirectory>C:\myapp\TestResults</ResultsDirectory>
    <SolutionDirectory>C:\myapp\</SolutionDirectory>
    <MaxCpuCount>0</MaxCpuCount>
    <EnvironmentVariables>
      <VSTEST_BACKGROUND_DISCOVERY>1</VSTEST_BACKGROUND_DISCOVERY>
    </EnvironmentVariables>
    <CollectSourceInformation>False</CollectSourceInformation>
  </RunConfiguration>
</RunSettings>

If I set the Copy Local to Yes (<Private>True</Private>) for the project reference, I am able to execute all test in the test project.
I have no idea what are the issues here, if the whole setup here is incorrect or something else, please help. Thanks.
I've tried building the UnitTestProject into unittest folder (without net6.0).
C:\myapp\sources\unittest\UnitTestProject.dll

And change <Directory> in the .runsettings from ..\..\ to ..\
<AssemblyResolution>
  <Directory path="..\" includeSubDirectories="true"/>
</AssemblyResolution>

It is still not working.
I even tried target the Project1 to .Net 6, not working as well.

Edit #1:
I enabled the logging level to Trace, and in the trace file

AssemblyResolver.OnResolve: Project1: Resolving assembly.
AssemblyResolver.OnResolve: Project1: Searching in:
'C:\myapp\sources\unittest\net6.0'.   AssemblyResolver.OnResolve:
Project1:  Assembly path does not exist:
'C:\myapp\sources\unittest\net6.0\Project1.dll', returning.
AssemblyResolver.OnResolve: Project1: Assembly path does not exist:
'C:\myapp\sources\unittest\net6.0\Project1.exe', returning.
AssemblyResolver.OnResolve: Project1: Failed to load assembly.

It seems like it doesn't use the runsettings file where I specifically specified the Directory path under the AssemblyResolution

Edit #2:
I changed the Directory path in the AssemblyResolution in the runsettings file to use the absolute path to the bin folder, still it is not using that setting.
Answer: Got the answer from the microsoft/testfx.
[ MSTest][Discovery] Unable to load types from the test source ... Could not load file or assembly #1645

As you pointed out, you are using the AssemblyResolution configuration
in the runsettings file. This property allows users to give different
locations in which MSTest should try to be loading dlls from. This is
used internally in a custom assembly resolver along with AppDomains.
In netcore/net versions of .NET, some functionnalities of the
AppDomain are no longer available which is preventing some of the
behaviours of MSTest.
To answer more specifically your questions. No, there will not be any
"fix" for supporting the AssemblyResolution property in netcore/net
versions of MSTest. But we will update the documentation to specify
this is not supported AND we will emit a warning if we detect this
property in some netcore run.
As for workarounds, I would suggest "fixing" the project setup so that
the dlls are found in the location of the test dll. As explained in
some previous comment, you could remove the , you could add a
task to copy the dlls in the custom location or edit the "production"
projects to emit in the custom location
Answer: You can try by using absolute path just for testing. I guess this is because of path only I too have encountered similar issue and was able to debug using absolute path.
Hope this helps.
Comment: Welcome to SE! @RohitSingh Please improve your answer with a sample reproducible solution to the question.
Comment: You mean putting the absolute path in the `.runsettings`? I've tried using `C:\myapp\sources` and `C:\myapp\sources\bin` and still no luck.
Edit: The test will eventually be running in a server, so I guess using absolute path is not a good idea. Thanks.


Why does the compiler look for a default constructor for my exception class?

Question: I've defined a small exception hierarchy for my library. It inherits from std::runtime_error, like this:
class library_exception : public std::runtime_error {
    using std::runtime_error::runtime_error;
};

class specific_exception : public library_exception {
    int guilty_object_id;

    specific_exception(int guilty_object_id_)
        : guilty_object_id(guilty_object_id_) {}
};

The compiler says:

error: call to implicitly-deleted default constructor of 'library_exception'

and points to the specific_exception constructor.
Why is it trying to call the default constructor here?
Answer: library_exception inherits from std::runtime_error. The latter does not have a default constructor, which means the former isn't default constructable.
Similarly, specific_exception isn't default constructable because its base class isn't. You need a default constructor for the base here because the base is implicitly initialized:
specific_exception(int guilty_object_id_)
    : guilty_object_id(guilty_object_id_) {}

To fix this, call the appropriate base class constructor:
specific_exception(int guilty_object_id_)
    : library_exception("hello, world!"),
      guilty_object_id(guilty_object_id_) {}

Answer: Retracted: This answer was misguided. (The constructors referred to are actually used in default initialization of class members, not the class itself.)
std::runtime_error has a string field, something like this:
class runtime_error {
    std::string msg;

public:
    runtime_error(std::string msg) : msg(msg) { }
};

msg is not initialized by your constructor (and can't be, since the field's private). Therefore the default constructor is invoked. More precisely,

default initialization […] is the initialization performed when a variable is constructed with no initializer.
…
Default initialization is performed in three situations:
…
3) when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.
The effects of default initialization are:
…
If T is a […] class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object.

(cppreference.com)
However, I still don't get why it's complaining about the base class library_exception instead of specific_exception. Adding an argument-less constructor in specific_exception doesn't make a difference.
Comment: Isn't the default constructor deleted when one of the base classes' default constructor is deleted? so `library_exception` has a deleted default constructor. Note: I can't quote the standard here


How do form #states interact with dialog action buttons, if at all?

Question: A dialog can be fired by a link formatted as such:

    Some path displayed in modal dialog.

If the contents of /some/path are a form, then drupal takes its action buttons and drops them into a "footer"

 in the dialog. This seems to take into account the initial state of the buttons -- so if submit has the disabled attribute by default then the corresponding UI button gets the .is-disabled class applied. The "real" form action buttons are rendered but set to display: none.
However, I've got #states set up on my submit button with
$form['actions']['submit']['#states'] = [
  'disabled' => [
    ':input[name="field_fivestar_rating[0][rating]"]' => [
      [
        ['value' => '-'],
        ['OR'],
        ['value' => '0'],
      ],
    ],
  ],
];

The "real" form submit button is updated correctly according to its #states attribute, but the same cannot be said for the corresponding dialog button. It seems to be static based on the initial state of the submit button.
Is this expected behavior? If so, is this something that deserves an issue in the queue? Seems like an oversight and usability concern.
Answer: This doesn't answer the question itself, but since I struggled for a while to get this all syncd up I figured I should drop the work into something that people might hit from google. To get the attributes all syncd up you can use the following js file:
(function ($, Drupal, drupalSettings) {
  var handler = Drupal.behaviors.commentsRatingFlexible = {
    attach: function (context, settings) {
      // If our form is loaded in a modal, then the context is
      // the form itself. Therefore we cannot look for the form
      // inside of context. As such, we need to check for forms
      // that exist in both situations an handle accordingly.
      var formInstances = [];

      // This would be the class for your particular form
      $('.comment-rating-flexible-form', context).each(function () {
        formInstances.push($(this));
      })

      if ($(context).hasClass('comment-rating-flexible-form')) {
        formInstances.push($(context));
      }

      // Lookup any rating-flexible-forms and disable the submit
      // button by default, since it shouldn't allow an empty val
      // for the fivestar field (if it's present)
      for (var k in formInstances) {
        var $form = formInstances[k];
        var $submit = $('.form-submit', $form);
        var $fivestarSelect = $('[name="field_fivestar_rating[0][rating]"]', $form);

        if (!$fivestarSelect.length) {
          return
        }

        handler.dialogSubmitButtonHandler($form); //must be called first
        handler.observeAttributes($submit);

        if ($fivestarSelect.val() == '-' || $fivestarSelect.val() == '0') {
          // #states don't apply on form load, only on change,
          // so we need to disable the form button here and
          // sync that onto the dialog's button
          $submit.attr('disabled', "");
        }
      }
    },
    /**
     * Syncs attributes from real form-submit onto dialog submit btn.
     *
     * @param $form
     *   The form contained in the dialog
     */
    dialogSubmitButtonHandler: function ($form) {
      var $drupalModal = $form.parent();

      // If the form is loaded outside the context of a modal, don't execute
      if ($drupalModal.attr('id') !== 'drupal-modal') {
        return;
      }

      // The actual modal and the rest of its contents won't exists
      // on the initial load. As such, we need to add a watcher to
      // the DOM to find out when our dialog action buttons exist
      // so that we can act on them then.
      var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
          if (!mutation.addedNodes.length) {
            return
          }

          mutation.addedNodes.forEach(function (node) {
            var $node = $(node);
            if (!$node.hasClass('ui-dialog-buttonpane')) {
              return;
            }

            var $formSubmitButton = $('.form-submit', $form);
            var $dialogSubmitButton = $('.form-submit', $node);

            // Watch for our custom $.event from observeAttributes
            $formSubmitButton.on('attributeUpdated', function (e, attrData) {
              $dialogSubmitButton.attr(
                attrData.attributeName,
                attrData.attributeNewValue
              );
            })

            observer.disconnect();
          })
        })
      })

      observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
      })
    },
    /**
     * Fires an event when an element's attributes change.
     *
     * @param $el
     *   The jQuery element being observed
     */
    observeAttributes: function ($el) {
      var observer = new MutationObserver(function (mutationList, observer) {
        var eventData = [];

        mutationList.forEach(function (mutation) {
          if (mutation.attributeName === 'style') {
            return;
          }

          var attributeName = (mutation.attributeName === 'class') ? 'classList' : mutation.attributeName;

          $el.trigger('attributeUpdated', {
            'attributeName': mutation.attributeName,
            'attributeNewValue': mutation.target[attributeName],
            'attributeOldValue': mutation.oldValue
          })
        })
      });

      observer.observe($el[0], {
        attributes: true,
        attributeOldValue: true,
      });
    },
  }
})(jQuery, Drupal, drupalSettings);


The purpose Swift URL Components in iMessage Apps?

Question: I am brand new to iMessage App development. Looking at some examples, it looks like the way information is transferred from the sender to the recipient with iMessage Apps is via URLComponents.

Is this the only way to send information on iMessage Apps?
I am unfamiliar with URLComponents in swift, does the actual URL even matter?

Thanks!!
Answer: MSMessage's url property is where you can store your custom data.
You can use iMessageDataKit library for storing key-value pairs in MSMessage objects. It makes setting and getting data really easy like:
let message: MSMessage = MSMessage()

message.md.set(value: 7, forKey: "user_id")
message.md.set(value: "john", forKey: "username")
message.md.set(values: ["joy", "smile"], forKey: "tags")

print(message.md.integer(forKey: "user_id")!)
print(message.md.string(forKey: "username")!)
print(message.md.values(forKey: "tags")!)

(Disclaimer: I'm the author of iMessageDataKit)
Answer: You can use it w/ native swift as well:
let layout = MSMessageTemplateLayout()
var components = URLComponents()
let caption = URLQueryItem(name: "caption", value: self.melody)
let decodedMelody = URLQueryItem(name: "melody", value: self.melody)

components.queryItems = [caption, decodedMelody]

let message = MSMessage(session: session ?? MSSession())
layout.image = self.screenImage.image

layout.caption = "Melody built with haptic and vibro."
layout.subcaption = "sent via iVibrio"
message.summaryText = "something summary"

message.url = components.url!
message.layout = layout

Here's my complete example how to send data and image via iMessage application


Ordenar dados em dataframe pandas pela frequência de repetição de cada elemento

Question: Eu tenho um dataframe e quero organizar os dados pela frequência de aparecimento de cada elemento. Do que mais se repete para o que menos se repete, para criar um ranking. Eu quero que a organização seja feita a partir das colunas uf e tipo_acidente
acidentes2020 = pd.read_csv('https://arquivos.prf.gov.br/arquivos/index.php/s/jdDLrQIf33xXSCe/download', compression='zip',encoding='iso8859-1', sep=';')

ranking2020 = acidentes2020[['uf', 'tipo_acidente']]

Comment: você quer apenas sortear as observações? Se sim, veja o método `sort_values`: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html Caso você queira agrupar os valores antes de ranquear, use `groupby`: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
Comment: desculpe, minha pergunta foi equivocada. Eu quero ranquear mesmo. Por exemplo: quero que mostre o `tipo_acidente` que mais ocorreu para determinada `uf`.
Answer: Em detalhes:
Carregando biblioteca
import pandas as pd

Criando DataFrame de teste
df = pd.DataFrame({"A": [1,2,3,1,2,3,1,1,2,2,1,3]})

print(df)

    A
0   1
1   2
2   3
3   1
4   2
5   3
6   1
7   1
8   2
9   2
10  1
11  3

Criando coluna com frequências
df['frequencia'] = df.groupby('A')['A'].transform('count')

print(df)

    A  frequencia
0   1           5
1   2           4
2   3           3
3   1           5
4   2           4
5   3           3
6   1           5
7   1           5
8   2           4
9   2           4
10  1           5
11  3           3

Ordenando por frequência
df1 = df.sort_values(by='frequencia')

print(df1)

    A  frequencia
2   3           3
5   3           3
11  3           3
1   2           4
4   2           4
8   2           4
9   2           4
0   1           5
3   1           5
6   1           5
7   1           5
10  1           5

Nota 1: usar o ascending=False para ordenar em ordem decrescente
Nota 2: usar o inplace=True para não ter que atribuir o resultado a outro DataFrame


Iterating a groupby datetime over several weeks

Question: I'm trying to group my data by a week that I predefined using to_datetime and timedelta. However, after copying my script a few times, I was hoping there was a way to iterate this process over multiple weeks. Is this something that can be done?
The data set that I'm working with lists sales out sales revenue and spending out by the day for each data source and its corresponding id.
Below is what I have so far but my knowledge of loops is pretty limited due to being self-taught.
Let me know if what I'm asking is feasible or if I have to continue to copy my code every week.
Code
import pandas as pd
from datetime import datetime, timedelta,date

startdate = '2021-09-26'
enddate =  pd.to_datetime(startdate) + timedelta(days=6)

last7 = (df.date >= startdate) & (df.date <= enddate)
df = df.loc[last7,['datasource','id','revenue','spend']]

df.groupby(by=['datasource_name','id'],as_index=False).sum()
df['start_date'] = startdate
df['end_date'] = enddate
df

Comment: Can you share sample dataset?
Answer: If I have understood your issue correctly, you are basically trying to aggregate daily data into weekly. You can try following code
import datetime as dt
import pandas as pd

#Get weekend date for each date

df['week_end_date']=df['date'].apply(lambda x: pd.Period(x,freq='W').end_time.date().strftime('%Y-%m-%d'))
#Aggregate sales and revenue at weekly level

df_agg = df.groupby(['datasource_name','id','week_end_date']).agg({'revenue':'sum','spend':'sum'}).reset_index()

df_agg will have all your sales and revenue numbers aggregated by the weekend date for corresponding date.
Comment: Thank you SAL, gave it a try, and the script works well. Do you have any advice on where to learn more about lambda functions and stringing functions?
Comment: you can use a function instead of a lamba if your code rules increase. lambda are anonymous functions, nothing more.
Comment: Hi SAL, thank you for your help! I will give it a try today and let you know how it turns out.
Comment: So the client came back and now wants the start of the week to be Sunday ie Sunday = 0 instead of Sunday = 6. Is there a way to change the lambda function to reflect a Sunday start date? I told them its likely not doable since Datetime is based off of internal time


Javascript: Select option based on its contents

Question: Basically this, but in pure javascript:
How to get 'value' of select tag based on content of select tag, using Nokogiri
I have a select list with a lot of countries/states, and I want to be able to select one based on what is between the <option> tags.
<option value="4783">Argentina</option>

(I know I could use the value, but each one is a random mesh of numbers, so I would have to collect each individual one - not economical)
Answer: It is a bit painful, but in pure JavaScript:
for(var i=0,sL=mySelObj.length;i<sL;i++){
  if(mySelObj.options[i].text == myValue){
    mySelObj.selectedIndex = i;
    break;
  }
}

Comment: painful in that you need to iterate over the list... meaning that if the desired value is the last item and there are 100's of items you have to check each before selecting the final option.  Where possible I would always try and pre-select the value at the server where "hopefully" determining the selected option at code generation time is easier.
Comment: Oh, I see. I thought you meant painful in comparison to other client-side solutions.
Answer: Now that querySelector is available in most browsers you can use:
document.querySelector('select').selectedIndex =
    document.querySelector('option[value=4783]').index;

Comment: If you know which browsers you need to support, you can check the support matrix for querySelector at http://caniuse.com/queryselector.
Answer: Just 10 years late, but let's look at a new age solution.
If you are working in ES6+ here is a simple "one liner" to do the trick.
If you require broad compatibility, use a transpiler or another solution.
let $select = document.querySelector('select[name="countries"]');
let compareValue = 'Argentina';

$select.value = [...$select.options].filter(option => {
    return option.innerText === compareValue;
})[0].value;

The true one-liner expression:
$select.value = [...$select.options].filter(option => option.innerText === compareValue)[0].value;

Answer: The textContent property lets you see what's inside the tag. Off my head and without testing, that should work:
function selectByDisplayValue(selectTag, displayValue)
{
    var options = selectTag.getElementsByTagName('option');
    for(var i = 0; i < options.length; i++)
        if(options[i].textContent == displayValue)
        {
            options[i].selected = true;
            break;
        }
}

Where selectTag is the DOM object of your <select> tag, and displayValue is the display value of the option you want to select (for your example, "Argentina" it would be).
Comment: `textContent` is a DOM Level 3 method that is not supported by IE (and some other minor or older browsers). For `Option` objects you can use `.text`, which goes way back to JavaScript 1.0.


How do I set up a nameserver to process ALL DNS requests?

Question: Is there any way I can set up a nameserver to process ALL DNS requests that come to my server and pass them on to backend servers regardless of whether I have a DNS entry for the target domain?
For example, even if I don't have a DNS entry for example.com, as long as a request for example.com comes to my server, it gets processed.
Currently, I have a a server running bind, which resolves all requests to its own IP. I have a load-balancer set up which forwards all the HTTP requests to one of many back-end servers. All my backend servers run apache2. Right now, I also have DNS entries on ALL my backend servers for all the domains I want them to process (because they're my backup nameservers). But I'm adding new domains all the time and don't want to add more DNS entries to ALL my servers each time each time I add a new domain...
I just want to get around having to add any DNS entries at all. ANY method of doing this would be appreciated.
Thanks!
Comment: You say you want the request for example.com to be processed... processed how? if it's going to return something, where should it get the something from?  A caching nameserver would just look it up in global DNS.  A proxy could forward the request to another nameserver and return whatever it gets back.  Need more info.
Comment: I think you need to clarify what you mean by "as long as a request for example.com comes to my server, it gets processed".
Answer: If you have a primary and set of "backup" nameservers, then why aren't you using DNS zone transfers (possibly with notification) to ensure that when you add an entry on the master DNS, the secondaries pick it up immediately?
Answer: In theory you should be able to setup com as the domain, and setup a DNS entry for * to point to the correct public IP.
Comment: But first read this: http://cr.yp.to/djbdns/com-wildcard.html
Comment: Figured it wasn't the best idea in the world.
Answer: "Caching nameserver" is what you're looking for, I assume. Just add a Forward instruction to your bind configuration, as explained in many tutorials and setup instructions, and you'll be fine.
Answer: I know what you want and I want it too. For those who are confused about this question, i think it means this:
Say I have 100 domain names. All have the same NS records: NSX.EXAMPLE.COM

I'm in charge of NSX.EXAMPLE.COM
I have just one zone file, with A record pointing to 10.0.0.1
I want ANY request that comes to NSX.EXAMPLE.COM to return data from that record.

Now, the main purpose of this question is to come up with a system that works when I decide to add another domain WITHOUT ANY MODIFICATION to the DNS server configuration.
I now register FOO.COM and point it to NSX.EXAMPLE.COM. This should be enough to make FOO.COM resolve to 10.0.0.1
Another way of looking at this would be like this:
If you BY MISTAKE query NSX.EXAMPLE.COM for any domain, it will respond with 10.0.0.1
Answer: I think, what you really want is a PowerDNS authoritative and recursor setup. But I'm not sure if the authoritative server will forward requests to the zones that it's authoritative for.
Just refer to the PowerDNS documentation at: http://downloads.powerdns.com/documentation/html/


Improving as a solo guitarist without learning scales

Question: I am a drummer of 20+ years.  I am a guitarist for only the last 5 or so (more of a guitar owner).  I can play many chords, and have composed a number of songs.  I learned to play drums without a mentor, and have continued the same way learning the guitar.
My weakness is that I haven't been able to improve playing solos.  I have written a number of passages which could be considered solos.  But playing these passages time and again starts feeling stale, because my progression is very fixed.  I refuse to learn scales.  I do realize that there is a great globe of musical theory and many schools of approach to learning all of these scales.  I choose not to learn the same way that a vast majority of guitarists have; if I drink the kool-aid, then surely my approach will be a not-too-distant relative of any number of guitarists.
And isn't the goal to not sound like everyone else?  I realize the irony of my question - how do I not do like so many others, but maybe do it like you?  I am looking for perspective.  Certainly there must be more than few of you who have learned to play the guitar (and solo) very well while ignoring the establishment of scales.
Comment: Scales are fundamental to music in general, not to particular artists.  "I refuse to learn scales." is like saying "I refuse to understand Physics.  If I jump off this building, I'm going to be _different_."  It might even work for a while, but you'll be able to improve whatever style you choose much more quickly if you at least have a feel for the mathematical way in which notes are fundamentally related.
Comment: Refusing to learn scales will lead to you "discovering" those scales yourself, but it will take a lot of time. Unless you are a true innovator. If so, learning stuff will not kill the ability to create. Music is plagued by the romantic notion that learning about the craft will somehow destroy the ability to create, something e.g. painting does not suffer from.
Comment: I wish someone asked you what style you play before answering. Maybe you work in the vein of Thurston Moore!
Comment: Jason - I'm going to clean up all the comments on this and the answers. In general, comments are for gaining clarity, not for conversations. [chat] is the place to go for that.
Answer: tl;dr: You can always guess what notes to play by ear and find what notes sound good, but at the end of the day you are playing in a scale and you should be aware of that.

There are some guitarists that don't know scale (or music theory for that matter) and they tend to play by ear. They listen to the progression and try to play something over it and find out what works and what doesn't. By doing this, they are picking a set of notes and musical ideas that sound good against a progression.
Unknowingly to them, typically they are playing inside a scale, they just don't know it. The definition of a scale is the following:

In music, a scale is any set of musical notes ordered by fundamental frequency or pitch.

If the set of notes the guitarist comes up with are pentatonic, modal, or experimental is irrelevant, it's still some type of scale. Any set of notes is a scale.  Typically even musicians who were never trained in formal music study tend to come up with musical ideas inside typical scales like major or minor without knowing it.
The theory behind scales is based on the practice and implementation. They will help you find what sound you like as there are many, many scales out there. Just because the standard scales don't interest you doesn't mean that there aren't any exotic scales you could really enjoy.
You seem to be equating scales with "boring" or "bland" solos and I would kind of agree with that, but in the bigger picture most good soloists don't stay in one scale the whole time. Combining multiple scales with chromatic and non-harmonic tones creates some of the most beautiful solos and I can guarantee most don't even think about it. They just do what sounds good. However looking at a solo you can analyse what they are doing and learn so much about what is going on and find what you like and what you don't like about it and use it to your advantage. This is how most guitarists get better and find out what sounds good and they use it where they see fit.
There are a lot of scales out there and many different ways to solo over a progression. You don't need to know every way, but anyone playing guitar should be aware that that you can break down a solo you like and most likely break sections down to sets of scales and arpeggios. It's not required, but it is a tool to improve you're playing and understanding what you like.
Answer: I think the most important thing you need is to learn how to dive in your guitar's neck without getting lost. Moving around past a certain speed and without watching where your fingers are requires tons of practice. That practice relies in repeating some pattern over and over and over.
You can try 1 million solos, practice them, improve and master them and you will get some dexterity from that. You can, however, learn a couple scales and then try a couple solos that are in that scale...life will be way easier then. You are learning from general to specific, and what you get by doing it that way is not just dexterity but knowledge about structures that you can reuse later to play other pieces or compose your own music.
Learning by imitation is a valid approach, but there may be better ways. Scales are just a tool you can use to improve. When people improvises without learning scales they are probably using them without knowing it.
With that said...Here is a post that tries to give reasons about why your music can feel stale.
Answer: You seem to be mistaken in thinking that playing scales means you have to play the same scales as everyone else - you don't.  In fact, even playing chords and/or arpeggios is a form of playing scales.
A scale is, informally, nothing more than a system of dividing a range of frequencies into discrete steps.
So saying you 'refuse' to learn scales is, in a way, saying you refuse to play tonally.  That's fine, but you will have to spend many years finding note combinations that do not sound bad to people, and training your fingers to find them reliably.  You may eventually come to realize that the majority of these combinations you come up with are identical to many common scales, and that you should have just played scales to begin with, but you will certainly find a great many uncommon scales that do not sound bad.
OTOH I think you might be well served by just skipping straight to learning unusual modes. That way, you have something to practice and you can improve much more quickly, but you won't be playing what everyone else is playing.
Comment: Well indeed those are useful but in modern usage are effectively permutations of the same scale (just with a different starting note).  While the literature doesn't really have a lot of common terminology and particular genres get stuck in particular modes, in a general sense a mode could be any combination of notes (& related chords)that evokes the sound of a particular 'world music', a particular emotion, or whatever other qualit(y/ies) you want it to have.  I believe Miles Davis, one of the early pioneers of modal improvisation, borrowed many of his modes from the study of ethnomusicology.
Answer: Not learning scales is like being a weightlifter who ignores leg day. They are in some ways the most boring thing you can do, but fundamental in more subtle ways than you may realize.
I would say scales are not important because they are the fundamental unit of music theory (which may be wrong but the first years of music theory pedagogy can imply it), but because scales are the fundamental unit of practice.
This is, in part, because they are boring.

You will never play a scale faster out of excitement or greater interest in a passage.
You will be able to count to play more evenly (even as an experienced drummer, because physically playing a new instrument can mess up your evenness).
You will hear every mistake you make in a scale because you are listening intently and not getting distracted by the enjoyment of the music.
You will learn to play every note as part of every key it belongs to.
You will know exactly how fast you can play in ideal, simple conditions.
You will improve at slowing down, practicing evenly, then speeding back up, evenly.

I think - at least to my level of knowledge - that learning guitar without a focus on theory is a very reasonable thing to do. But you do need a focus on practicing well, and I tried to answer why scales are a huge part of practicing well, regardless of their overemphasized role in theory.
Answer: There are plenty of arguments for learning scales, and some against. I've played with many,many musos (and loads of guitarists !!), some of whom know scales, some don't. It's often not possible to decide which camp an individual is in when they play. There are great players out there who play 'from the soul' and haven't a clue about scales, keys or theory of any sort. There's also some who know all the scales, but somehow, it doesn't help them to play brilliant stuff. Very good, yes, but not brilliant.
I think the crux of the matter is in being able to listen to a new piece, and realise pretty quickly which scale/s is/are being used. I know that I wasted an awful lot of time finding notes for particular tunes, that I could have saved if I'd known scales.Yes, they can be boring, and, let's face it, not many tunes have more than 3 or 4 consecutive notes such as you'd find in a scale. So why bother learning them ?
A new pupil wanted to learn to play like xxxx from xxxxxxx.  He used tabs but was confused. He tried to find the notes to solos by moving a fret at a time up and down. Once I'd shown him a minor pentatonic, and how to move it up and down into different keys, he appreciated the usefulness of knowing his scales.
Answer: I learned all the music theory I know (not much, but enough to get by), and a lot of great stuff about how chords (and thus solos) are built, from this pretty awesome...comic book: http://www.planetalkguitar.com/
The author is a professional guitarist who never worries about scales - the whole book is about chord tones (which like everything else in music, are related to scales). But you only learn about them so you can learn how to find your way around and between them where it matters, on the fretboard.
This is not a magic method or some sort of scam that purports to make you an amazing player without effort. This is a solid system that's based on real understanding - it just doesn't focus on learning scales and practicing them.
Chord tones are almost as fundamental as scales, it's not musical snake oil. But it does offer a clear pathway to improving as a guitarist and especially as an improviser, without the focus on scales I totally understand your dislike of.
Answer: The guitar neck is a featureless grid of notes. The vast majority of music is played in a key (which if you read about the history of music, and in particular pythagorean tuning, is fundamental to the way frequency ratios between notes work.)
You only need to learn one scale by rote: the pentatonic. That will give you a sense of where 'home' is on the neck for playing in a particular key. That will be an enormous boost to your tendency to find notes that sound right (i.e., not horribly discordant.)
I'll say that again. Learning one scale (the pentatonic) will give you a sense of where 'home' is on the neck.
What you choose to do next, is up to you. Once you've learned the pentatonic you will gradually find the additional notes to form the diatonic scale by ear yourself (for major and natural minor.) You will also find the various other notes that are frequently added as accidentals. These include sharp 6ths, 7ths for the harmonic and melodic minor, plus the sharp 3rd (rather less used, as it tends to force a key change into the major scale of the same root.) They also include the flat 3rd known as the Blue note.
You may prefer doing it this way than reading a book, but you're going to find the same notes everyone else has found. There are, after all, only 12 of them. Once you've learned the pentatonic, additional theory may possibly accelerate your learning of how to play. It will, however, definitely consolidate your learning and improve your knowledge of terminology.
But by avoiding the subject entirely, you're just making life hard for yourself unnecesarily. Learn the pentatonic, which is the most basic of rules. That will help you to move about in a key.
Once you know the rules, you will be in a much better position to break them. And music, like painting, is about knowing when to follow the established rules and when to break them. You can change key in a song. You can add in strange notes. But you need to do it just enough to keep your listeners on their toes. Follow the rules too much and they will get bored. But ignore the rules completely and you will just make undirected noise, which they won't like either.
Comment: Guitar fingerboards are hardly featureless - most have dot or marker patterns so we know where we are. The pentatonic you  mention is the minor, I guess, closely related, certainly physically on guitar,and musically, to major pent. Blue notes can be b3, b5 and b7.
Comment: @Tim Pentatonic Minor & Major are just modes of the same scale. If you've learned Am pentatonic in 2 octaves, you've learned Cmaj pentatonic, too, just start on a different note. I use the dots a bit, but I have 3 frets I call home: The ones where the 1st, 4th and 5th of the major mode of the key I'm playing in are on the G string. I can play all the notes of the tonic fret if I'm playing pentatonic and all the notes on all three frets if I'm playing diatonic. If the key moves up a semitone I mentally move the whole pattern up a semitone. But now the dots are in a different relative position.
Comment: I know that ! That's why it got mentioned ! A, for example, is always 5th fret, E string, usually 2nd marker. Bb is always between that dot and the next one up. So the landmarks are there to guide you, and their features should help.
Answer: I'm assuming you have a core tune you've written and you want to add a solo.  If so, then my suggestion is to put down the guitar, put on the headphones, and listen to the song for... weeks or months if that's what it takes.  Start to hear a solo in your head.  When you have a very accurate "sonic vision" of the solo you want, then grab the guitar and find the notes... rearrange them as needed so that it's easy to play... maybe tweak it as you stumble across interesting twists.  Etc.  The key is to use your imagination, and to be precise... listen again and again until that thing is painted in your brain with enough clarity that when you're digging for it on guitar, there is no "close enough."
If you want to improvise something cool on the spot... well, then you need to be a rare genius or you need to learn some theory and scales.
Answer: There are two parts to your question. One pertains to art in general, while the other relates to the specific craft of music.
With regards to art, generally speaking you need to become proficient in the standard ways of doing things in order to be capable of effectively forging new ground. A painter needs to know how to draw figures and landscapes before they can paint surrealistic art. A writer needs to know how to write a newspaper article or an essay before they can write a work of literature. Likewise, a musician needs to know how to play popular rock songs, blues, etc in order to have the tools and skills necessary to find your own voice.
With regards to scales. Most, if not all, musicians who improvise on guitar are using scales. Some of them know what scale they're using, while others don't. But generally improvised lines can be analyzed and it can be said "they're using such-and-such scale there." Now, many guitarists learn to play by ear, by imitating the solos of other guitarists. While others learn the keys and scales and learn it that way. So just pick whichever method is comfortable for you.
Answer: We're all trying to persuade you to play scales!  I'm going to too.  But don't play scales because the Berklee teachers have a method of faking improvisation by associating scales with chords.  Learn them to develop fluency, to learn where each pitch "is" on your instrument, so that when your ear wants "that" note, your fingers know where it is.  Play arpeggios as well.  Major, minor, dominant 7ths, dim 7th...   Now, buy the auto-accompaniment program Band-in-a-Box.  Enter the chord sequence to a song you want to work on.  Set the accompaniment to just bass and drums, tell it to loop forever.   Now sing a solo - hum, sing "la", whatever.  Keep it simple, we don't need a lot of notes.  Play what you sung. After all that scale and arpeggio practice, your fingers should KNOW where to go.
Answer: The idea that learning the scales will make you sound like everyone else is like saying you will write like Shakespeare if you learn the alphabet - scales, in some form, are just the foundation of 99.999% of all western music so, unless you are planning to play experimental noise music, all learning scales will do is make life so much easier for you. What you do with them is then up to you, and that is where your own voice comes in.
There are approaches that can help improvisation without learning scales - but again, if you know your scales you will make this a far easier process for yourself.
Take a chord and then play every possible note over it to hear how it sounds. Sometimes notes that are in the relative scale will sound spot on while others sound a bit off. Sometimes notes outside the parent scale will have their own interesting flavour. Then when soloing over that chord, use the notes that worked best or choose which flavour of note you are looking for at that point, rather than thinking necessarily about the parent scale.
That can be a very effective non-scalar way of approaching a solo, but again unless you know your scales you will struggle to transpose these ideas to other chords, or know which notes are which in relation to the chord, so you will massively restrict your ability to re-use this information and therefore hamper any progress.
Just learn the scales! Why make life hard for yourself?
Answer: Travel way back in time, before people realized there were notes that sounded good together when they tried to compose a melody. As best I can figure that's what you're interested in learning to do. Perhaps by studying that part of historical musical development you might find the answer you are looking for. But by doing so, you may actually discover the actual value of scales just like musicians from centuries past.
Then again you may discover something entirely new. That would be my suggestion. Some call it study and experimentation, and often find something that they didn't find before, but there's no guarantee some one else hasn't already found it and just didn't pursue it the way that you might choose too.
 Two days later I decide to edit my answer and add a thought that occurred to me this morning. There is an area of study called chord melody that focuses on using chords to make your melody lines with, it's generally used in jazz and can be considered pretty advanced stuff by many, but it might be just the ticket for you. Check it out.
Answer: Why refusing to learn scales? Besides if you are playing something that makes sense (sounds good) you are playing a scale for sure, whether you know it or not. Here is a nice A minor (C major) pentatonic diagram,just play a song in one of these keys and try playing tones in the diagram,there is no way it would not sound good or at least musical:

Made using Chords & Scales software.
Answer: Let me get this straight. You think that the way you play the guitar is unique lol. There isn't anything anyone could play on an instrument that hasn't been done billions of times before in tonal music. You are already playing scales whether you like it or not. You think you are playing by ear, but guessing witch notes sound right isn't really playing by ear. You will not develop your sense of relative pitch unless you know some form of scales. You don't have to know what those scales are called and you don't have to learn them formally but you have to learn them if you want to develop your ear and expand your knowledge and ability on your instrument. Not to be mean, but when I hear people like you say that they refuse to learn scales or any music theory because they want to be unique and they often think they have a very good ear for music, but I am here to tell you that that is completely backwards.
Usually people that don't know any scale patterns are the most predictable and stale musicians. I guarantee if I heard you play your licks and runs that you do right now, those runs would probably consist of notes from the most common scales used in American music such as the minor and major pentatonic scales.
Im not saying that's a bad thing, I am just saying that its far from unique, because every beginning guitarist in America and most of the world learn those scales first whether they are self taught or formally taught. Also one more thing, its not about what you play, its about how you play it. Like I said before every thing that you can think of has already been done in music billions of times, so if you think that not learning scales will make you a unique musician you are sadly mistaken.
Learning scales and harmony is the key to becoming a musician, and once you learn the Music Theory you will get so used to it that you don't have to think about it, and that more than anything is what can set you free as a musician
Comment: I agree with most things here. A suggestion is that you divide the answer in paragraphs, since it will improve readability.


How to judge whether model is overfitting or not

Question: I am doing video classification with a model combining CNN and LSTM. In the training data, the accuracy rate is 100%, but the accuracy rate of the test data is not so good. The number of training data is small, about 50 per class. In such a case, can I declare that over learning is occurring? Or is there another cause?
Answer: To me, accuracy on a training set makes no sense. I ignore it. If you want to test overfitting on training data, you can do this by cross-validation. For details, please see the link
Comment: When cross validation is carried out, what kind of accuracy rate value is given when the model is overfitting?
Comment: Please keep in mind that overfitting is not just a yes/not condition. Very different test and train accuracies mean that overfitting is serious.