text:
Q: External Provider Login in ASP Core, Identity Server 4 and Angular 2 I have an ASP Core App setup with Identity Server 4 that provides token based authentication for an Angular 2 SPA.
To Login, username and password is sent via a Http Post to the "/connect" endpoint of identity server.
I want to extend the login process to include External Providers (Google, Facebook & all) but all the resources i can find online speak of an "Account Controller" which is inside of an MVC app, which i do not have.
I have been able to setup the client side of this process (retrieve the id_token of a user from Google, on the Angular SPA), but i don't know how to continue .
Where do i send the Oauth id_token ? Do i use the Extension Grants ? How ?
Please note that i do not have an "Account Controller" Class, the login flow is done by Identity Server and the JWT is returned to the angular app. I need guidance or advice on how to take the Oauth id_token, gotten from External Providers like Google, send it to the ASP core backend and create a user for that id_token, so when next the user logs into the app from Google, the User object (Apllication User) is fetched for him.
My setup can be found at this repo : https://github.com/robisim74/AngularSPAWebAPI

A: For external providers you need the so called "implicit flow" - that's how it works. Check the quick start:
https://identityserver4.readthedocs.io/en/release/quickstarts/4_external_authentication.html


text:
Q: Why do the conditions $x_1+x_2=b$ and $x_1\cdot x_2=ac$ hold for any quadractic equation? Consider the equation $$ax^2+bx+c=0.$$ The factorization of the left hand side is of the form $(x+x_1)(x+x_2)$, where the solutions $x_1$ and $x_2$ must satisfy $$(1)\quad x_1+x_2=-\tfrac bc\quad\mbox{and}\quad(2)\quad x_1\cdot x_2=\tfrac ca.$$
I solve the equation by putting $$x_1=\tfrac12 b+k\quad\mbox{and}\quad x_2=\tfrac12 b-k.$$ This means (1) holds and by substitution into $(2)$, I get
$$(\tfrac12 b+k)(\tfrac12 b-k)=-ac\iff k^2=ac+\tfrac14 b^2.$$ This yields a solution for $k$, and then I can find $x_1$ and $x_2$.
I have been using this method with success and I like it a lot, since I always forget the quadratic formula. but I have no clue what I am doing. More specifically, why do the conditions (1) and (2) hold for any quadratic equation?

A: $(x + x_1)(x + x_2) = x^2 + (x_1 + x_2)x + x_1 x_2$. Now compare coefficients.

A: First of all there are lot of mistakes in your notation the quadratic equation should be factorized as:
$$ax^2 + bx + c = a(x-x_1)(x-x_2)$$
And we want to prove that the following holds:
$$x_1 + x_2 = -\frac ba \tag{1}$$
and
$$x_1x_2 = \frac ca \tag{2}$$
From the formula for quadratic equations we have:
$$x_{1/2} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
So WLOG let's have:
$$x_1 = \frac{-b + \sqrt{b^2 - 4ac}}{2a} \quad \quad \text {and} \quad \quad x_1 = \frac{-b - \sqrt{b^2 - 4ac}}{2a}$$
For $(1)$ just add this together:
$$x_1 + x_2 = \frac{-b + \sqrt{b^2 - 4ac}}{2a} + \frac{-b - \sqrt{b^2 - 4ac}}{2a} = - \frac{2b}{2a} - \frac ba \tag{1}$$
For $(2)$ just multiply them together:
$$x_1x_2 = \frac{-b + \sqrt{b^2 - 4ac}}{2a} \times \frac{-b - \sqrt{b^2 - 4ac}}{2a}$$
$$x_1x_2 = \frac{b^2 - (\sqrt{b^2 - 4ac})^2}{4a^2}$$
$$x_1x_2 = \frac{b^2 - b^2 - 4ac}{4a^2} = \frac{c}{a} \tag{2}$$
This relations are know as Vieta's Formulas and back at school, they taught us that this is how Vieta find out this relations.
Actually the Vieta's Formulas don't just hold for polynomials of second degree, they hold for polynomials of any degree. Consider the following polynomial:
$$P(x) = a_nx^n + a_{n-1}x^{n-1} +...a_1x + a_0x^0$$
The Vieta stated that the the $(n − k)^{th}$ coefficient $a_{n−k}$ is related to a signed sum of all possible subproducts of roots, taken $k-at-a-time$. Or using mathematical notation written as:
$$\sum_{1\le i_1\le i_2 \le i_3 ... \le i_k \le n} x_{i1}x_{i2}x_{i3}...x_{ik} = (-1)^k \frac{a_{n-k}}{a_n}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql запись в таблицу Можно ли записать в таблицу mysql вот также, мне нужно информацию отображать в ввиде текста:

A:
Можно ли записать в таблицу mysql вот также?

Нет, реляционная модель не позволит её нарушать


text:
Q: How to execute migration files from 2 different locations in TypeORM I want to execute migration scripts from 2 or more locations in my project, is there any way to do this?
below code contains the entry In my datasource.ts file.
const type = <DatabaseType>process.env.DB_TYPE || <DatabaseType>'postgres';

const AppDataSource = new DataSource(<DataSourceOptions>{
  type,
  url: process.env.DB_URL || 'postgresql://postgres:postgres@localhost:5432/postgres',
  synchronize: false,
  migrationsTableName: '_jackson_migrations',
  logging: ['error'],
  entities: ['src/db/sql/entity/**/*.ts'],
  migrations: ['migration/${type}/**/*.ts'],
});

current migration file path is migrations: [migration/${type}/**/*.ts],
and other path is migration/db/{mongo/sql}/*.ts
${type} is dynamic it can be pg,mysql or any other db
I tried this migrations: [migration/${type}/**/*.ts, migration/db/sql/*.ts] but it's not working.


text:
Q: Is the following set reflective, symmetric or transitive $R = \{(x,y) : x+ y \leq 2015 , x,y \in \mathbb{Z}\}$ is the following set reflective, symmetric or transitive $R = \{(x,y) : x+ y \leq 2015 , x,y \in \mathbb{Z}\}$
The set is transitive as $(1,2)$ is there $(2,1)$ is there and $(1,1)$ is there and so on..
It is reflective as $(1,1) \;\; (2,2)$ will be there an so on..
It is symmetric because $(1,2)$ will be there and $(2,1)$ will be there and so on.
Am I correct?

A: $(2000, 2000) \notin R$ - so $R$ is not reflective.
$(2000, 10) \in R$ and $(10, 2000) \in R$, but as noted above, $(2000, 2000) \notin R$, so $R$ is not transitive.
$R$ is symmetric, though - $(x, y) \in R \iff x + y \leq 2015 \iff y + x \leq 2015 \iff (y, x) \in R$.


text:
Q: How to stop a python subprocess which is running unit tests right away? Terminate and kill not working I have a Tkinter GUI running two threads, the main tread for the GUI and a worker thread. The worker thread creates a subprocess using the following code:
myProcess = subprocess.Popen(['python', '-u', 'runTests.py'],
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)

The file runTests.py does some setup and then runs a unit test file using the following command:
execfile('myUnitTests.py')

The file myUnitTests.py has several unit tests some that take over five minutes to run.
From the GUI I click a button to stop running the tests. This in turn makes the worker thread send a signal to stop the subprocess:
myProcess.terminate()

The terminate command does not stop the process right away, it waits until the current unit test finishes running and then it terminates the process?
I have tried to use os.kill but I get the same results as with terminate().
Any idea of how can I make my program more responsive so that it kill the subprocess right away?

A: The Python documentation [ http://docs.python.org/library/signal.html ] says:

*

*Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the "atomic" instructions of the Python interpreter. This means that signals arriving during long calculations implemented purely in C (such as regular expression matches on large bodies of text) may be delayed for an arbitrary amount of time.

So if your five-minute unit test is doing "a long calculation implemented purely in C", and your unit test harness installs a handler for SIGTERM, that's your problem.  If so, try myProcess.kill instead of myProcess.terminate (or, if you haven't got 2.6, myProcess.send_signal(9)).  SIGKILL is uncatchable from user space and should have immediate effect.
Warning: any clean-up actions that are supposed to run on the way out of your unit test framework will not be executed.


text:
Q: Azure ServiceBus SubscriptionClient.EndReceive() returns null I call BeginReceive() on a SubscriptionClient like this:
client.BeginReceive(new TimeSpan(6, 0, 0), new AsyncCallback(DownloadResults), null);

And in the DownloadResults() callback I call client.EndReceive() [client is a static member of the class]
static public void DownloadResults(IAsyncResult ar)
{
    // Get the message from the service bus.
    msg = client.EndReceive(ar);
    if (msg == null)
    {
        Console.WriteLine("Error!");
        return;
    }
}

Sometimes client.EndReceive() returns null. It's not very clear to me by looking at the MSDN page for SubscriptionClient.EndReceive() as to exactly when EndReceive() returns null. Is it because the timelimit I specified in BeginReceive() was exceeded? Or is it because there was an error?

A: It appears that if the time limit is exceeded, the callback is called. When we try to retrieve the message by calling SubscriptionClient.EndReceive(), null will be returned.
The default timeout value is one minute, and there is no way to set an infinite timeout. If you want an infinite timeout, you can call SubscriptionClient.BeginReceive() again if the message is null.
For example:
static public void DownloadResults(IAsyncResult ar)
{
    // Get the message from the service bus.
    msg = client.EndReceive(ar);
    if (msg == null)
    {
        // Start waiting for the message again.
        client.BeginReceive(new TimeSpan(6, 0, 0), new AsyncCallback(DownloadResults), null);
        return;
    }
}

Source: http://social.msdn.microsoft.com/Forums/windowsazure/en-US/b14587ce-3fc7-4b56-8a35-4f2c6babce26/servicebus-subscriptionclientendreceive-returns-null

A: The contract for Receive states that ServiceBus will not throw an Exception. When Receive/BeginReceive/ReceiveAsync times out, the call will do whatever it needs to do to return a value (such as execute your callback) and you will get back a null in a timeout situation.


text:
Q: wbadmin system state backup fails When trying to backup the system state to shared drive the backup fails. This share is a samba share.  The samba server is not on AD but I mapped a network drive so the credentials would be saved (Can't actually backup to the network drive, wbamin prevents that).  When I run the backup over it fails.  Both the log files mentioned in the output below are empty.  Any ideas?
PS C:\Users\Administrator> wbadmin start systemstatebackup -backuptarget:\\ny-back01\backups
wbadmin 1.0 - Backup command-line tool
(C) Copyright 2004 Microsoft Corp.

Starting to back up the system state [8/19/2010 1:41 PM]...
Retrieving volume information...
This will back up the system state from volume(s) System Reserved (100.00 MB),Local Disk(C:) to \\ny-back01\backups.
Do you want to start the backup operation?
[Y] Yes [N] No Y

Creating a shadow copy of the volumes specified for backup...
Please wait while system state files to back up are identified.
This might take several minutes...
Found (118) files.
Found (10194) files.
Found (14481) files.
Found (31086) files.
Found (36456) files.
Found (48828) files.
Found (69057) files.
Found (73761) files.
Summary of the backup operation:
------------------

The backup of the system state failed [8/19/2010 1:43 PM].
Log of files successfully backed up:
C:\Windows\Logs\WindowsServerBackup\Backup-19-08-2010_13-42-09.log

Log of files for which backup failed:
C:\Windows\Logs\WindowsServerBackup\Backup_Error-19-08-2010_13-42-09.log

The operation ended before completion.
The version does not support this version of the file format.
PS C:\Users\Administrator>

A: The default allocation method for *nix OS's (of allocating disk blocks only when they're needed) is throwing Windows Backup for a loop. You need to pre-allocate the space.
Add the strict allocate = yes to your smb.conf and give it a shot again. (See http://www.samba.org/samba/docs/man/manpages-3/smb.conf.5.html for details about the strict allocate option.)
I'm seeing some rumblings that indicate that turning on strict allocate, however, can make some Windows clients "time out" when asking to allocate very large files... Lovely. Trading one problem for another. Your mileage may vary.


text: Q: Trend Survey Statistical Tests I am designing a trend survey using a Likert style survey.  I have three opinion questions, each with the same choice of responses ranging from Not Likely to Very Likely. Are there any statistical tests I could use to analyze this data?


text:
Q: What is the best way to define a global constant in PHP which is available in all files? What is the best way to define a constant that is global, i.e., available in all PHP files?
UPDATE: What are the differences between constants and class constants? Can they be used interchangeably?

A: When you want to use global constants across PHP files, I feel a good practice is to use Object Oriented principles and define these in relevant classes.  Using the spl_autoload_register() function built into PHP, you can define all your later classes to extend the related "globals class" without worrying about including files manually everywhere.  All the later child classes of that globals class will always have access to the related global variables. (I say related because it's good design to have global constants in a class be related in some way, rather than everything grouped together with no rhyme or reason)

A: Define your constant in your top .php file, that will be included in all the other scripts. It may be your front controller, your config file, or a file created for this single purpose.
!defined('MY_CONST') && define('MY_CONST', 'hello');

A: do the following:
define("CONSTANT_NAME","value");

if you want to access this constant from other php files, you have to include it:
include_once("thefilewiththeconstant.php");

A: check this
<?php
//Global scope variables
$a = 1;
$b = 2;

 function Sum()
 {
global $a, $b;

$b = $a + $b;
 }

Sum();
echo $b;
?>

A: A better way is to check if the constant is assigned to anything and if it's not assigned to anything then assign it, else assign it to NULL and then assign it to your constant
defined("FOO") ? null : define("FOO", "BAR");

A: It depends. In your situation I would go for define() because it has a more compact syntax in usage. But define() can only hold scalar values in PHP < 7.0 In case you need i.e. an associative array you have no other choice then to go for $GLOBALS or use PHP >=7.0.
// Storing a single value works fine with define
define( 'ROOT_DIR', dirname(dirname(__FILE__)) . '/' );

// But not for complex data types like this array
$USERPIC_PARAMS = array(
            "user_root"       => "images/users",
            "padding_length"    => 8,
            "split_length"      => 4,
            "hash_length"         => 12,
            "hide_leftover"     => false
    );

// Then you need $GLOBALS
$GLOBALS['USERPIC_PARAMS']  = $USERPIC_PARAMS;
// Or in PHP >=7.0
define( 'USERPIC_PARAMS', $USERPIC_PARAMS );

// output your define
echo ROOT_DIR;
// output your $GLOBALS var
echo $GLOBALS['USERPIC_PARAMS'];
// output in PHP >=7.0 your constant
echo USERPIC_PARAMS;

A: Whichever file you create your constant(s) in, you will have to require/include it in the files you will be using them.
Otherwise you can use the $_SESSION global but that requires session initialization by session_start() at the beginning of your code in each of those files.


text:
Q: Are Launchpad bugs in a way moderated? Is Launchpad (in general) moderated?

*

*brainstorm is

*ask ubuntu is

*ubuntu answers is

what about ubuntu bugs?

A: Bug 45419 asks for a way for users to report posts/comments/content as spam or abuse.  At the moment there is no formal mechanism but you can as in #launchpad or file a support question against Launchpad itself.

A: For new bug reports on Launchpad the terminology is triaging, rather than moderating.
Triaging gives bugs a relative importance and priority, in addition to categorising them against the correct part of Ubuntu.  You can read more about the triaging facilities at:

*

*dev.launchpad.net/BugTriage
Occasionally (but very rarely) patent nonsense gets filed in Launchpad, in which case it is marked "Invalid"—being impossible to process further.  Marketing spam added as comments to existing bug reports may also be deleted.
Does that answer your query?  Is there any area that you're still interested in, or which you'd like expanding with more detail?

A: Is it moderated? Well depends upon what you mean by "Moderated". Is it customizable in regards to team creation and management? Yes, you can moderate your team(s) and/or project(s) on Launchpad. Quite easily too once you get the hang of it. But in general usage, difficult to say. Anyone can go look at the site and browse but to do anything you do actually have to register and confirm your account. From there it's pretty much "Have at it..." at least to me.

A: Mostly not. Launchpad relies heavily on the community: bad bug reports are marked as invalid and simply forgotten.
For bad comments theres no "report button" but you can request removal on Launchpad Answers atleast for spam.


text:
Q: Why can't I use Related Model created with same request in Laravel? I have one table in which I store password reset tokens. There are 4 fields in that table. They are user_id , token , created_at and updated_at.
What I want to do is, Check if user already has password reset token or not. If a user already has password reset token, I want to send an email with the same token. If a user does not have a token, I want to create token and then send the email.
Problem is, I can send the email if token is already created. But, I am getting the error Trying to get property of non-object (View: /var/www/html/project_name/resources/views/emails/passwordResetLink.blade.php).
Why can't I access the password reset token with $user->passwordResetLink->token directly after creating the record in the database? Here is my code.
$user = User::findByUsername(request('username'));
if($user)
{
    if(count($user->passwordResetLink))
    {
        $user->passwordResetLink->save();
    }
    else
    {
        $token = md5(str_random(16));

        $record = new PasswordReset;
        $record->user_id = $user->id;
        $record->token = $token;
        $record->save();
    }

    Mail::to($user)->send(New \App\Mail\PasswordResetLink($user));
    return 1;
}

I am trying to access user's password reset token using $user->passwordResetLink->token. It's working fine if the record is already created but not working if the record does not exist.
PS: I am using save() because touch() isn't working because I don't have id field in my password_resets table in the database. let me know what's wrong with the code. I know save() won't work as I am not updating anything!
UPDATE: I solved my error by replacing the Mail line to Mail::to($user)->send(New \App\Mail\PasswordResetLink(User::find($user->id)));.

A: You change a related model after loading the primary model, this will cause the relation of the primary model to be outdated, one could solve this by reloading the relationship.
In your case you could use:
$user->load('passwordResetLink');

before
Mail::to($user)->send(New \App\Mail\PasswordResetLink($user));

This will reload only the PasswordResetLink and prevent having to reload the whole object.


text:
Q: Mnesia: Will post-netsplit restores copy entire table? Under mnesia with majority tables, when a netsplit occurs, a fully consistent, connected system can be restored by setting the mnesia master nodes to the majority island, and restoring the minority tables from there. As Ulf Wiger puts it:

If mnesia discovers a split-brain situation, it will issue an event,
  "running partitioned network". One way to respond to this would be to
  set master nodes to the "island" that you want to keep, and then
  restart the other nodes. When they come back up, they will
  unconditionally load tables from the master nodes.

My question is whether the minority will copy the entire table from the majority or whether it will only copy those transactions that have occurred since the netsplit.
Note that I am not asking about Wiger's netsplit, but the default mnesia behavior of setting some master nodes and then restarting the other ones.


text:
Q: Spring data - webflux - Chaining requests i use reactive Mongo Drivers and Web Flux dependancies
I have a code like below.
  public Mono<Employee> editEmployee(EmployeeEditRequest employeeEditRequest) {
        return employeeRepository.findById(employeeEditRequest.getId())
                .map(employee -> {
                    BeanUtils.copyProperties(employeeEditRequest, employee);
                    return employeeRepository.save(employee)
                })
    }

Employee Repository has the following code
Mono<Employee> findById(String employeeId)

*

*Does the thread actually block when findById is called? I understand the portion within map actually blocks the thread.

*if it blocks, how can I make this code completely reactive?

*Also, in this reactive paradigm of writing code, how do I handle that given employee is not found?

A: Yes, map is a blocking and synchronous operation for which time taken is always going to be deterministic.
Map should be used when you want to do the transformation of an object /data in fixed time. The operations which are done synchronously. eg your BeanUtils copy properties operation.
FlatMap should be used for non-blocking operations, or in short anything which returns back Mono,Flux.
"how do I handle that given employee is not found?" -
findById returns empty mono when not found. So we can use switchIfEmpty here.
Now let's come to what changes you can make to your code:
  public Mono<Employee> editEmployee(EmployeeEditRequest employeeEditRequest) {

    return employeeRepository.findById(employeeEditRequest.getId())
        .switchIfEmpty(Mono.defer(() -> {
          //do something
        }))
        .map(employee -> {
          BeanUtils.copyProperties(employeeEditRequest, employee);
          return employee;
        })
        .flatMap(employee -> employeeRepository.save(employee));

  }


text:
Q: Transaction over Data abstraction layer(DAL: Data Access Layer) Currently I am working on a DAL design, I have concern regarding managing transaction in Business Layer(BL) while keeping it unaware of DB technologies.
For ex: I have two DAOs
SalesOrderDAO, SalesOrderItemDAO

At some point in BL I would like to call update/create method on both in a transaction:
// some where in BL
  SalesOrderDAO soObj = new SalesOrderDAO();
  SalesOrderItemDAO soiObj = new SalesOrderItemDAO();

  //transaction start
  soiObj.create(); // it could be update as well
  soObj.update();
  //on some condition transaction roll back

  //transaction end

How to acheive it?
Constraint:

*

*I am using Hibernate in DAL.

*I don't want my BL to be aware of Hibernate.

*Outside the DAL no one knows or should know what technology is being
used to access the DB

(Am I missing something?)

A: I did some research(after i received comment on question) I found spring have all I needed.
Say, in BL we have method: SomeBLMethod(), which does db operation using SalesOrderDAO, SalesOrderItemDAO and SomeBLMethod should be under transaction.
We need to do following to make Transaction work:

*

*Get the object of SalesOrderDAO, SalesOrderItemDAO implementation using spring @Autowired attribute and perform db opration using these attributes.

*Make SomeBLMethod transactional using sprint @Transactional attribute.

*The implementation of SalesOrderDAO, SalesOrderItemDAO should use @Autowired SessionFactory object

*We also need to do some spring configuration.(which you can find in following url)

Reference:

*

*Example: http://www.byteslounge.com/tutorials/spring-with-hibernate-persistence-and-transactions-example

*Spring Transaction Management Doc: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/transaction.html
PS: I am adding this answer to help others.


text:
Q: No consigo entender bien RegExp Intento obtener los parámetros de una URL cualquiera a través de un RegExp, pero me parece demasiado lioso lo que estoy leyendo y no me aclaro nada.
Ahora mismo tengo esto:
let u   = url.replace(new RegExp('^/'), '').split('/'),
let fc  = u.shift(), skin = u.shift(), path=u.join("/");
let fcb = fc.replace(new RegExp('?'),'').slit('?');

A partir de url, que es la URL completa con la que he de trabajar, se hace un RegExp para quitar de en medio todo salvo el nombre del archivo al que hacer referencia.
Yo intento dar con la forma de poder quitar también los parámetros que se pongan, es decir:
http://localhost:8080/social?param=cualquiera

Necesitaría obtener dicho param=cualquiera y separar 'social' de todo lo demás.
¿Cómo podría hacerlo?

A: Como dice @EugeniBejan en los comentarios, la clase URL provee de varios metodos para obtener información de la url, una posibilidad es usar searchParams:

const url = new URL('http://example.com/path/index.html?parametro1=un_valor&parametro2=otro_valor');

const parametros = {}

url.searchParams.forEach((e,i)=>parametros[i] = e);

console.log(parametros)

A: Si quieres obtener la parte final de la url, lo que serían los valores que siguea a ? lo más sencillo es usar location.search. En el ejemplo que pones al final de tu pregunta el resultado de location.searh sería ?param=cualquiera. Ahora, con el método splice(1), le eliminas el carácter inicial (?).
Pero si lo que quieres es usar una expresión regular puedes hacer esto
reg = /\?(\w+)=(\w*)$/;
cad = "http://localhost:8080/social?param=cualquiera";
valores= cad.match(reg);
console.log(valores[1]);  //param
console.log(valores[2]);  //cualquiera

La expresión regular busca el carécter ? seguido de cualquiera carácter una o más veces seguido de un signo igual y después otra serie de caracteres justo al final de la cadena ($, indica final de la cadena).
Como ves ? se debe escapar \? porque  es un carácter usado en las expresiones regulares.
Las expresiones regulares son estupendas pero al principio son liosas. Debes tener muy claro lo que buscas y ser capaz de definirlo para poder crear el patrón.
EDITO
Si además necesitas el nombre que precede a la cadena de parámetros, o sea, entre el último / y el ? puedes hacer esto:
reg = /\/([^\/]+)\?(\w+)=(\w*)$/;
cad = "http://localhost:8080/social?param=cualquiera";
valores= cad.match(reg);
console.log(valores[1]);  //social
console.log(valores[2]);  //param
console.log(valores[3]);  //cualquiera

Ahora buscas lo que siga a una barra invertida y esté antes de un ?. Pero esos caracteres no pueden contener a la barra, por eso se precede ésta del ^.
Y ya puestos a rizar el rizo si además quieres sacar lo que precede a "social" pues añades otra agrupación a la expresión regular
reg = /(^.*)\/([^\/]+)\?(\w+)=(\w*)$/;
cad = "http://localhost:8080/social?param=cualquiera";
valores= cad.match(reg);
console.log(valores[1]);  //http://localhost:8080
console.log(valores[2]);  //social
console.log(valores[3]);  //param
console.log(valores[4]);  //cualquiera

Ahora se coge todo lo que hat entre el principio de la cadena (^) y la última barra / , seguido de lo que no sean barras y están seguidos del carácter ?, segido de lo que venga antes del signo = y finalmente lo que sigue a este signo y el final de la cadena.
Aparte de solucionar el caso concreto con esta respuesta pretendo explicar un poco como funcionan las expresiones regulares, siguiendo el enunciado de tu pregunta. Espero que te haya servido.

A: Para conseguir separar la url de los parametros simple y llanamente tuve que utilizar esta expresión:
let cad = fc.match(/\?/m);
Así me da un Array de dos objetos con lo que hay delante y detrás de la ?


text:
Q: ALT world & Mega Pencil - what does my money get me? I've been playing Pokemon Picross for a little while, and enjoying it, but I've started to hit the pay wall now. The game doesn't seem to be very good at explaining what some of the higher priced unlocks will actually get you, and I'd like to make an informed decision before spending any real life money!
ALT world is 800 picrites:
I've done the ALT world tests, so know that it unlocks the slightly different types of puzzles, but how many puzzles do you get, and are there additional unlocks where you have to shell out more? (like the standard stages unlock)
Mega Pencil is 500 picrites:
Is this to play the one stage, or once I've purchased this can I play any of the Mega pencil stages. What is different about this puzzle?
The Nintendo e-store says that if I purchase 5000 picrites you will  be able to obtain Picrites for free in this shop, so about £28.78 of real life monies. Does this mean you get unlimited picrites once you hit this, or that they give you a one off bundle of x picrites?
Are there any other unlocks further in the game which require more picrites? (Other than the standard unlocking of the next world & unlocking Pokemon slots)

A: The Alt World:

Alt World is a repeat of all of the stages in the standard world, but with a twist. These puzzles are done a bit differently. All the puzzles in the standard world are duplicated so you can get Pokémon here if you haven't yet got them in the main world. Each stage also has its own set of challenges and Picrite rewards for completing them.
  However, while the Pokémon in each area is the same between worlds, the placement and order of them varies.

Regarding Picrites:

You have to spend 300 Picrites to get to the Alt World and 500 Picrites to get the Mega Pencil to complete Mega Evolved Pokémon stages.

So you have to buy the Mega Pencil just once.
And about micro-transactions:

You can only purchase up to 5,000 Picrites in the lifetime of the game. Once you have done this, however, you'll be able to get free Picrites. You'll then be given them in batches of 1,000 until you hit 8,000 in your pack preventing you from running out of them at any time in the future game play.

Source Serebii.


text:
Q: Is there way to know if ODD number can be expressed as sum of two primes? I'm solving problem and I need your help, I know that every even integer can be expressed as sum of two primes and every integer can be expressed as sum of three primes. (for all integers <= 2 * 10^9)
But I want to know is there a way to check can we express odd number as sum of two primes.
Thanks in advance.

A: To make the sum of two numbers odd, one of the numbers must be odd and the other even. There is only one even prime, so that limits you to sums of the form $2+p$. Thus the odd numbers that are the sum of two primes are exactly the ones that are two more than a prime. The first few are
$$
5, 7, 9, 13, 15, 19, 21, 25, 31, 33, 39, 43\ldots
$$
Also note that it is not known whether every even number is the sum of two primes. Every single even number that has been checked has been verified to be the sum of two primes, but we don't know whether it is always true.

A: Note that every prime is odd, with the exception of 2, and also note that an odd number plus an odd number yields an even number. So if we have an odd number ( a prime) and we want to generate another odd number through addition, we have to add an even number. This means that the only odd numbers expressible as a sum of two primes are numbers of the form p+2, where p is a prime number.
The first odd number greater than one that can't be written as a sum of two primes is 3.

A: Sure; if $n-2$ is prime, then yes, otherwise not.
Adding two numbers to get an odd number requires that one of them is odd and the other even, but since there is only one even prime ($2$), the test is simple.


text:
Q: How to best create a test DB when doing TDD? what's the best practice for creating test persistence layers when doing an ASP.NET site (eg. ASP.NET MVC site)?
Many examples I've seen use Moq (or another mocking framework) in the unit test project, but I want to, like .. moq out my persistence layer so that my website shows data and stuff, but it's not coming from a database. I want to do that last. All the mocking stuff I've seen only exists in unit tests.
What practices do people do when they want to (stub?) fake out a persistence layer for quick and fast development? I use Dependency Injection to handle it and have some hard coded results for my persistence layer (which is really manual and boring).
What are other people doing? Examples and links would be awesome :)
UPDATE
Just a little update: so far I'm getting a fair bit of mileage out of having a fake repository and a SQL repository - where each class implements an interface. Then, using DI (I'm using StructureMap), I can switch between my fake repository or the SQL repository. So far, it's working well :)
(also scary to think that I asked this question nearly 11 months ago, from when I'm editing this, right now!)

A: Assuming you're using the Repository pattern from Rob Conery's MVC Store Front:
http://blog.wekeroad.com/mvc-storefront/mvc-storefront-part-1/
I followed Rob Conery's tutorial but ran into the same want as you. Best thing to do is move the Mock Repositories you've created into a seperate project called Mocks then you can swap them out pretty easily with the real ones when you instantiate your service. If your feeling adventurous you could create a factory that takes a value from the config file to instantiate either a mock or a real repository,
e.g.
public static ICatalogRepository GetCatalogRepository(bool useMock)
{
     if(useMock)
          return new FakeCatalogRepository();
     else
          return new SqlCatalogRepository();
}

or use a dependency injection framework :)
container.Resolve<ICatalogRepository>();

Good luck!
EDIT: In response to your comments, sounds like you want to use a list and LINQ to emulate a db's operations e.g. GetProducts, StoreProduct. I've done this before. Here's an example:
public class Product
{
     public int Identity { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     //etc
}

public class FakeCatalogRepository()
{
     private List<Product> _fakes;

     public FakeCatalogCatalogRepository()
     {
          _fakes = new List<Product>();

          //Set up some initial fake data
          for(int i=0; i < 5; i++)
          {
              Product p = new Product
              {
                 Identity = i,
                 Name = "product"+i,
                 Description = "description of product"+i
              };

              _fakes.Add(p);
          }
     }

     public void StoreProduct(Product p)
     {
         //Emulate insert/update functionality

         _fakes.Add(p);
     }

     public Product GetProductByIdentity(int id)
     {
          //emulate "SELECT * FROM products WHERE id = 1234
          var aProduct = (from p in _fakes.AsQueryable()
                         where p.Identity = id
                         select p).SingleOrDefault();

          return aProduct;
     }
}

Does that make a bit more sense?

A: Boring or not, I think you're on the right track.  I assume you're creating a fakeRepository that is a concrete implementation of your IRepository which in turn is injected into your service layer.  This is nice because at some point in the future when you're happy with the shape of your entities and the behavior of your services, controllers, and views, you can then test drive your real Repositories that will use the database to persist those entities.  Of course the nature of those tests will be integration tests, but just as important if not more so.
One thing that may be less boring for you when the time comes to create your real repositories is if you use nHibernate for your persistence you will be able let nhibernate generate your database after you create the nhibernate maps for your entities,  assuming you don't have to use a legacy schema.
For instance, I have the following method that is called by my SetUpFixture to generate my db schema:
public class SchemaBuilder
{
   public static void ExportSchema()
    {
        Configuration configuration = new Configuration();
        configuration.Configure();
        new SchemaExport(configuration).Create(true, true);
    }
}

and my SetUpFixture is as follows:
[SetUpFixture]
public class SetUpFixture
{
    [SetUp]
    public void SetUp()
    {
        SchemaBuilder.ExportSchema();
        DataLoader.LoadData();
    }
}

where DataLoader is responsible for creating all of my seed data and test data using the real respoitory.
This probably doesn't answer your questions but I hope it serves to reassure you in your approach.
Greg

A: I've gone the route of creating tables and data during a setup method in a unit test class, running tests, then doing clean up during the teardown.  Yes, this method works, but if you really end up using your unit tests for debugging purposes, invariably you will run the setup, debug something then stop in the middle without doing the teardown.  It's very brittle and you will probably end up (in the long run) with bad data in your test database and/or unusable unit tests.  I personally think its best to mock the database layer using a mocking framework.  I do understand that sometimes it's best to do logic in the database.  For these cases you can use a tool like DBFit to write tests for your database layer.

A: Although I'm not using Asp.Net or the MVC framework I do have the need to test services without hitting the database. Your question triggered the writing up of a short (ok, maybe not so short) summary of how I do it. Not claiming it's the best or anything, but it works for us. We access data through a repository and when required we plug in an in-memory repository as explained in the post.
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/14/testable-data-access-with-the-repository-pattern.aspx

A: I am using a complete in memory database with SQLite and ActiveRecord. Basically we delete and re-create the database before every integration test is being run, so that the data is always in a known state. The contents of the database are inserted through code. So an example would be like this:
ActiveRecord.Initalize(lots of parameters)
ActiveRecord.DropSchema();
ActiveRecord.CreateSchema();

and then we just add lots of customers or whatever, DDD style:
customerRepository.Save(customer);

Another way to solve this could be using NDbUnit to maintain the state of the database.

A: I know this question is a bit old, but I've finally come up with an answer :)
Firstly, use RavenDb (Embedded). It's part of the RavenDb Document Database. Its a fully in memory database and works perfectly with unit tests :) I've done it with MSTest, NUnit and xUnit.
Secondly, you can use NHibernate with SqlLite if you don't want to use RavenDb. Ayende has a post about using this.


text:
Q: Непонятное поведение JS ВОПРОС ПОПРАВЛЕН И УТОЧНЕН!
Есть код, где переключение между ссылками очищает "результирующий" div. Но только пытаюсь сделать ссылку "постраничности", то очистка происходит, но окно закрывается. Голову уже сломал куда копать - ведь ситуации идентичны, даже вызовы методов пробовал реализовать один в один, все равно окно исчезает. Окно - это всплывающий div.
Если очистку отключить, то результат на фото. Если включить div становится скрытым, но при нажатии на показ в div находится нужный результат. Почему же становится не видимым. Еще хочу добавить, что при дебаге блок не исчезает, а отрабатывает как нужно.
Это код с очисткой (пробовал разные методы - здесь 2 варианта)
if (clear_box) {
    box_result.html("");

   /* box_result.remove();
   $('.nc_result').append("

");
    box_result = $('#notify_body');*/

}

добавил пример работающей ссылки на фото без очистки.

A: Нашел причину, у меня в методе при необходимости идет запрос на сервер, в это время и возникает проблема, отправил выполнение метода через другой с задержкой в 1 миллисекунду. Заработало. НО ПО МНЕ ЭТО ОГРОМЕННЫЙ КОСТЫЛЬ. Буду структуру кода менять. Всем спасибо


text:
Q: check if date is valid In my program I have the user input a date in the format of "Month Day" (example May 25) and I want to be able to print an error message if it is an invalid date (example February 30).
So here's some code
$start_date = ARGV[0];
my $year = DateTime->now->year;                                          # adds a year to the date
my $date_parser = DateTime::Format::Strptime->new(pattern => '%Y %B %d', # YYYY Month DD
);
my $start_epoch = $date_parser->parse_datetime("$year $start_date")->epoch();

Right after this I need some kind of if statement right?

A: If the date is invalid, then the parser will return undef. You will see this quite quickly if you do:
my $start_date = "Feb 30";
my $year = DateTime->now->year;                                          # adds a year to the date
my $date_parser = DateTime::Format::Strptime->new(pattern => '%Y %B %d', # YYYY Month DD
);
my $start_epoch = $date_parser->parse_datetime("$year $start_date")->epoch();

The solution:
my $parsed =  $date_parser->parse_datetime("$year $start_date");
if ( not defined $parsed ) { print "Error - invalid date\n"; }

A: From perlmonks:

use Time::Local;
my $date = ' 19990230'; # 30th Feb 1999
$date =~ s/\s+$//;
$date =~ s/^\s*//;
my ($year, $month, $day) = unpack "A4 A2 A2", $date;
eval{
    timelocal(0,0,0,$day, $month-1, $year); # dies in case of bad date
+
    1;
} or print "Bad date: $@";

This should do you justice


text:
Q: How can I provide options inside slots with Watson Assistant I want to get multiple information from a certain node using slots.
One thing is, I want to give options for some of the questions I prompt.
Example: the user will make a reservation. I'm capturing date and time with the slot, and also where does he want the table. For the table part, I would like to provide him with two options "inside" or "outside".
Is that possible using slots?

A: This feature is coming soon. At this point, you need to export the entire workspace json and manually edit it there, we don't have GUI support just yet.


text:
Q: How to disable a button on user change in Login form I have a scenario where I have a login application like below

*

*When user is set to Faculty then Form 2 -> button1 should get disabled

*When user is set to Admin then Form 2 -> button1 should get enabled

How to achieve this using C# windows application ?

A: Set the 'Modifiers' property of the Form2 -> button1 to Public. Then add this code to the Click event of the login button:
    Form_2 frm=new Form_2();
    If(comboBoxUser.SelectedItem=="Faculty")
    {
            frm.button1.Enabled=false;
    }
    else
    {
            frm.button1.Enabled=true;
    }


text:
Q: How to set responsively images on images to appear fixed using HTML+CSS+JS? I got a task where I have to rewrite an old Adobe Flex application in HTML, CSS, JavaScript.
It is an application for customers to demonstrate our product with several images (images on images, so let's say we have png files for background, house and stickfigures) and the images change based on interaction with the user.
For my example let's just have a background and two stickfigures.
The background should always take 100% of the width. As we resize the browser the stickfigures should stay always at the same place on the background.
At my first try

Trying this way the top: xx%; doesn't seem to work, so I googled a bit and added height: 512px; to my container class. After that the 'top' worked, but as I resize the web browser the stickfigures move around on the background.

Any help, clue, idea is really appreciated, please ask if something is not clear.

A: I made some changes in your exemple :
HTML

CSS
.container {
    position: relative;
    width: 100%;
    height: auto;
}
.my-background {
    position: relative;
    left: 0;
    top: 0;
    width: 100%;
    height:auto
}
.stickfigures {
    position: absolute;
    z-index: 10;
}
.jane {
    left: 5%;
    top:20%;
    width: 20%;
}
.james {
    left: 60%;
    top:50%;
    width: 15%;
}

Please see the demo : JSFiddle


text:
Q: Variables being set to wrong value I'm having an issue with calculations being off inside my function. I'm using VB6, which may be my first problem. What's happening is I'm iterating through a loop, stepping from one variable to another variable, stepping by a variable, calculating every discount for an item. It puts each of those calculated discounts in a text file lookup table. If the value the user feeds it is between those 2 values, that's the discount it applies.
The problem comes in calculating out the discount value. Let's say I'm discounting .04 dollars per unit per step. So the first step's discount would be .04, then .08, then .12, etc. To calculate this, it counts the number of steps to go through the specified range and then multiplies the steps by the discount per step value. That's the main problem. When I do that, I get a floating point rounding error. I multiply the total steps (1) by the total discount (.04) and get .03999999999999999.
This wouldn't be a huge issue but because it calcs this out multiple times and adds calculations into calculations I can't have this loss of precision, it's throwing off my values later down the road. How do I avoid this type of rounding error?
Also it's worth noting that my values that I'm assigning are doubles and singles, could this attribute to the problem?
TL;DR: 1 * .04 = .03999999999999 in VB6 for some reason. Even if I assign a floating point variable = 15.1, it becomes = 15.1000003814697. How would I go about fixing this?

A: Both floating point value types (Single and Double) have this issue, due to the way they are represented in memory as two parts: a mantissa and an exponent. If you want integer-like precision, then you must use the Decimal subtype. VB6 does not support this type directly. For instance, you can't write:
Dim decValue As Decimal
decValue = 1.536

Instead, Decimal is supported via the Variant type, e.g.
Dim vdecValue As Variant
vdecValue = CDec (1.536)

The upside is you get the precision you want. The downside is that each value takes up 14 bytes rather than 4 or 8. You are also limited to functions which accept Variant/Decimals.
It is a shame that you haven't provided an algorithm. It is quite possible that you could fix the rounding problems up front. For instance, if your discount was in a known range, and a known precision, e.g., 0.11 to 0.95, you could keep track of the total discount as hundredths of a whole value. You total up the hundredths as Integer/Long values, and only convert to Single/Double at the last possible point. Obviously, this only works if you don't need a running total. Ironically, this "assumed decimal point" is exactly how VB represents Currency and Decimal values.


text:
Q: In MVC should a model handle validation? I am trying to re-architect a web application I developed to use the MVC pattern, but I'm not sure if validation should be handled in the model or not. For example, I'm setting up one of my models like this:
class AM_Products extends AM_Object
{
    public function save( $new_data = array() )
    {
        // Save code
    }
}

First Question: So I'm wondering if my save method should call a validation function on $new_data or assume that the data has already been validated?
Also, if it were to offer validation, I'm thinking some of the model code to define data types would look like this:
class AM_Products extends AM_Object
{
    protected function init() // Called by __construct in AM_Object
    {
        // This would match up to the database column `age`
        register_property( 'age', 'Age', array( 'type' => 'int', 'min' => 10, 'max' => 30 ) );
    }
}

Second Question: Every child class of AM_Object would run register_property for each column in the database of that specific object. I'm not sure if this is a good way of doing it or not.
Third Question: If validation should be handled by the model, should it return an error message or an error code and have the view use the code to display an appropriate message?

A: I do not completely agree with "back2dos": My recommendation is to always use a separate form/validation layer, that the controller can use to validate input data before it's sent to the model.
From a theoretical standpoint, model validation operates on trusted data (internal system state) and should ideally be repeatable at any point in time while input validation explicitly operates once on data that comes from untrusted sources (depending on the use case and user privileges).
This separation makes it possible to build reusable models, controllers and forms that can be loosely coupled through dependency injection. Think of input validation as whitelist validation ("accept known good") and model validation as blacklist validation ("reject known bad"). Whitelist validation is more secure while blacklist validation prevents your model layer from being overly constrained to very specific use cases.
Invalid model data should always cause an exception to be thrown (otherwise the application can continue running without noticing the mistake) while invalid input values coming from external sources are not unexpected, but rather common (unless you got users that never make mistakes).
See also: https://lastzero.net/2015/11/why-im-using-a-separate-layer-for-input-data-validation/

A: First Answer: A key role of the model is to maintain integrity. However processing user input is a responsibility of a controller.
That is, the controller must translate user data (which most of the time is just strings) into something meaningful. This requires parsing (and may depend on such things as the locale, given that for example, there are different decimal operators etc.).
So the actual validation, as in "is the data well formed?", should be performed by the controller. However the verification, as in "does the data make sense?" should be performed within the model.
To clarify this with an example:
Assume your application allows you to add some entities, with a date (an issue with a dead-line for example). You might have an API, where dates might be represented as mere Unix time stamps, while when coming from a HTML page, it will be a set of different values or a string in the format of MM/DD/YYYY. You don't want this information in the model. You want each controller to individually try to figure out the date. However, when the date is then passed to the model, the model must maintain integrity. For example, it might make sense to not allow dates in the past, or dates, that are on holidays/sundays, etc.
Your controller contains input (processing) rules. Your model contains business rules. You want your business rules to always be enforced, no matter what happens. Assuming you had business rules in the controller, then you'd have to duplicate them, should you ever create a different controller.
Second Answer: The approach does make sense, however the method could be made more powerful. Instead of the last parameter being an array, it should be an instance of IContstraint which is defined as:
interface IConstraint {
     function test($value);//returns bool
}

And for numbers you could have something as
class NumConstraint {
    var $grain;
    var $min;
    var $max;
    function __construct($grain = 1, $min = NULL, $max = NULL) {
         if ($min === NULL) $min = INT_MIN;
         if ($max === NULL) $max = INT_MAX;
         $this->min = $min;
         $this->max = $max;
         $this->grain = $grain;
    }
    function test($value) {
         return ($value % $this->grain == 0 && $value >= $min && $value <= $max);
    }
}

Also I don't see what 'Age' is meant to represent, to be honest. Is it the actual property name? Assuming there's a convention by default, the parameter could simple go to the end of the function and be optional. If not set, it would default to the to_camel_case of the DB column name.
Thus the example call would look like:
register_property('age', new NumConstraint(1, 10, 30));

The point of using interfaces is that you can add more and more constraints as you go and they can be as complicated as you want. For a string to match a regular expression. For a date to be at least 7 days ahead. And so on.
Third Answer: Every Model entity should have a method like Result checkValue(string property, mixed value). The controller should call it prior to setting data. The Result should have all the information about whether the check failed, and in case it did, give reasons, so the controller can propagate those to the view accordingly.
If a wrong value is passed to the model, the model should simply respond by raising an exception.

A: Yes, the model should perform validation. The UI should validate the input, too.
It's clearly the responsibility of the model to determine valid values and states. Sometimes such rules change often. In that case I'd feed the model from metadata and/or decorate it.

A: Great question!
In terms of world wide web development, what if you asked the following, also.
"If bad user input is supplied to a controller from a user interface, should the controller update the View in a kind of cyclic loop, forcing commands and input data to be accurate before processing them? How? How does the view get updated under normal conditions? Is a view tightly coupled to a model? Is user input validation core business logic of the model, or is it preliminary to it and thus should occur inside the controller (because user input data is part of the request)?
(In effect, can, and should, one delay instantiating a model until good input is acquired?)
My opinion is that models should manage a pure and pristine circumstance (as much as possible), unencumbered by basic HTTP request input validation that should occur before model instantiation (and definitely before the model gets input data). Since managing state data (persistent, or otherwise) and API relationships is the world of the model, let basic HTTP request input validation occur in the controller.
Summarizing.
1) Validate your route (parsed from the URL), as the controller and method must exist before anything else can go forward. This should definitely happen in the front-controller realm (Router class), before getting to the true controller. Duh. :-)
2) A model may have many sources of input data: an HTTP request, a database, a file, an API, and yes, a network. If you are going to place all of your input validation into the model, then you consider HTTP request input validation part of the business requirements for the program. Case closed.
3) Yet, it is myopic to go through the expense of instantiating lots of objects if the HTTP request input is no good! You can know if ** HTTP request input** is good (that came in with the request) by validating it before instantiating the model and all its complexities (yes, perhaps even more validators for API and DB input/output data).
Test the following:
a) The HTTP request method (GET, POST, PUT, PATCH, DELETE ...)
b) Minimum HTML controls (do you have enough?).
c) Maximum HTML controls (do you have too many?).
d) Correct HTML controls (do you have the right ones?).
e) Input encoding (typically, is the encoding UTF-8?).
f) Max input size (is any of the input wildly out of bounds?).
Remember, you may get strings and files, so waiting for the model to instantiate could get very expensive as requests hit your server.
What I have described here hits at the intent of the request coming in through the controller. Omitting the verification of intent leaves your application more vulnerable. Intent can only be good (playing by your fundamental rules) or bad (going outside your fundamental rules).
Intent for an HTTP request is an all or nothing proposition. Everything passes, or the request is invalid. No need to send anything to the model.
This basic level of HTTP request intent has nothing to do with regular user input errors and validation. In my applications, an HTTP request must be valid in the five ways above for me to honor it. In a defense-in-depth way of speaking, you never get to user input validation on the server-side if any these five things fail.
Yes, this means even file input must conform to your front-end attempts to verify and tell the user the max file size accepted. Only HTML? No JavaScript? Fine, but the user must be informed of the consequences of uploading files that are too big (chiefly, that they will lose all form data and be kicked out of the system).
4) Does this mean that HTTP request input data is not part of the business logic of the application? No, it just means computers are finite devices and resources must be used wisely. It makes sense to stop malicious activity sooner, not later. You pay more in compute resources for waiting to stop it later.
5) If the HTTP request input is bad, the entire request is bad. That is how I look at it. The definition of good HTTP request input is derived from the business requirements of the model, but there must be some point of resource demarcation. How long will you let a bad request live before killing it and saying, "Oh, hey, never mind. Bad request."
The judgement is not simply that the user has made a reasonable input mistake, but that an HTTP request is so out-of-bounds that it must be declared malicious and stopped immediately.
6) So, for my money, the HTTP request (METHOD, URL/route, and data) is either ALL good, or NOTHING else can proceed. A robust model already has validation tasks to concern itself with, but a good resource shepherd says "My way, or the high way. Come correct, or do not come at all."
It is your program, though. "There is more than one way to do it." Some ways cost more in time and money than others. Validating HTTP request data later (in the model) should cost more over the lifetime of an application (especially if scaling up or out).
If your validators are modular, validating basic *HTTP request input** in the controller should not be a problem. Just use a strategized Validator class, where validators are sometimes composed of specialized validators, too (e-mail, phone, form token, captcha, ...).
Some see this as completely wrong headed, but HTTP was in its infancy when the Gang of Four wrote Design Patterns: Elements of Re-usable Object-Oriented Software.
==========================================================================
Now, as it pertains to normal user input validation (after the HTTP request has been deemed valid), it is updating the view when the user messes up that you need to think about! This kind of user input validation should occur in the model.
You have no guarantee of JavaScript on the front-end. This means you have no way to guarantee asynchronous updating of your application's UI with error statuses. True progressive enhancement would cover the synchronous use case, too.
Accounting for the synchronous use case is an art that is being lost more and more because some people do not want to go through the time, and hassle, of tracking the state of all their UI tricks (show/hide controls, disable/enable controls, error indications, error messages) on the back-end (usually by tracking state in arrays).
Update: In the diagram, I say that the View should reference the Model. No. You should pass data to the View from the Model to preserve loose coupling.


text:
Q: How to animate a typing text effect in javascript Written some script to give the effect of typing text but I want each character to fade in. Ive tried adding x.style.opacity and getting the element by Id but this changes the whole thing is there any way to target the individual characters? Here is my code:
var i = -1;
var string = "BREAKING NEWS "
var array = string.split("");

function Next(){
i++;
if(i > (array.length - 1)){
    i = 0;
}
setTimeout('Slide()',50);
 }

 function Slide(){
x = document.getElementById('test')
x.innerHTML += array[i];

setTimeout('Next()',50);

}

A: You can't target single characters you need to wrap them in a tag, like span:
DEMO
function Slide() {
    var sp = document.createElement('span');
    sp.setAttribute('class', 'fadein');
    sp.appendChild(document.createTextNode(array[i]));
    x.appendChild(sp);
    setTimeout('Next()', 50);
}

and you can animate them with css animations
.fadein {
    animation: fadein 2s;
}
@keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}


text:
Q: how to get post data in Magento Model File - Magento 2x I want to get POST data in Model file, Which is my custom file of AccountManagement
/app/code/[Vendor]/[Module]/Model/AccountManagement.php

Note:

I can access it through $_POST, 'superglobal'  variable but i don't wanna use it that way, Because it's not valid for Magento standard.
Because Magento use to featch POST and REQUEST data using this method in Controller.
$this->postData = $this->getRequest()->getPostValue();

But i am not able to use same method in Model file.
So anyone have any idea to fetch POST data in Model file IN Magento 2x, As per Magento Standard

A: Please try below code. We will inject Http class in the constructor and use that to get post data. This is a standard way of Magento 2
<?php
namespace Namespace\Module\Model;
class ModelClassName
{
    protected $request;
    public function __construct(
        \Magento\Framework\App\Request\Http $request,
    ) {
       $this->request = $request;
    }
    public function getPost()
    {
        return $this->request->getPost();
    }
}

A: Just for reference, it worked for me.
$this->getRequest()->getPost()

Or add Magento\Framework\App\RequestInterface to the constructor parameters in your own classes:
<?php
namespace MyModuleNameSpace\MyModule\Block
use Magento\Framework\App\RequestInterface;

class MyClass
{
    /**
     * Request instance
     *
     * @var \Magento\Framework\App\RequestInterface
     */
    protected $request;

    /**
     * @param RequestInterface $request
     */
    public function __construct(RequestInterface $request)
    {
        $this->request = $request;
    }

    public function getMyPostParams()
    {
        $postData = $this->request->getPost();
    }
}


text:
Q: Simplifying compound fraction not producing answer provided by book I am working on a problem in a textbook(Precalculus Mathematics for Calculus, by James Stewart) and the answer in the back of the book for the problem(1.4 #67) is -xy but I am not getting that. Here is the problem:
\begin{align}
\frac{\frac{x}{y}-\frac{y}{x}}{\frac{1}{x^2}-\frac{1}{y^2}}
\end{align}
Here is how I worked it out:
\begin{align}
\frac{\frac{x}{y}-\frac{y}{x}}{\frac{1}{x^2}-\frac{1}{y^2}}=\frac{\frac{x^2-y^2}{xy}}{\frac{y^2-x^2}{x^2y^2}}=\frac{x^2-y^2}{xy}*\frac{x^2y^2}{y^2-x^2}
=\frac{xy(x^2-y^2)}{y^2-x^2}=\frac{(xy)(x+y)(x-y)}{(y+x)(y-x)}=\frac{xy(x-y)}{y-x}=\frac{x^2y-xy^2}{y-x}
\end{align}
Can someone please explain what I am doing wrong here?

A: You were almost there. $\frac{xy(x-y)}{y-x}$(your second last one)$=-xy$


text:
Q: GoogleCobal (Free Version) - Working with PySpark with Hive
AnalysisException                         Traceback (most recent call last)
 in
----> 1 spark.sql('''CREATE TABLE employees (
2     employee_id INT,
3     employee_first_name STRING,
4     employee_last_name STRING,
5     employee_salary FLOAT,
2 frames
/usr/local/lib/python3.8/dist-packages/pyspark/sql/utils.py in deco(*a, **kw)
194                 # Hide where the exception came from that shows a non-Pythonic
195                 # JVM exception message.
--> 196                 raise converted from None
197             else:
198                 raise
AnalysisException: Hive support is required to CREATE Hive TABLE (AS SELECT);
'CreateTable pyspark_semistructureddata.employees, org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, ErrorIfExists
`


text:
Q: How i can display image from path Laravel? there is my form.blade.php file
 D:\wamp\www\blog\resources\views\admin\articles\partials\form.blade.php

there is my images
D:\wamp\www\blog\public\images

How i can display it ?
I use this, but this not work for me.
image_path : ''}}" alt="">

A: Try
image}}" alt="">

A: public directory is publicly accessible. So, you can just set src as /images/{{$article ? $article->image_path : ''}}

A: You should try this.
image}}" alt="">


text:
Q: Android dialog transparency (not the usual) I have an issue with my android dialog. I would like it to be displayed over any activity (probably a no-no as far as design guidelines but I have good reason). This works. And I'm %95 happy with it. The issue is there seems to be an activity background still displayed beneath my dialog.  This is apparent if I don't call finish() on my activity on each intended close action. Which I've done so it's less problematic, however, the dialog closes a split second prior to the activity background being cleared so the user sees an ugly centimeter long box for a split second as it finishes.
[____]
Is there any way to combat this? I've tried all of the API dialog themes: No action bar, no title bar, transparent, etc etc to no avail. I also attempted to set the dialog color to full transparency as well.

A: I had the same problem and my solution was:
@Override
protected void onPause() {
    this.finish();
    super.onPause();
}


text:
Q: While loop involving floating point numbers #include<stdio.h>
void main()
{
 float x=1.1;
 while(x==1.1)
 {
     printf("\n%f",x);
     x=x-0.1;
 }
}

I have learnt that while loop can also involve floating point numbers but the above program doesn't show any output. Why is it so ?


text:
Q: pine script trading - Partial exit working for long but not for short strategy Hello and thank you for looking into this!
I have coded a pullback strategy, which attempts to buy once price retraces back to an EMA and then sells part of the position at a fixed ATR target, the other part at the next one, or at a raised stop. This works fine for exiting a long position. You can find the code I use below
if long_entry
    strategy.entry("buy", true, initial_qty , comment = "ELP")

strategy.exit("TP1", "buy", qty_tp1, limit = target_price1, stop = stop_price1)
strategy.exit("TP2", "buy", limit = target_price2, stop = stop_price1, when = strategy.position_size > qty_tp1 )
strategy.exit("TP2", "buy", limit = target_price2, stop = stop_price2, when = strategy.position_size < qty_tp1)

I I try to do the same for a variation of the strategy, that looks for shorts, the second stop will not trigger and no matter how I try to arrange things, will not work.
This is the short version
if short_entry
    strategy.entry("enter short", false, qty1, comment = "ESP")

strategy.exit("Stop1/TP1", "enter short", qty2, limit = target_price1, stop = stop_price1)
strategy.exit("Stop1/TP2", "enter short", limit = target_price2, stop = stop_price1, when = strategy.position_size < qty2)
strategy.exit("Stop2/TP2", "enter short", limit = target_price2, stop = stop_price2, when = strategy.position_size > qty2)

To make it easier to understand the approach, I have included two screenshots.
The 1st one shows how the raised stop triggers after price has reach TP1 in my long strategy. Red is the initial stop, blue the entry price, green the 1st and 2nd target and yellow the raised stop.
The 2nd one shows how the stop is unaffected by price trading through it.
I have tried all kinds of combinations with the "when" function, but I cannot get it to work. What am I missing here?
Thanks a lot!


text:
Q: setTitleTextAttributes not working properly Hello in I've been facing this weird bug where the app only works on iPhone 6.
so in one of my methods I have
- (void)dummy {
   UIFont *titleFont = [HTFont thinFontOfSize:20];
   [[UINavigationBar appearance] setTitleTextAttributes:@{
   NSFontAttributeName:titleFont }];
}

If I comment that out, the app works on iPhone 4s
I am assuming it is something wrong with the HTFont file but I can't seem to figure it out.
HTFont.m
#define IS_IPAD   (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

#define SCREEN_WIDTH  CGRectGetWidth([[UIScreen mainScreen] bounds])
#define SCREEN_HEIGHT CGRectGetHeight([[UIScreen mainScreen] bounds])

#define IS_IPHONE4  (IS_IPHONE && MAX(SCREEN_WIDTH, SCREEN_HEIGHT) < 568.0)
#define IS_IPHONE5  (IS_IPHONE && MAX(SCREEN_WIDTH, SCREEN_HEIGHT) == 568.0)
#define IS_IPHONE6  (IS_IPHONE && MAX(SCREEN_WIDTH, SCREEN_HEIGHT) == 667.0)
#define IS_IPHONE6P (IS_IPHONE && MAX(SCREEN_WIDTH, SCREEN_HEIGHT) == 736.0)

static NSString * const kFontName = @"SourceSansPro-Regular";
static NSString * const kThinName = @"SourceSansPro-Light";

@implementation HTFont

+ (UIFont *)fontOfSize:(CGFloat)size {

    return [UIFont fontWithName:kFontName size:[HTFont     adjustedFontSizeForScreen:size]];
}

+ (UIFont *)thinFontOfSize:(CGFloat)size {

    return [UIFont fontWithName:kThinName size:[HTFont     adjustedFontSizeForScreen:size]];
}

+ (CGFloat)adjustedFontSizeForScreen:(CGFloat)size {

    if (IS_IPHONE5) {

       return size;

    } else if (IS_IPHONE6) {

        return size * 1.1;

    } else if (IS_IPHONE6P) {

       return size * 1.2;

    } else {

        return size * 0.9;
    }
}

What could be causing the error?
*** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary
initWithObjects:forKeys:count:]: attempt to insert nil object from
objects[1]'
*** First throw call stack:


text:
Q: Provide a dependency property of a control to a converter in the control? I have two objects, Culture and Translation, neither of which are complicated. Culture is like a simple CultureInfo, but with an extra field.  Cultures likely won't change often, and there won't be many to begin with.  However, there will be many Translations, and each Translation has a CultureID property.  Translations each have a TranslationID, so that you can link Translations together.  The data would look something like this:
TranslationID,     CultureID,     Text;
1,                 en,            Hello;
1,                 es,            Hola;
2,                 en,            Bye;
2,                 es,            Adios;
I'm trying to build a control where I can bind the list of Cultures as well as the list of Translations.  For each TranslationID, there may not be a Translation for every Culture.  So I may have English, Spanish, German and Chinese as my Cultures, but for "How are you", I may only have the English and German Translations.
A list of Translations of the same TranslationID will be bound to the control.  Inside the control there will only be one or zero Translations per Culture.  I have a xaml Listbox of Expander elements.  Each Expander should have one Culture, with the Culture.Name property as the header.  The content of each Expander is a TextBox containing the Translation of that Culture, if the Translation exists.  If it doesn't exist, the TextBox is blank.  So far, I've got this much working.
Outside of the control, one of the Cultures can be picked for editing Translations, even though inside the control any Translation of a Culture can be edited.  That's fine if that happens.  What the current editing Culture should do is make the Expander in my control that contains that very Culture, be the only one that is Expanded when the control is opened (the control will be in a Popup).  All other Expanders in the Listbox in the control should be not expanded.  I have made a dependency property in my control that takes the current editing Culture, called CurrentTranslationCulture.
This is where my problem lies.  I tried using a DataTrigger and a custom converter to make the comparison of a Culture to the CurrentTranslationCulture.  However, since the converter is it's own class, it doesn't have access to the CurrentTranslationCulture.  I tried passing it in as a ConverterParameter, but I couldn't bind it to the ConverterParamater parameter in the Binding of the DataTrigger.  I don't even know if this is the approach I should be taking.  Does anyone know the solution to this, or perhaps even a better one?  Thanks in advance.
Code:  The below code does not work completely.  If you take out the ConverterParameter, it would work, but all of my Expanders would be closed.  Inside the ConverterParamerter, ElementName=labelTranslationEditor, is the name I provided to my control in an attempt to access it.
<ListBox x:Name="listTranslations" AlternationCount="2">
                <ListBox.ItemTemplate>
                    <DataTemplate DataType="{x:Type office:Culture}">
                        <Expander x:Name="cultureExpander" Header="{Binding Path=Name}" IsExpanded="False">
                            <Expander.Triggers>

                            </Expander.Triggers>
                            <TextBox x:Name="tbInsertLabelText" Style="{StaticResource popupLabelTextBox}" MinWidth="300" MaxWidth="450"
                                VerticalAlignment="Top" HorizontalAlignment="Right" SpellCheck.IsEnabled="True" TextWrapping="WrapWithOverflow" />
                        </Expander>

                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding Path=CultureID, Converter={StaticResource expandedConverter}, ConverterParameter={Binding ElementName=labelTranslationEditor, Path=CurrentTranslationCulture}}" Value="false">
                                <Setter TargetName="cultureExpander" Property="IsExpanded" Value="false" />
                            </DataTrigger>
                        </DataTemplate.Triggers>
                    </DataTemplate>
                </ListBox.ItemTemplate>

A: From the MSDN forum...  The solution to the Expander problem was to use a MultiBinding to capture both the Culture that is bound to the expander, as well as the CurrentTranslationCulture.  The two are then passed into the Converter which applies the appropriate logic.
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/2699e07e-5eff-4499-8aec-34f6e1e298a0
Here is the only code that changed:
<DataTemplate.Triggers>
                            <DataTrigger Value="True">
                                <DataTrigger.Binding>
                                    <MultiBinding Converter="{StaticResource expandedConverter}">
                                        <Binding Path="CultureID" />
                                        <Binding ElementName="labelTranslationEditor" Path="CurrentTranslationCulture" />
                                    </MultiBinding>
                                </DataTrigger.Binding>
                                <Setter TargetName="cultureExpander" Property="IsExpanded" Value="True" />
                            </DataTrigger>
                        </DataTemplate.Triggers>


text:
Q: Get one record at a time from SQL This is the function that I use to display the row from the database. The default value is level 1, SID 1. If the user chooses from the dropdown list, the level can change, but the ID stays the same because I didn't know what to do here. I want to get one record at a time, but when I press the next button, I want to get the next row with the selected level. If that is possible, can you give me some tips on how to do this? Thank you in advance.
 public void FillPageSpelling()
    {
        ArrayList videoList1 = new ArrayList();

        if (!IsPostBack)
        {
            videoList1 = ConnectionClass.GetSpelling(1,1);
        }
        else
        {
            int i = Convert.ToInt32(DropDownList1.SelectedValue);
            videoList1 = ConnectionClass.GetSpelling(i,1);
        }
        StringBuilder sb = new StringBuilder();
        foreach (Spelling sp in videoList1)
        {

            sb.Append(
           string.Format(
               @"

        <input type=text style=display:none  id=TextBox3 value={0}>

        Level:
        {3}

        Sentence:
          {1}

      Sound: <audio controls><source src=sound/{2}></audio>

        Write the word here: <input type=text id=TextBox1>

      <input type=button value='Check' class='p-userButton' onClick='ButtonClick(document.getElementById(""TextBox1"").value, document.getElementById(""TextBox2"").value);'/>

      <input type=button value='Cheat' class='p-userButton' onClick='Cheat(document.getElementById(""TextBox2"").value);'

      <input type=button value='Next' class='p-userButton'

        <input type=text style=display:none id=TextBox2 value={4}>

", sp.SID, sp.Sentence, sp.Audio, sp.Level, sp.Word));
            lblOutput.Text = sb.ToString();
        }
    }

Here is the method that returns one record based on the level and ID:
 public static ArrayList GetSpelling(int level, int sid)
{
    ArrayList list = new ArrayList();
    string query = string.Format("SELECT * FROM Spelling WHERE Level LIKE '{0}' and SID LIKE '{1}'", level, sid);

    try
    {
        conn.Open();
        command.CommandText = query;
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            int SID = reader.GetInt32(0);
            string Sentence = reader.GetString(1);
            string Word = reader.GetString(2);
            int Level = reader.GetInt32(3);
            string Audio = reader.GetString(4);

            Spelling lst = new Spelling(SID, Sentence, Word, Level, Audio);
            list.Add(lst);
        }
    }
    finally
    {
        conn.Close();
    }
    return list;
}
}

A: I don't necessarily have an answer to your problem but I do have a few topics for you to research.
As someone else suggested, research proper binding of forms to server side code. If MVC (which I recommend), model binding from the View to the Controller is where you would need to focus.
Research MVC.
Research Object Relational Mappings - if you like .NET, try Entity Framework 5.
Also, look into third party data grids and data pagers.


text:
Q: trigger page reload on specific checkbox selection Ok, I have a code which saves 30 or so checkbox selections to local storage which works fine, I also have a separate checkbox (as below) which when checked automatically reloads the page
<input type="checkbox" id="autoload" class="autoload"> Tick this box to automatically update the results as you choose them from the options below

Below is the code I have to trigger the page reload
if ($('#autoload').is(':checked')) {
    location.reload();
    }

Below is the code which saves the checkboxes to local storage and where I want to add the trigger reload code above
window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

My problem is I do not know where or how to place the trigger page reload code into the code above to make it work. Hope all my babblings make sense, any help really appreciated.

A: You can use ".change" trigger for check box like this:
window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

$('#autoload').change(() => {
   if ($('#autoload').is(':checked')) {
      location.reload();
   }
});

A: Sorted it myself
window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
      if ($('#autoload').is(':checked')) {
         location.reload()
      };
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}


text:
Q: Custom Innosetup page with custom buttons I would like to create a custom Innosetup page which has the following layout. That will be displayed as the very first page and if user clicks the Configure button, he will be taken to the typical install pages. if user clicks the Install button, the install will happen silently.
+------------------------------------+
|                                    |
|                                    |
|        a bitmap image              |
|                                    |
|                                    |
+------------------------------------+
Cancel               Install Configure

It looks like custom pages and forms do not allow that. Is this possible with Innosetup?

A: In my first answer I didn't really see the requirement for additional buttons.
I think you can not do this with InnoSetup, but you could actually create a "wrapper" application that shows your page and upon the "Install" button click runs the InnoSetup setup.

Searching SO a bit more, I found there's actually a way of adding your own buttons to the UI as described in the answer to this question: Inno Setup - replace default next/back/cancel buttons. I don't know, however, if there's also a way of removing unwanted buttons.
It is stated in this answer that there are examples in the CodeClasses.iss example script in \program files\inno setup 5\examples.


text:
Q: Access variables from another file I'm trying to have something like a configuration file, and store in it variables.
When I'm trying to include it, I can't access the variables. it gives me this error:
Notice: Undefined variable: myVar

include.php
<?php
$myVar = "Text";
?>

index.php
<?php
include('include.php');
?>
<html>
.....
<body>
<?php
echo $myVar;
?>
</body>

P.S. I heard it's not a good habit to have this file with variables and include it in every page. if it is, please show me the better way to do this.
Thanks.

A: If you're thinking about using include.php to use as a database sort of, then I'ld suggest reading about MySQL and start using that instead.
If you're only looking to carry on a single variable, your code should be all right.
I don't know if it's just your message, or if you do the same in your code, but echo $myVar must be inside a php tag
<?php echo $myVar; ?>

Also, make sure you've entered the correct path to your file in the include() function, and make sure it's called before trying to output the variable.


text:
Q: Could not build module Foundation I am using a sub-project which has a C++ library that it uses and this project has a SDK that I am trying to use.
I have several projects that I am trying to build, each of which use this SDK. I have some targets that compile fine but then I have some that tell me Could not build module: Foundation.
As I said this happens in some but not all of my targets, I was able to get some to work by clearing the linker flags but this does not fix it on all targets. So it seems weird to me that some targets work fine while others do not.
I have tried:
Removing linker flags
Reinstalling Xcode
Messing with header search paths
Any suggestions? I've been stuck on this for a while.

A: As don't have more information in question here.
Try making

Allow Non-modular Includes in Framework Modules

to Yes in your Build Settings.


text:
Q: Regex for Lightning Input in Aura Component I have one Lightning input in which I have to show the error message if condition is not satisfied.
1.4 characters min
2.12 characters max
3.Allowed characters:
Letters (A,B,M....26 capital letters of the English alphabet)
4.Digits (1,2,3....)
5.Dash ( - )

*It must contain at least 1 digit

Need to check and show different error message for different condition if not satisfied in Aura Component in JS.
help with this how can I achieve this in aura
Controller:
  if( 4 > updatedAFName.length )
        {
            let errorMessage= "Le numéro d'adhésion ne peut pas contenir moins de 4 caractères";
            helper.showToast(component, event, helper,afLabel,errorMessage,"error");
             component.set("v.isInEditingMode", true);
             component.set("v.isInSavingMode", true);
        }
        else if(updatedAFName.length > 12 )
        {
            let errorMessage= "Le numéro d'adhésion ne peut pas excéder 12 caractères";
            let afLabel= $A.get("$Label.c.TM_B02_APPLICATION_FILE");
            helper.showToast(component, event, helper,afLabel,errorMessage,"error");

        }
        else{
             if(isChangeAFName) {
                 component.set("v.IsApplicationNumberModalOpen", true);
                 component.set("v.isChangeAFName", true);
                }
                component.set("v.isInEditingMode", true);
                component.set("v.isInSavingMode", true);
                //component.set("v.IsApplicationNumberModalOpen", true);
            }```

A: To check length use below:
if(stringToCheck.length < 4 || stringToCheck.length > 12){
 //throw error
}

To not allow small letters a-z use below:
const regex = /[a-z]/;
if(regex2.test(stringToCheck)){
 //if a-z is entered throw error
 //this will allow A-Z, 0-9, '-'....
 //throw error
}

To must contain at least one digit use below:
const regex = /\d/;
if(!regex2.test(stringToCheck)){
 //if no digit is entered throw error
 //throw error
}


text:
Q: Placing divs/tables I got some tables that are filled with data to generate tables, now everything works fine, but i cannot get these tables on the places i want them...
when i load the page they look fine:

but when i make one of them larger they dont stay so nice in place:

any way to keep them together even when one on the other side is made bigger?
I tried this with floating and aligning, and then i dont know any other options.
EDIT:
note that my tables are being generated.
Like if the user wants to add 2 graphs to the site, he gets 2 of this tables, and within this tables he can choose how much variables he want to show in it and needs to input query's for it.
So the height of the tables is never really the same, and can change all the time.
that why i am having problems finding a solution

A: Since you use tables why don't you enclose all 4 of them into a 5th table?

 put here table A
 put here table B

 put here table C
 put here table D

Style the outer table to have red borders and some pading on its cells and you are set


text:
Q: jquery code causes unwanted space I am having an issue with an options and answers feature I have. If I select an options which contains an output of some many buttons e.g If I choose option 20, it will display 20 buttons, the problem I am getting is that at the bottom of the table column, the space drops down a little bit. It only does it when an option is changed and then the space remains throughout. My question is simply how can I stop the space at the bottom of the table column to increase when an option changes?
I have found out that the code that is causing this problem is this:
  //THE ISSUE IS HERE

var _x = $(e.currentTarget);
var _y = _x.closest('td.extratd');
var _z = _y.prev();

$('textarea', _z).css('height', '').height(_z.innerHeight());

//ISSUE ABOVE

Now what the code above does is allow the textarea within the Question column to fill the whole table cell when ever the textarea is appended or if the option changes. So I need the code above but what the code above also does is create an unnecessary space at the bottom of the table row so I need help to sort out the unwanted space.
I have a jsfiddle here which you can use to see what is happening and it also includes the code above: http://jsfiddle.net/aND4g/61/
Please follow steps below in order to use fiddle:

*

*When you open fiddle, on top type in a content in the question textarea and then click on Open Grid and select button 3 or 4.

*When you have done step 1 then click on the Add Question button to append the above details into the table below

*Now WITHIN THE APPENDED ROW, click on the Open Grid and select the other option from what you first chosen. You will see that it creates an unwanted space at the bottom of the table row

A: It's because you're using innerHeight(), which includes padding-top and padding-bottom.

Get the current computed height for the first element in the set of matched elements, including padding but not border.
  -- innerHeight() API documentation

Since these are both equal to 1em, you're getting 2em more height than you want. So, I implemented a quick-and-hacky fix:
// Get the padding of the cell
var ignoreHeight = parseInt(_z.css("padding-top")) + parseInt(_z.css("padding-bottom"));
// Set the height without that padding
$('textarea', _z).css('height', '').height(_z.innerHeight() - ignoreHeight);

jsFiddle
Basically, I just added the padding into a variable, and subtracted that from the actual height you're setting. There might be a better way you can "ignore" this padding with some nicer method, but it seems to me this will work for your case.


text:
Q: c# - Share class between Winform and aspx application I've created a system formed bye a c#/winform application and c#/ASPX application who exchange information via XML files.
The c#/Winform application work as a frontend : make different operation and use some file saved as Xml to share information with other application.
The c#/ASPX application is my backend. I can call it by browser form other PC and through it I configure the front-end application.
The system works perfectly.
The question is this :
I've some classes that are the same in first and second application.
how can I use the classes, without having to rewrite them in a project and the other?
NOTE1 : I use visual studio express as IDE (visual express desktop 2015 for winform and visual express web 2015 for aspx)
NOTE2 : the application have to work on linux mono too.

A: Create a separate class library project having the shared classes.  Then reference this class library from your WinForm and ASP.Net applications.  Hope that helps.


text:
Q: Calculating the adjacency matrix and finding nearest neighbors for different node type/classes Before I describe my problem I'll summarise what I think I'm looking for. I think I need a method for nearest-neighbor searches which are restricted by node type in python (In my case a node represents an atom and the node type represents the element the atom is). So only returning the nearest neighbors of a given type. Maybe I am wording my problem incorrectly. I haven't been able to find any existing methods for this.
I am writing some ring statistics code to find different types of rings for molecular dynamics simulation data. The input data structure is a big array of atom id, atom type, and XYZ positions.
For example.

At the moment I only consider single-element systems (for example graphene, so only Carbon atoms are present). So each node is considered the same type when finding its nearest neighbors and calculating the adjacency matrix.
For this, I am using KDTree and scipy.spatial algorithms and find all atoms within the bond length, r, from any given atom. If an atom is within, r radius of a given atom I consider it connected and then populate and update an adjacency dictionary accordingly.
def create_adjacency_dict(data, r, leaf_size=5, box_size=None):
    from scipy.spatial import KDTree
    tree = KDTree(data, leafsize=leaf_size,
                  boxsize=box_size)
    all_nn_indices = tree.query_ball_point(data, r, workers=5)  # Calculates neighbours within radius r of a point.
    adj_dict = {}
    for count, item in enumerate(all_nn_indices):
        adj_dict[count] = item  # Populate adjacency dictionary

    for node, nodes in adj_dict.items():
        if node in nodes:
            nodes.remove(node)  # Remove duplicates

    adj_dict = {k: set(v) for k, v in adj_dict.items()}

    return adj_dict

I would like to expand the code to deal with multi-species systems. For example AB2, AB2C4 etc (Where A,B and C represent different atomic species). However, I am struggling to figure out a nice way to do this.
                                             A
                                            / \
                                           B   B

The obvious method would be to just do a brute force Euclidean approach. My idea is to input the bond types for a molecule, so for AB2 (shown above), you would input something like AB to indicate the different types of bonds to consider, and then the respective bond lengths. Then loop over each atom finding the distance to all other atoms and, for this example of AB2, if an atom of type A is within the bond length of an atom B, consider them connected and populate the adjacency matrix. However, I'd like to be able to use the code on large datasets of 50,000+ atoms, so this method seems wasteful.
I suppose I could still use my current method, but just search for say the 10 nearest neighbors of a given atom and then do a Euclidean search for each atom pair, following the same approach as above. Still seems like a better method would already exist though.
Do better methods already exist for this type of problem? Finding nearest neighbors restricted by node type? Or maybe someone knows a more correct wording of my problem, which is I think one of my issues here.

A: "Then search the data."
This sounds like that old cartoon where someone points to a humourously complex diagram with a tiny label in the middle that says "Here a miracle happens"

Seriously, I am guessing that this searching is what you need to optimize ( you do not exactly say )
In turn, this suggests that you are doing a linear search through every atom and calculating the distance of each.  Could it be so!?
There is a standard answer for this problem, called an octree.
https://en.wikipedia.org/wiki/Octree
A netflix tv miniseries 'The Billion Dollar Code' dramatizes the advantages of this approach https://www.netflix.com/title/81074012


text:
Q: numba fails as soon as jitted function is called I'm working on a bit of code to 'smooth' a .fits image, and although it works great, it's rather slow (approx. 3 minutes per image). I am trying to optimize the code using numba, but I'm stuck trying to get it to work with the functions I am calling. I believe the issue has to do with the way numba passes variables from one block to another.
The function 'smoother' takes a .fits file from the specified folder and feeds it (as an array) into the 'pixcal' function. 'pixcal' turns the image into a stack (i.e. a 1024x32x32 array) and then 'pixcal' feeds this into the 'boxcar' function. 'boxcar' iterates through the image and feeds the stack into 'robust_mean' which does the actual smoothing, and then the smoothed array is returned to the beginning. Here's the pastebin: https://pastebin.com/CwDbN5D3
The code fails as soon as any of the jitted functions are called, before even a single line is executed. Does anyone have a clue what's going wrong here?
Here's an error message:
Analyzing file 1 of 5: image_contracted_R01_M01_N02.fits
begin pixcals and smoothing (may take a while)
size of image:  (1024, 1024)
made stack:  (1024, 32, 32)
boxcar smoothing
Traceback (most recent call last):

  File "<ipython-input-29-93e136cc4875>", line 1, in <module>
    runfile('C:/Users', wdir='C:/Users')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Documents/AAA_Lab_Work/Python/smoothing/good_code/combined code.py", line 197, in <module>
    smoother()

  File "C:/Users/Documents/AAA_Lab_Work/Python/smoothing/good_code/combined code.py", line 186, in smoother
    hdu = fits.PrimaryHDU(pixcal(fits.getdata(filename), width, channels)) #create hdu object to encapsulate data

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\dispatcher.py", line 307, in _compile_for_args
    return self.compile(tuple(argtypes))

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\dispatcher.py", line 579, in compile
    cres = self._compiler.compile(args, return_type)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\dispatcher.py", line 80, in compile
    flags=flags, locals=self.locals)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 766, in compile_extra
    return pipeline.compile_extra(func)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 362, in compile_extra
    return self._compile_bytecode()

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 725, in _compile_bytecode
    return self._compile_core()

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 712, in _compile_core
    res = pm.run(self.status)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 248, in run
    raise patched_exception

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 240, in run
    stage()

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 433, in stage_objectmode_frontend
    cres = self.frontend_looplift()

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\compiler.py", line 413, in frontend_looplift
    flags=loop_flags)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\transforms.py", line 193, in loop_lifting
    cfg = compute_cfg_from_blocks(blocks)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\analysis.py", line 213, in compute_cfg_from_blocks
    cfg.add_edge(k, target)

  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\controlflow.py", line 83, in add_edge
    assert dest in self._nodes

AssertionError: Failed at object (object mode frontend)

Thanks a lot for the help :^)


text:
Q: Can I trust that every Debian-derived distro will have a 'base-files' package that contains '/etc/debian_version'? What I want is a quick, reliable command to ascertain that the Linux I'm running in is Debian-based. The following command seems to work. It also returns the Debian version:
dpkg -L base-files 2>/dev/null | grep '^/etc/debian_version$' >/dev/null 2>&1 && cat /etc/debian_version

My previous idea was to use dpkg -S /etc/debian_version to see if it belonged to some package, regardless of name. But dpkg -S is slow.
I only have a lingering doubt: are there older Debian-derivated distros where my assumption doesn't hold? Is there a better way?

A: A better approach is to test that what you want to do is possible rather than relying on what the distribution is. For example my Ubuntu box claims it is "squeeze/sid". If you want to install something via dpkg, check dpkg is where you expect it an is executable. If you want to modify the networking setup? Check that /etc/networking/interfaces exists. Check for tools like update-rc.d etc.
You should also use /etc/lsb-release rather than /etc/debian_version.

A: I don't believe you can make that assumption no.
Please see:

*

*How do I find out what version of Linux is running?

*How do I find out the distro of a server?

*Determining type of Linux machine