text:
Q: Laravel 5.1 Create or Update on Duplicate In Laravel 5.1, for MySQL insert, I want to see if the record already exists and update on duplicate or create new if none exists.
I have already searched SO where the answers were for old laravel versions. In one of the old topics it said that a new updateOrCreate() method was added in core last year. But when I try that, I am getting the error:
Integrity constraint violation: 1062 Duplicate entry '1' for key 'app_id'

This is the query I use:
AppInfo::updateOrCreate(array(
    'app_id' => $postData['appId'],
    'contact_email' => $postData['contactEmail']
));

Where app_id is the unique foreign key in that table and I want to update the record if exists or create a new one. I have tried searching the 5.1 docs and couldn't find the info I need. Can someone guide me here please...

A: I created a package to work with MySQL insert on duplicate key.
It may be useful for others:
https://packagist.org/packages/yadakhov/insert-on-duplicate-key
Example:
/**
 * Class User.
 */
class User extends Model
{
    use Yadakhov\InsertOnDuplicateKey;
    ...
}

// associative array must match column names
$users = [
    ['id' => 1, 'email' => 'user1@email.com', 'name' => 'User One'],
    ['id' => 2, 'email' => 'user2@email.com', 'name' => 'User Two'],
    ['id' => 3, 'email' => 'user3@email.com', 'name' => 'User Three'],
];

User::insertOnDuplicateKey($users);

A: As per the Definition of the Eloquent Model Method "updateOrCreate()"

function updateOrCreate(array $attributes, array $values = []){}

it takes two argument ...

*

*one is the attributes using which you want to check in database if the record is present

*second is the new attribute values that you want to create or update

AppInfo::updateOrCreate(['app_id' => $postData['appId']],
                        ['contact_email' => $postData['contactEmail']]);

A: Add the follow method insertUpdate to your Model
<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public static function insertUpdate(array $attributes = [])
    {
        $model = new static($attributes);

        $model->fill($attributes);

        if ($model->usesTimestamps()) {
            $model->updateTimestamps();
        }

        $attributes = $model->getAttributes();

        $query = $model->newBaseQueryBuilder();
        $processor = $query->getProcessor();
        $grammar = $query->getGrammar();

        $table = $grammar->wrapTable($model->getTable());
        $keyName = $model->getKeyName();
        $columns = $grammar->columnize(array_keys($attributes));
        $insertValues = $grammar->parameterize($attributes);

        $updateValues = [];

        if ($model->primaryKey !== null) {
            $updateValues[] = "{$grammar->wrap($keyName)} = LAST_INSERT_ID({$keyName})";
        }

        foreach ($attributes as $k => $v) {
            $updateValues[] = sprintf("%s = '%s'", $grammar->wrap($k), $v);
        }

        $updateValues = join(',', $updateValues);

        $sql = "insert into {$table} ({$columns}) values ({$insertValues}) on duplicate key update {$updateValues}";

        $id = $processor->processInsertGetId($query, $sql, array_values($attributes));

        $model->setAttribute($keyName, $id);

        return $model;
    }
}

You can use:
App\User::insertUpdate([
    'name' => 'Marco Pedraza',
    'email' => 'mpdrza@gmail.com'
]);

The next query it will be executed:
insert into `users` (`name`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?) on duplicate key update `id` = LAST_INSERT_ID(id),`name` = 'Marco Pedraza',`email` = 'mpdrza@gmail.com',`updated_at` = '2016-11-02 01:30:05',`created_at` = '2016-11-02 01:30:05'

The method automatically add/remove the Eloquent timestamps if you have enabled or disabled.

A: To use laravel function updateOrCreate you need auto increment id in your table.
what they are doing is
select id from your_table where your_attributes
after that get auto increment id
then
update your_table set your_values where field_id

A: I am answering to this question cause I can't find any answer related to ON DUPLICATE KEY UPDATE, although I am using Laravel 5.4.
If you look at the updateOrCreate method in the Laravel's core code, you will see after all Laravel is using 2 different queries: one for update and another one for create. Because of this, sometimes you can get duplicated data in the DB. So in some cases it can be useful to write this kind of raw query:

DB::statement("INSERT INTO table_name (col_1, col_2) VALUES (?,
  ?) ON DUPLICATE KEY UPDATE col_1 = col_1 + 1", ([val_1, val_2]));

Hope it can be useful for someone.

A: In my case this was caused by a simple mismatch on the auto incrementing key in my model table.
Getting the current max id:
SELECT max(id) from companies

Then setting the sequence value one higher:
select setval('companies_id_seq', 164);

eliminated the error.


text:
Q: sudo not found in shell of CTRL+ALT+F1
*

*CTRL+ALT+F1

*Login to shell

*Type any command: sudo, ls, cat

*Output:
 -bash sudo: No such file or directory

Also when I login, environment variable is printed:
-bash: export: '/home/some/path:/home/some/other/path: _not a  valid identifier_

It's thenot a valid identifier part which I believe is causing the problem. I am new to Ubuntu. What I would like to know is

*

*How to get sudo working here?

*Anyway I can edit my .profile?

A: You have trashed the definition of PATH, the list of directories the shell searches for commands you type. Thus, when you type ls the shell looks at the directories in $PATH and doesn't find /bin/ls. There is a two-step fix:
# First, manually set PATH to something survivable
export PATH=/usr/local/bin:/usr/bin:/bin

# then edit your `~/.bashrc`, find the line that begins with
# "/home/some/path:/home/some/other/path" and see why Bash wants to
# see an identifier at this point. Bad continuation on the previous line?
nano ~/.bashrc

When you've fixed the problem, either log out/in or source ~/.bashrc in every shell process you have open.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shortest path algorithm using dictionaries [Python] This is my first question and actually my first time trying this but I read the rules of the questions and I hope my question comply with all of them.
I have a project for my algorithm subject, and it is to design a gui for dijkstra shortest path algorthim. I chose to use python because it is a language that I would like to master. I have been trying for more than a week actually and I am facing troubles all the way. But anyways this is good fun :)!
I chose to represent my directed graph as a dictionary in this way :
 g= {'A': {"B": 20, 'D': 80, 'G' :90}, # A can direct to B, D and G
'B': {'F' : 10},
'F':{'C':10,'D':40},
'C':{'D':10,'H':20,'F':50},
'D':{'G':20},
'G':{'A':20},
'E':{'G':30,'B':50},
'H':None}  # H is not directed to anything, but can accessed through C

so the key is the vertice and the value is the linked vetrices and the weights. This is an example of a graph but I was planning to ask the user to input their own graph details and examine the shortest path between each two nodes [start -> end] The problem is however that I don't even know how to access the inner dictionary so I can work on the inner paramteters, and I tried many ways like those two:
for i in g:
    counter = 0
    print g[i[counter]]     # One
    print g.get(i[counter]) # Two

but the both give me the same output which is: (Note that I can't really access and play with the inner paramters)
{"B": 20, 'D': 80, 'G' :90}
{'F' : 10}
{'C':10,'D':40}
{'D':10,'H':20,'F':50}
{'G':20}
{'A':20}
{'G':30,'B':50}
None

So my question is, could you please help me with how to access the inner dictionaries so I can start working on the algorithm itself. Thanks a lot in advance and thanks for reading.

A: This is actually not so hard, and should make complete sense once you see it.  Let's take your g.  We want to get the weight of the 'B' connection from the 'A' node:
>>> d = g['A']
>>> d
{"B": 20, 'D': 80, 'G' :90}
>>> d['B']
20
>>> g['A']['B']
20

Using g['A'] gets us the value of the key in dictionary g.  We can act directly on this value by referring to the 'B' key.

A: Using a for loop will iterate over the keys of a dictionary, and by using the key, you can fetch the value that is associated to the key. If the value itself is a dictionary, you can use another loop.
for fromNode in g:
    neighbors = g[fromNode]
    for toNode in neighbors:
        distance = neighbors[toNode]
        print("%s -> %s (%d)" % (fromNode, toNode, distance))

Note that for this to work, you should use an empty dictionary {} instead of None when there are no neighbors.

A: I guess these give you some ideas:
for dict in g:
     print dict.get("B","")

for dict in g:
     print dict.keys() #or dict.values()

for dict in g:
     print dict["B"]


text:
Q: How to prevent client side HTML encoding with jsRender from encoding already encoded string from server This is a tough one to explain, so please bear with me. I am using a combination of server-side encoding using the ASP.NET HttpUtility.HtmlEncode() method and client-side encoding with jsRender (awesome rendering library by the way.)
When I use either of these by themselves it works fine. The character < would become < but it would still display as < in the browser which is good because sometimes there are legitimate cases where these characters are used and need to be displayed to the user correctly, but not executed by the browser.
The problem is when I encode server-side and then also encode that same string client-side it now displays the encoded string in the browser. You are probably asking yourself why would I want to do it in both places. The reason for that is that I prefer to do it server side but I like having the client-side there too in case a developer forgets to do it server-side or vice versa as a failsafe.
Is there any way to have it encode in both places and still have it display as the non encoded string in the browser?

A: I ended up solving this by creating my own custom jsRender tag with a custom render function that checks to see if the string is already encoded and if it is it will leave it alone otherwise it will encode it.
Here is the link for creating custom tags jsRedner Custom Tags Documentation


text:
Q: How to attach datepicker to a single dynamic inserted input field? I know this question has been asked for many years, but after reading so many questions related to this I'm still enable to achieve what I want.
I have a table containing a bunch of input fields Those input fields use the jQuery UI datepicker. There is also a button to add a table row.
When I click the button to add a table row, it is added to the modal correctly. But, the datepicker of all input fire at the same time(no similar id used).
Modal code:

        <form class="form-horizontal" id="edit-form">

                Date

                            <input type="text" name="date" placeholder="Enter date"  class="form-control usedatepicker"/>
                            <button type="button" name="add" id="add" class="btn btn-success">Add More</button>

              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-primary">Save changes</button>

            </form>

JS code:
$(document).ready(function(){
      var i=1;
      $('#add').click(function(){
           i++;
           $('#dynamic_field').append('
<input type="text" name="data" placeholder="Enter date" class="form-control usedatepicker" />	<button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button>
');
           $(".usedatepicker").datepicker();

      });
      $(document).on('click', '.btn_remove', function(){
           var button_id = $(this).attr("id");
           $('#row'+button_id+'').remove();
      });
 });

A: yes, because the problem with Jquery you can't able to attach the event to dynamic element from Jquery. To overcome this issue, you need to reference the previous available element on DOM as a main selector, like this below code.
$('body').on('focus',".class_of_dynamic_element", function(){
$(this).datepicker();});

Now the datapicker will attached to that element.


text:
Q: Dense subset of two Banach spaces also dense in the intersection My question is:
Let $ V $ be a vector space (over $ \mathbb K\in\{\mathbb{R}, \mathbb{C}\} $), $ X,Y\subseteq V $ two subspaces equipped with norms $ \|\cdot\|_X, \|\cdot\|_Y $ such that $ (X,\|\cdot\|_X) $ and $(Y,\|\cdot\|_Y)$ are Banach spaces and $ D\subseteq X\cap Y$. If $ D $ is dense in $ (X,\|\cdot\|_X) $ and $(Y,\|\cdot\|_Y)$, is $ D $ also dense in $ X\cap Y $ equipped with $ \|\cdot\|:=\|\cdot\|_X + \|\cdot\|_Y $?
At first sight, it seemed very clear to me that this should be true. But I even fail to answer the following (possibly) easier question:
Let $ X $ be a vector space over $ \mathbb K $ equipped with two norms $ \|\cdot\|_1, \|\cdot\|_2 $ such that $ (X,\|\cdot\|_1) $ and $(X,\|\cdot\|_1)$ are Banach spaces and $ D\subseteq X$. If $ D $ is dense in $ (X,\|\cdot\|_1) $ and $(X,\|\cdot\|_2)$, is $ D $ also dense in $ X $ equipped with $ \|\cdot\|:=\|\cdot\|_1 + \|\cdot\|_2 $?
The answer is yes, if $ \|\cdot\|_1, \|\cdot\|_2 $ are equivalent, so I tried to think about a counterexample using nonequivalent norms on a specific space and I also found a nice paper about nonisomorphic complete norms (https://www.researchgate.net/publication/226200984_Equivalent_complete_norms_and_positivity) but it didn't helped me so far to construct anything useful for my question.
Thanks for your help!

A: I have a negative answer for your "easier" question based on the construction of https://mathoverflow.net/a/184471.
Let $X_1 := (X, \|\cdot\|_1)$ be an infinite dimensional Banach space and let $\varphi$ be an unbounded linear functional on $X_1$. We fix $y \in X$ with $\varphi(y) = 1$ and define
$$ S x := x - 2 \, \varphi(x) \, y.$$
It is easily checked that $S^2 x := S S x = x$.
The norm
$$ \|x \|_2 := \| S x\|_1$$
gives rise to the normed space $X_2 := (X, \|\cdot\|_2)$. Since $S  :X_2 \to X_1$ is an isometric isomorphism (by definition), $X_2$ is complete.
From $\varphi(x) = -\varphi(Sx)$ one can check that $\varphi$ is also unbounded on $X_2$. Indeed, we find $x_n \in X$ with $\varphi(x_n) \ge n$ and $\|x_n\|_1=1$. Hence, $\varphi( S x_n) \ge n$ and $\|S x_n\|_2 = \|x_n\|_1 = 1$.
Thus, the kernel of $\varphi$ is dense in $X_1$ and $X_2$.
However, we can check that $\varphi$ is bounded w.r.t. $\|\cdot\|=\|\cdot\|_1+\|\cdot\|_2$:
$$
2 \, \|y\|_1 \, |\varphi(x)|
=
\| 2 \, \varphi(x) \, y \|_1
\le
\|x\|_1 + \| x - 2 \, \varphi(x) \, y \|_1
=
\|x\|_1 + \| S x\|_1
=
\|x\|.$$
Hence, the kernel of $\varphi$ is closed and therefore not dense w.r.t. the norm $\|\cdot\|$ in $X$.
I would imagine that your original question would be also interesting if we add the following (reasonable) assumption:
if $\{z_n\} \subset X \cap Y$ satisfies $z_n \to x$ in $X$ and $z_n \to y$ in $Y$
then $x = y$.
Note that this is not satisfied in my counterexample.


text:
Q: "Validation that might throw exception" - Naming convention and semantics If you validate something in code you can either work with a return value indicating that something is wrong or you can throw an exception. In my controller I have Exceptional validation like this:
 void DoSomething()
 {
     Validate();  // throws exception if something is wrong
     .....
 }

I wonder if there is a common naming convention that implies that an exception is thrown when something is wrong so that I don't need to add the comment // throws exception if something is wrong and distinguishes from if (!IsValid())
Note: validation-naming-conventions does not answer my question.
Update after accepting the answer: What I have learned from this Question

*

*AssertValid() or VerifyAndThrow() are good names (tnx @hacktick)

*Validation must distinguish with a context (warning or error)

*Exceptional Validation is good as a kind of Contract or second line of defense that might exist only in Debug mode to ensure that the surrounding if (IsValid(...)) does not miss something (tnx @ Cody Gray)

A: Typically you would use:
// for a validations that returns just plain yes no (true|false). in the case of a property use caching for the last validationresult.
bool IsValid

// for a validation that returns a list of errors of some sort (messagelist, id list, custom objects, whatever you need).
object Validate();

// validates and throws an exception if one or more error occured.
void ValidateAndThrow();

Also make sure to consider if you need warnings of some kind. For example if you validate your registration DTO model and want to warn a user if the password is weak but do not want to prevent the user from saving it if he chooses to.


text:
Q: How do I save the files lists in vim? I've opened many files in vim,
is there a command to save the full paths of opened files into a separate file so that next time I can resume with vim -p files.txt?

A: One quick way is to save the session with :mksession list.vim.
This will have lines of the form badd +0 path/to/file  (or +currentLine)
You can just pull out these lines if that is all you need.
The fun part is, you can resume next time with just vim -S list.vim :-)
More at Vim Documentation on Sessions, and many other web sources.


text:
Q: Como chamar shortcode no wordpress atraves de um select? eu tenho uma pagina dentro do meu site em wordpress+woocommerce que tem dois selects, e depois de selecionar os dois, gostaria que em uma DIV abaixo chamasse o produto por shortcode. O problema eh que provavelmente precise de um refresh.
HTML
<select class='turno'>
<option value=''>Selecione</option>
<option value='[products skus="a1'>manha</option>
<option value='[products skus="a2'>tarde</option>
<option value='[products skus="a3'>noite</option>
</select>

<select class='hora'>
<option value=''>Selecione</option>
<option value='[products skus="a1'>1</option>
<option value='[products skus="a2'>2</option>
<option value='[products skus="a3'>3</option>
</select>

"]

JAVA SCRIPT
 $(document).ready(function(){
 $('.turno').on('change', function(){
 $('.turnoescolhido').text($(this).val());
 });

 $('.hora').on('change', function(){
 $('.horaescolhido').text($(this).val());
 });
 });

A: É possível fazer uma atualização parcial do conteúdo da página utlizando AJAX.
De maneira bem simples, você colocaria algo assim na sua página ou arquivo js:
$('.hora').on('change', function(){
    var url = 'http://meusite/wp-admin/admin-ajax.php',
        dados = {
            "action": "products", // nome do shortcode
            "shortcode": $(this).val() // shortcode completo [products...]
        };

    // carrega valor do shortcode no elemento html
    $('.horaescolhido').load(url, dados);

});

E em no seu plugin ou tema:
<?php
// essa é a função que é executada quando usuario não está logado
function wp_ajax_nopriv_products_func() {
    wp_ajax_products_func();
}

// essa é executada quando o usuário está logado
function wp_ajax_products_func() {
    $shortcode = isset($_REQUEST['shortcode']) ? $_REQUEST['shortcode'] : '';

    // para do_shortcode() devemos passar o valor completo do shortcode
    // exemplo [products sku="a1"]
    echo do_shortcode($shortcode)

    // esse die é muito importante
    die;
}

// registra as funções que irão atender a requisição
// o identificador da função deve ser wp_ajax_ + valor_do_action
// e/ou wp_ajax_nopriv_ + valor_do_action
add_action('wp_ajax_nopriv_products', 'wp_ajax_nopriv_products_func', 1);
add_action('wp_ajax_products', 'wp_ajax_products_func', 1);

?>

Algumas referencias:

*

*Ajax em plugins

*Ajax no Wordpress


text:
Q: OpenSSL::PKey::RSAError: Neither PUB key nor PRIV key: not enough data on travis-ci I'm making use of the google/api_client library in ruby. My code works fine in development and local test, but not so well on Travis-CI. I'm storing my private key as a multi-line string both locally and on Travis. My code fails here:
require "google/api_client"

class GoogleCalendarAdapter
  def key
    OpenSSL::PKey::RSA.new(ENV["GOOGLE_P12_PEM"], "notasecret")  # line 27
  end
end

I have defined the GOOGLE_P12_PEM environmental variable via the Travis-CI web console as:
"-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAK...\n...
\n-----END RSA PRIVATE KEY-----\n"
This is the error I recieve:
Failure/Error: events = calendar.fetch_events(start_time, end_time)
 OpenSSL::PKey::RSAError:
   Neither PUB key nor PRIV key: not enough data
 # ./lib/google_calendar_adapter.rb:27:in `initialize'
 # ./lib/google_calendar_adapter.rb:27:in `new'
 # ./lib/google_calendar_adapter.rb:27:in `key'
 # ./lib/google_calendar_adapter.rb:36:in `oauth2_client'
 # ./lib/google_calendar_adapter.rb:49:in `google_api_client'
 # ./lib/google_calendar_adapter.rb:15:in `fetch_events'
 # ./spec/lib/google_calendar_adapter_spec.rb:18:in `block (3 levels) in <top (required)>'

Any suggestions on how to troubleshoot this issue are welcome.

A: I ended up encrypting my p12 file, and providing instructions on how to decrypt the file in my .travis.yml, as documented, here


text:
Q: List tables involved in a sql statement before it is run? Is it possible, in .NET, to pass a sql statement to SQL server for parsing and return the tables involved in the statement and the type of operation. So for a statement like this :
select * from Table1
left outer join Table2 on Table1.id=Table2.foreignid;
delete from Table2 where date < 2009/12/12

SQL Server might return the tables involved like this :
Table1    Read
Table2    Read
Table2    Delete

So the statement isn't executed, it just returns the tables involved.
The reason I ask is that the application I am working on has application level table permissions that I want to apply on a table by table basis. The current method of parsing out the tables involved in a statement uses a regular expression and fails in anything other than simple statements. Obviously you can't really be using a regular expression for this kind of job

A: Would SET SHOWPLAN_ALL do it for you? It simulates the call query on the server and you may be able to parse the results.
Edit: It looks like SET SHOWPLAN_TEXT would be easier to parse.

A:
The reason I ask is that the application I am working on has application level table permissions that I want to apply on a table by table basis.

It seems to me you should create a database level role to capture those permissions, and apply them on that level. You paid for your database management system - don't spend your time coding what is best done by a solution that's already in place.
Application level permissions may make sense on the row level, and even those can be implemented at the database. But if they are on the table level, I don't see any excuse that justifies coding enforcement yourself. Use your database, you paid for it.


text:
Q: Is CLLocation latitude equal to zero? How do I check to see if _mapView.userLocation.location.coordinate.latitude is equal to 0?
Latitude is a type of double typedef double CLLocationDegrees;
I've tried comparing it to 0, -0.000000, 0.000000 and 0.00 with no luck.
I've tried converting it to a string like this
NSLog(@" lat %@", ([NSString stringWithFormat:@"%f", _mapView.userLocation.location.coordinate.latitude] == @"0.000000") ? @"yes" : @"NO" );
string  0.000000
lat NO

but this doesn't work either.
What am I missing here?

A: It's stored as a double so simple numeric comparison should suffice:
if (coordinate.latitude == 0)

However, if you're dealing with real locations, it's highly unlikely that it is ever actually 0, so you may need to round the value first.
From comments it looks like you are assuming that a coordinate of 0,0 indicates an error with the location. This is not the case. If the coordinate is invalid, then the horizontalAccuracy property will be negative. This is the correct way to check for an invalid coordinate:
if (coordinate.horizontalAccuracy < 0)

A: I'm not sure why but if I store a reference as a float it works as expected.
float lat = _mapView.userLocation.location.coordinate.latitude;
float lon = _mapView.userLocation.location.coordinate.longitude;

if (lat == 0 || lon == 0) {
...

A: using swift, but the same you can do with category's objective-c:
extension CLLocation {

    func isZero() -> Bool {
        return self.coordinate.latitude == 0.0 && self.coordinate.longitude == 0.0
    }

}

A: You would think the above answers would work but I ended up storing latitude/longitude as a float then normal comparisons worked as expected.


text:
Q: Syntax error when starting Rails server, RVM could be the issue? I am getting the following error when trying to start my Rails application in production for the first time:
/var/www/railsapp/config/initializers/session_store.rb:3: syntax error, unexpected ':', expecting $end ...sion_store :cookie_store, key: '_intranet_session' ^

I have read that this could be an issue with the current ruby version, so I installed RVM and updated the running version.
**root@rails ~#** ruby -v
ruby 1.8.7 (2010-04-19 patchlevel 253) [i686-linux], MBARI 0x8770, Ruby Enterprise Edition 2010.02
**root@rails ~#** rvm use 1.9.3
Using /usr/local/rvm/gems/ruby-1.9.3-p125
**root@rails ~#** ruby -v
ruby 1.9.3p125 (2012-02-16 revision 34643) [i686-linux]

I notice that the production version of Ruby is 1.9.3p125 but the development version is 1.9.3p0, not sure if that matters.
I then double checked the Rails version was the correct one:
**root@rails www/railsapp#** rails -v
Rails 3.1.4

I thought it would be worth restarting the server and then the application just for giggles but that didn't help either.
When reading a few other questions I noticed that if RVM isn't installed then running 'rvm list known' would fail, so I tested it:
**root@rails www/railsapp#** rvm list known
# MRI Rubies
[ruby-]1.8.6[-p420]
[ruby-]1.8.7[-p358]
[ruby-]1.8.7-head
[ruby-]1.9.1[-p431]
[ruby-]1.9.2-p180
[ruby-]1.9.2-p290
[ruby-]1.9.2[-p318]
[ruby-]1.9.2-head
[ruby-]1.9.3-preview1
[ruby-]1.9.3-rc1
[ruby-]1.9.3-p0
[ruby-]1.9.3[-p125]
[ruby-]1.9.3-head
ruby-head

# GoRuby
goruby

# TheCodeShop - MRI experimental patches
tcs

# JRuby
jruby-1.2.0
jruby-1.3.1
jruby-1.4.0
jruby-1.6.5
/usr/local/rvm/config/known

If it helps I am running the Turnkey Linux Rails appliance (TurnKey Linux 11.3 / Ubuntu 10.04 Lucid LTS).
I'm at a bit of a dead end of what to try, and advice would be greatly appreciated!

A: The problem is with the system environment.
What everyone failed to ask (including myself) was to see the full error logs. Doing so revealed he was using Passenger and it was loading the gem from 1.8.
More investigation shows RVM was loading as a system-wide install. So setting 1.9.3 as the system default and then re-install the passenger gem, then installing the apache2 module, then updating the apache configs fixed the issue.
This this box is dedicated for that one app, the above fix shouldn't be a problem. If you end up running more rails apps and need a more tightly defined environments, then read through this documentation http://beginrescueend.com/integration/passenger/. This will let you create a gemset for each app. I'm not sure how it will work with different ruby versions, as passenger will still have to be loaded from a single ruby install, but it might be able to run the scripts as a different ruby version?

A: I think you have a syntax error in your session_store.rb.
Take a look at the example here.
So, you probably want something like this instead of what you have:
Intranet::Application.config.session_store :cookie_store, :key => '_intranet_session'


text:
Q: QDbus: register multiple objects on same path If I understand, it is possible to use the registerObject method only once on the same path, even if objects have different interfaces in Q_ClassInfo.
Is this correct?

A: Yes it is correct.
But if you do want to register multiple objects at the same path, you can do so by declaring those objects (say childX, childY) as children of an object, say parentObject and then calling register object as:
registerObject(yourPath, parentObject, QDBusConnection::ExportAdaptors)

This will register objects childX and childY at path yourPath
Note: childX and childY must inherit QDBusAbstractAdaptor


text:
Q: Fetch fork of a huge Github repository without redownloading unmodified files I cloned a repository from Github with this commmand: git clone https://github.com/user1/huge_repo. This repo is huge, multiple gigabytes.
Someone made a small edit to one of the files and pushed their fork on Github. I want to fetch their version of the repo (let's say, it's on https://github.com/user2/huge_repo) without downloading gigabytes of data that are unmodified. Is this possible?

A: You can use your existing clone as a reference clone.  For instance, if your existing clone lives in $HOME/sources/github.com/user1/huge_repo:
git clone --reference $HOME/sources/github.com/user1/huge_repo https://github.com/user2/huge_repo

You may wish to add --dissociate here, or not; that part is up to you.  With or without --dissociate, your Git asks the GitHub Git what commits they have to send you.  This makes a list of commits to fetch.  Let's assume for concreteness that the list includes a123456.  Your Git now:

*

*looks at the reference clone's objects to see if you already have commit a123456:

*

*if yes, uses the existing copy and tells the other Git no thanks, I already have that commit, which avoids downloading it at all

*if no, tells the other Git yes please, send a123456 (which makes it offer the parents of a123456, and we add those to the list of commits to check).

Your Git repeats this for all the commits needed, including those added because your Git said yes, please send that one.  The result is the set of objects you must download, plus a list of hash IDs that you can borrow or steal from the reference clone.
Their Git (GitHub's) packages up the commits and supporting objects that must be sent, knowing which commits your Git has said you already have.  So you get only new objects, not existing ones, and furthermore, those new objects can be delta-compressed against your existing objects.
Now the --dissociate flag comes into play.  If you did not use it, your Git stores, in your user2/huge_repo clone, an "alternates" entry that lists the path name in which the objects you're borrowing live.  The effect of this is that you're now borrowing them for the foreseeable future: some time in the future, you might try to use a commit or supporting object from this clone that you didn't actually clone.  You borrowed it from the reference.
Your Git software will go back to the reference clone and try to use that object from there.  If it's still there, everything works, but if something has happened to that reference clone—such as removing it entirely or merely discarding the referenced object from that clone because it was unused there—then your user2/huge_repo clone may become unusable.  (You can restore the usability by retrieving the missing object, as long as there's some place to get it from.)
If, on the other hand, you did use --dissociate, your Git will, having cloned user2/huge_repo with reference to the reference clone, now copy the reference clone's objects into your new clone.  This means the original reference clone can be removed, or have objects collected out of it, without damaging the new clone.
If you can guarantee that objects won't vanish from the reference clone, you can leave it in place and save disk space—potentially quite a bit.  If not, you'll probably want to spend the disk space up front, to avoid having to repair a broken repository later.
(GitHub work around this kind of problem by never expiring any objects by default.  That's why you have to ask them to remove sensitive data.)


text:
Q: Regular Expression: how to match least characters (non-greedy) but no less than N I want to have such a method leastMatch(String input, String regExp, int n)
input is the input text, regExp is the regular expression and n is the minimal amount of characters the result has.
The return value is a head of the input text which matches the regular expression and contain
at least n characters.
e.g.
leastMatch("abababab", "(ab)+", 3) //returns "abab"
leastMatch("abababab", "(ab)+", 0) //returns ""
leastMatch("abababab", "(ab)+", 4) //returns "abab"

A: use this syntaxe:
(ab){3,}    --> 3 or more
(ab){0,2}   --> less than 3
(ab){2,5}   --> between 2 and 5
(ab){3}     --> 3

you can easily determine the number of ab you allow with n and ab length (2 in this example)


text:
Q: unable to exit my process after completion. NodeJS I'm working on a Node JS program to connect to a remote SFTP server to copy log files. I'm using this NPM package. ssh2-sftp-client
const main = () => {
  const servers = ['server list'];
  servers.forEach((s) => {
    const sftp = new Client();
    // Connect to the server
    sftp.connect({
      host: s,
      port: '22',
      username: '',
      password: '',
    }).then(() => logger.log(`Connected to ${s}`))
      // get list of directories
      .then(() => sftp.list(rootLogPath))
      .then((dirs) => {
        dirs.forEach((d) => {
          const target = createTargetDirectory(d.name);
          // list all files in the directory
          sftp.list(`${rootLogPath}/${d.name}`)
            .then((files) => {
              // filter only today's files
              const todayFiles = files.filter((f) => f.type === '-' && moment().format('MMDDYYYY') === moment(f.modifyTime).format('MMDDYYYY'));
              // copy today's files into target
              todayFiles.forEach((f) => {
                sftp.get(`${rootLogPath}/${d.name}/${f.name}`, `${target}/${f.name}`)
                  .then(() => logger.log(`Copied ${f.name} from ${d.name} located on ${s}`));
              });
            });
        });
        return sftp.end();
      })
      .catch(() => logger.log(`Connection to ${s} failed`));
  });
};

main();

The code is working as expected but the problem is I'm not able to terminate the session. The program just waits after its completed the copy files operation. The sftp.end() call is prematurely closing out connection before copying is complete. If I remove that program just waits after copy is completed.
I'm not sure where to write the sftp.end() line to terminate the program.
EDIT 1: Updated code using Promise.all and making use of async/await now.
Split my code into pieces and now making use of async/await for better readability. Program now ends fine. no more waiting or hanging but the problem is files are not copied. I see a console message "Copied files from source directory".
const copyTodayFiles = async (src) => {
  try {
    let fileList = await sftp.list(`${rootLogPath}/${src}`);
    fileList = fileList.filter(
      (f) => f.type === '-' && moment().format('MMDDYYYY') === moment(f.modifyTime).format('MMDDYYYY'),
    );
    const target = createTargetDirectory(src);

    if (target) {
      fileList.forEach(async (f) => {
        try {
          await sftp.get(`${rootLogPath}/${src}/${f.name}`, `${target}/${f.name}`);
          logger.log(`Copied ${f.name}`);
        } catch (error) {
          logger.log(`Failed to copy ${f.name}`);
        }
      });
      console.log(`Copied files from ${src}`);
    }
  } catch (error) {
    logger.log(`Failed to read files from ${src}`);
    logger.log(error);
  }
};

const workOn = async (server) => {
  sftp = new Client();

  const config = {
    host: server,
    port: '22',
    username: '',
    password: '',
  };

  try {
    await sftp.connect(config);
    logger.log(`Connection to ${server} is successful.`);
    const logDir = await sftp.list(rootLogPath);
    Promise.all(logDir.map((d) => copyTodayFiles(d.name))).then(() => sftp.end());
    // logDir.forEach(async (d) => copyTodayFiles(d.name));
  } catch (error) {
    logger.log(`Connection to ${server} failed.`);
    logger.log(error);
  }
};

const main = () => {
  const servers = ['server list'];
  Promise.all(servers.map((s) => workOn(s)));
};

main();

A: In short, when you have a "chain" of promises (a.then(() => b.then(() =>...) and you want to do something at the end of them, you simply add that thing to the last .then callback.
However, if you're making multiple promises, you need to wait until all of them are finished, which you can do using Promise.all (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all):
Promise.all([promise1, promise2]).then(...

To do that, you'll need to convert all of your forEach calls to instead be map calls, which return the promises they create.  Once you do that, the map operation will return an array of those promises, which you can use with Promise.all.


text:
Q: My  tag is not getting rendered in DOM using *ngFor in Angular I want to change the icon color on hover
I cannot do it with adding icon as image
I can do it by using svg tag with svg:hover{fill: red;} in css but my svg tag is not rendering in dom using *ngFor loop
I caanot render <path d="{{element.path}}" /> s some svg's have multiple path elements
side-panel.component.html

{{ element.svg }}

{{ element.description }}

side-panel.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-side-panel',
  templateUrl: './side-panel.component.html',
  styleUrls: ['./side-panel.component.css'],
})
export class SidePanelComponent implements OnInit {
  constructor() {}

  elements = [
    {
      icon: '../../../assets/sidebar-icons/1.svg',
      description: 'Tableau de bord',
      svg: `<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.3186 2.6664C11.2439 1.77787 9.7561 1.77787 8.68145 2.6664L3.29539 7.11964C2.80425 7.52572 2.5 8.16727 2.5 8.8663V15.8109C2.5 17.0784 3.45214 18 4.5 18H6.5V14.7478C6.5 12.4927 8.23415 10.5587 10.5 10.5587C12.7659 10.5587 14.5 12.4927 14.5 14.7478V18H16.5C17.5479 18 18.5 17.0784 18.5 15.8109V8.8663C18.5 8.16727 18.1958 7.52572 17.7046 7.11965L12.3186 2.6664ZM13.593 1.12502L18.979 5.57827C19.9494 6.38059 20.5 7.59705 20.5 8.8663V15.8109C20.5 18.066 18.7659 20 16.5 20H14.5C13.3954 20 12.5 19.1046 12.5 18V14.7478C12.5 13.4803 11.5479 12.5587 10.5 12.5587C9.45214 12.5587 8.5 13.4803 8.5 14.7478V18C8.5 19.1046 7.60457 20 6.5 20H4.5C2.23415 20 0.5 18.066 0.5 15.8109V8.8663C0.5 7.59705 1.05059 6.38059 2.02097 5.57827L7.40703 1.12502C9.22126 -0.375008 11.7787 -0.375006 13.593 1.12502Z" fill="#020A26"/>
</svg>`,
    },
    {
      icon: '../../../assets/sidebar-icons/2.svg',
      description: 'Dossiers',
      svg: `<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.5 2C3.39543 2 2.5 2.89543 2.5 4V16C2.5 17.1046 3.39543 18 4.5 18H16.5C17.6046 18 18.5 17.1046 18.5 16V7.375C18.5 6.27043 17.6046 5.375 16.5 5.375H11.5704C10.5673 5.375 9.63061 4.8737 9.07422 4.0391L8.01168 2.4453C7.82622 2.1671 7.51399 2 7.17963 2H4.5ZM0.5 4C0.5 1.79086 2.29086 0 4.5 0H7.17963C8.18269 0 9.11939 0.501303 9.67578 1.3359L10.7383 2.9297C10.9238 3.2079 11.236 3.375 11.5704 3.375H16.5C18.7091 3.375 20.5 5.16586 20.5 7.375V16C20.5 18.2091 18.7091 20 16.5 20H4.5C2.29086 20 0.5 18.2091 0.5 16V4Z" fill="#020A26"/>
</svg>`,
    },
    {
      icon: '../../../assets/sidebar-icons/3.svg',
      description: 'Session',
      svg: `<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M0.5 6C0.5 3.23858 2.73858 1 5.5 1H15.5C18.2614 1 20.5 3.23858 20.5 6V15C20.5 17.7614 18.2614 20 15.5 20H5.5C2.73858 20 0.5 17.7614 0.5 15V6ZM5.5 3C3.84315 3 2.5 4.34315 2.5 6V15C2.5 16.6569 3.84315 18 5.5 18H15.5C17.1569 18 18.5 16.6569 18.5 15V6C18.5 4.34315 17.1569 3 15.5 3H5.5Z" fill="#020A26"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M6.5 0C7.05228 0 7.5 0.447715 7.5 1V4C7.5 4.55228 7.05228 5 6.5 5C5.94772 5 5.5 4.55228 5.5 4V1C5.5 0.447715 5.94772 0 6.5 0Z" fill="#020A26"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.5 8C4.5 7.44772 4.94772 7 5.5 7H15.5C16.0523 7 16.5 7.44772 16.5 8C16.5 8.55228 16.0523 9 15.5 9H5.5C4.94772 9 4.5 8.55228 4.5 8Z" fill="#020A26"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.5 15C13.5 14.4477 13.9477 14 14.5 14H15.5C16.0523 14 16.5 14.4477 16.5 15C16.5 15.5523 16.0523 16 15.5 16H14.5C13.9477 16 13.5 15.5523 13.5 15Z" fill="#020A26"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M14.5 0C15.0523 0 15.5 0.447715 15.5 1V4C15.5 4.55228 15.0523 5 14.5 5C13.9477 5 13.5 4.55228 13.5 4V1C13.5 0.447715 13.9477 0 14.5 0Z" fill="#020A26"/>
</svg>`,
    },
  ];
  ngOnInit(): void {}
}

A: If you want to render the whole svg tag in the dom you should put it in innerHtml of another parent element and sanitize the svg content before you render it:

In your component class:
  constructor(private sanitizer: DomSanitizer) {
    this.elements.forEach(
      (e) => (e.svg = this.sanitizer.bypassSecurityTrustHtml(e.svg))
    );
  }

Now to change the color of your svg on hover you should:

*

*remove the fill attribute from your path and your svg

*apply a class on your parent div

*set the fill style for your svg:
.path { fill: green; }
.path:hover { fill: red; }

A: for using svg icons in angular project exist a problem:
1.create a file for all of svg icons [example this project in the svg-icons directory exist a file => svg-icons-repo.component.ts]
2.using this site [https://svgsprit.es/] can convert svg icons to a standard model
3.then everywhere of project that you need to use svg icons call it with [id]
I create this project with your svg icons


text:
Q: input() в sublime text Всем привет!
Только недавно начал изучать Python.
Приступая к изучению "ввода данных и цикла while", первое что я увидел было:

«ПРИМЕЧАНИЕ Sublime Text и многие другие текстовые редакторы не
запускают программы, запрашивающие входные данные у пользователя. Вы
можете использовать эти редакторы для создания таких программ, но
запускать их придется из терминального окна.»

Sublime мне крайне "зашел", попробовал PyCharm и VS Code - пока тяжело для восприятия.
Простого решения, как сделать Sublime работоспособным я не нашел.
Помогите, пожалуйста, и объясните на пальцах - что нужно установить в Sublime, чтобы я продолжил изучать язык и не пересаживался на другое ПО.

A: В Sublime ничего устанавливать не нужно да и нечего, у него нет встроенного интерпретатора. Вы с ним прекрасно можете начинать изучение Python. Данное примечание говорит лишь о том, что запускать свой код вы сможете только из консоли.

A: Sublime Text уже "готов к использованию", в него не нужно подгружать ничего стороннего – просто откройте файл с расширением вашего языка программирования и начните писать код – Sublime сам выберет синтаксис для ЯП.
То есть вы просто не сможете что либо запустить в Sublime – только через консоль. Для начала обучения на Python нужно зайти на официальный сайт, скачать установщик среды Python, открыть его и следовать инструкциям.
Удачи с учёбой! :))


text:
Q: Removing parentheses around a date using regex Let's say I have a string like this:

This is my (2019) awesome string (that I want to modify)

The date in it has to stay, but without parentheses. Meanwhile everything else that is in parentheses has to go. So I would like to achieve this:

This is my 2019 awesome string

I am able to locate the date using this:
\b(201\d{1})\b

And I am also able to locate anything in parentheses using this:
(\(.*\))

But I only want to remove everything if it's not a date in parentheses or else I want to keep the date only removing the parentheses. Is there a way to do this without using if else?

A: In Python 3.5+ you may use
s = re.sub(r'\((\d{4})\)|\([^()]*\)', r'\1', s)

If there is a ( + 4 digits + ), only keep the 4 digits, else, remove the match.
See the regex demo.
Details

*

*\((\d{4})\) - (, then Capturing group 1 matching four digits and then )

*| - or

*\([^()]*\)  - a (, then 0+ chars other than ( and ), and then ).

The replacement is just \1 backreference to the value of Group 1.
NOTE: To use this approach in Python versions before 3.5 you will have to use a lambda expression as the replacement argument (due to a bug):
s = re.sub(r'\((\d{4})\)|\([^()]*\)', lambda x: x.group(1) if x.group(1) else '', s)

A: Just do it with two nested calls to re.sub:
re.sub(r' ?\(.*\)', '', re.sub(r'\((\d{4})\)', '\\1', my_string))

The inner regex looks for 4-digit numbers in parentheses and removes the parentheses. The outer one removes everything in parentheses that is left (including an optional space in the beginning).


text:
Q: I am trying to retrieve information from a Sharepoint list when clicking an image I have a Sharepoint list with 3 columns: Image, Title, and Description. I am trying to retrieve the items via ajax. The images I can get successfully and the idea is that when I click on the images I retrieve the title and description for the clicked image. What I am getting in the console, after clicking the image,is the first title and first description on the list regardless of the images I click on. After clicking the image, the title and description must append to a div with the id of #captionContainer.
var buildMainCarousel = function (items) {
    var flickitySlider = $('#flickityCarousel');
    var carouselContent;

    for (var i = 0; i < items.length; i++) {
        carouselContent = '
' +
            '' +
            '
';
        console.log(carouselContent);
        flickitySlider.append(carouselContent);
    }

};

var buildCaptions = function (items) {
    var captionContainer = $('#captionContainer');

 $(".carousel-cell img").click(function() {
    var clickedThumb= $(this);
        var title = items[i].Title;
        var description = items[i].Description;
       console.log(title);
        console.log(description);

});

};

var url1 = "/FunZone/_api/web/lists/GetByTitle('funZone')/items";
var handle_ajax = function (url) {
    $.ajax({
        url: url,
        method: "GET",
        headers: {
            Accept: "application/json; odata=verbose"
        },
        success: function (data) {
            var items = data.d.results;
            console.log(items);

            buildMainCarousel(items);
            buildCarouselNav(items);
            buildCaptions(items);
        },
        error: function (data) {
            console.log("Error: " + data);
        }

    });

};

handle_ajax(url1);

A: We can use Bootstrap Image carousel and SharePoint REST API with jQuery Ajax to achieve it, the following example for your reference.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            Previous

            Next


text:
Q: Forming Object Using Filter and Map method I have a object which contains information of sources:
multiplierInformation = [
{
groupName: 'RAW MATERIALS',
sourceType : [
{
name: 'Cement',
quantityDescription: '',
quantityFlag: false
}
]
}
]
I need to filter out values based on name property.
Please suggest.

A: basically this should work:

let arrayComingFromBackend = [{
  controls: [],
  count: 1,
  description: "",
  id: null,
  key: "cement",
  name: "Cement",
  quantity: 1,
  sourceFormulaId: "31de1317-f5a5-4620-a854-fcfed851ac78",
  sourceSpecifications: [],
  sourceType: "RAW MATERIALS",
  usageParameters: [],
  length: 1
}];

let multiplierInformation = [{
    groupName: 'RAW MATERIALS',
    sourceType: [{
      name: 'Cement',
      quantityDescription: '',
      quantityFlag: false
    }]
  },
  {
    groupName: 'AIR TRANSPORT',
    sourceType: [{
        name: 'Helicopter',
        quantityDescription: 'Number of Flights',
        quantityFlag: true
      },
      {
        name: 'Air Freight',
        quantityDescription: 'Number of Flights',
        quantityFlag: true
      }
    ]
  },
  {
    groupName: 'OTHER EQUIPMENT',
    sourceType: [{
        name: 'Non-Road Vehicle',
        quantityDescription: 'Number of this Equipment',
        quantityFlag: true
      },
      {
        name: 'Forklift - Diesel',
        quantityDescription: 'Number of Forklifts',
        quantityFlag: true
      },
      {
        name: 'Crane - Diesel',
        quantityDescription: 'Number of Cranes',
        quantityFlag: true
      },
      {
        name: 'Stationary Equipment',
        quantityDescription: 'Number of this Equipment',
        quantityFlag: true
      }
    ]
  },
  {
    groupName: 'FACILITY/BUILDING',
    sourceType: [{
        name: 'Office',
        quantityDescription: '',
        quantityFlag: false
      },
      {
        name: 'Warehouse and Storage',
        quantityDescription: '',
        quantityFlag: false
      },
      {
        name: 'Other',
        quantityDescription: '',
        quantityFlag: false
      }
    ]
  },
  {
    groupName: 'FRAC EQUIPMENT',
    sourceType: [{
        name: 'Tier 2',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      },
      {
        name: 'Dual Fuel T2',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      },
      {
        name: 'Tier 4F',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      },
      {
        name: 'Gas Turbine (based on DLE) 940 BTU Gas',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      },
      {
        name: 'Gas Turbine (based on WLE) 940 BTU Gas',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      },
      {
        name: 'Gas Turbine (based on GE SAC) 940 BTU Gas',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      },
      {
        name: 'Grid Power (Using TX Ercot Grid Emissions)',
        quantityDescription: 'Number of Engines',
        quantityFlag: true
      }
    ]
  },
  {
    groupName: 'CEMENT EQUIPMENT',
    sourceType: [{
        name: 'Elite Tier 3',
        quantityDescription: 'Number of Units',
        quantityFlag: true
      },
      {
        name: 'Elite Tier 4i',
        quantityDescription: 'Number of Units',
        quantityFlag: true
      },
      {
        name: 'Elite Rebuild',
        quantityDescription: 'Number of Units',
        quantityFlag: true
      },
      {
        name: 'Red Tiger',
        quantityDescription: 'Number of Units',
        quantityFlag: true
      }
    ]
  },
  {
    groupName: 'RAIL TRANSPORT',
    sourceType: [{
      name: 'Rail Transport',
      quantityDescription: 'Number of Trips',
      quantityFlag: true
    }]
  },
  {
    groupName: 'RIGS',
    sourceType: [{
        name: 'Halliburton Controlled Rig',
        quantityDescription: 'Number of Trips',
        quantityFlag: false
      },
      {
        name: '3rd Party Controlled / Rig Power',
        quantityDescription: 'Number of Trips',
        quantityFlag: false
      }
    ]
  },
  {
    groupName: 'ROAD TRANSPORT',
    sourceType: [{
        name: 'Passenger Car',
        quantityDescription: 'Number of Vehicles',
        quantityFlag: true
      },
      {
        name: 'Light Duty Vehicle',
        quantityDescription: 'Number of Vehicles',
        quantityFlag: true
      },
      {
        name: 'Medium Duty Vehicle',
        quantityDescription: 'Number of Vehicles',
        quantityFlag: true
      },
      {
        name: 'Heavy Duty Vehicle',
        quantityDescription: 'Number of Vehicles',
        quantityFlag: true
      },
      {
        name: 'Bus',
        quantityDescription: 'Number of Vehicles',
        quantityFlag: true
      }
    ]
  },
  {
    groupName: 'SEA TRANSPORT',
    sourceType: [{
        name: 'Halliburton Controlled Vessel',
        quantityDescription: 'Number of Vessels',
        quantityFlag: true
      },
      {
        name: '3rd Party Controlled Vessel',
        quantityDescription: 'Number of Vessels',
        quantityFlag: true
      }
    ]
  },
  {
    groupName: 'WASTE',
    sourceType: [{
        name: 'Waste Disposal',
        quantityDescription: 'Number of Vessels',
        quantityFlag: false
      },
      {
        name: 'Oil Contaminated Waste',
        quantityDescription: 'Number of Vessels',
        quantityFlag: false
      },
      {
        name: 'Lithium Battery',
        quantityDescription: 'Number of Vessels',
        quantityFlag: false
      },
      {
        name: 'Waste Recycling',
        quantityDescription: 'Number of Vessels',
        quantityFlag: false
      }
    ]
  },
  {
    groupName: 'PS EQUIPMENT',
    sourceType: [{
        name: 'PS Stationary Equipment',
        quantityDescription: 'Number of this Equipment',
        quantityFlag: false
      },
      {
        name: 'PS Self-Driving Equipment',
        quantityDescription: 'Number of this Equipment',
        quantityFlag: false
      }
    ]
  }
]

let res = multiplierInformation.filter(information => {
  for (const item of information.sourceType) {
    return arrayComingFromBackend.every(f => {
      const [key, value] = Object.entries(f)[0];
      return item[key] == value
    });
  }
});

let arrayComingFromBackend = [{
    controls: [],
    count: 1,
    description: "",
    id: null,
    key: "cement",
    name: "Cement",
    quantity: 1,
    sourceFormulaId: "31de1317-f5a5-4620-a854-fcfed851ac78",
    sourceSpecifications: [],
    sourceType: "RAW MATERIALS",
    usageParameters: [],
    length: 1
}];

let res = multiplierInformation.filter(information => {
    for (const item of information.sourceType) {
        return arrayComingFromBackend.every(f => {
            const [key, value] = Object.entries(f)[0];
            return item[key] == value
        });
    }
});

console.log(res);

A: <script>
/* Printing the name of students who play
basketball using filter and map method
simultaneously. */

// Taking an array of Student object
let students = [
    { id: "001", name: "Anish", sports: "Cricket" },
    { id: "002", name: "Smriti", sports: "Basketball" },
    { id: "003", name: "Rahul", sports: "Cricket" },
    { id: "004", name: "Bakul", sports: "Basketball" },
    { id: "005", name: "Nikita", sports: "Hockey" }
]

/* Applying filter function on students array to
retrieve those students Objects who play
basketball and then the new array returned by
filter method is mapped in order to get the name
of basketball players instead of whole object.*/
let basketballPlayers = students.filter(function (student) {
    return student.sports === "Basketball";
}).map(function (student) {
    return student.name;
})

console.log("Basketball Players are:");

// Printing out the name of Basketball players
basketballPlayers.forEach(function (players) {
    console.log(players);
});


text:
Q: populate a div-table from code behind trying to dynamically populate a div from code behind, with a table, and each time the loop goes round add another row to the table....
Table table = new Table();
            table.ID = "Table1";
            mapInnerDiv.Controls.Add(table);

            foreach (Layer l in Layers)
            {
                string splitURL = l.URL.Split('/')[7];

                TableRow row = new TableRow();
                TableCell cell = new TableCell();

                TextBox tb = new TextBox();

                tb.ID = splitURL;

                    // Add the control to the TableCell
                    cell.Controls.Add(tb);
                    // Add the TableCell to the TableRow
                    row.Cells.Add(cell);
            }

the above code does not populate the div. from the console I can see that a table is added to the div, but it is empty.
Adding to the innerHTML such as mapInnerDiv.InnerHtml = "this is a text post";
 will display this message but if I use  tags and try to add to the div from here it will prove difficult when adding a new row??
any ideas on where my loop is going wrong thanks

A: Your code needs some re-arranging and you need to add the rows to your table.
Table table = new Table();
table.ID = "Table1";

foreach (Layer l in Layers)
    {
    string splitURL = l.URL.Split('/')[7];

    TableRow row = new TableRow();
    TableCell cell = new TableCell();
    TextBox tb = new TextBox();
    tb.ID = splitURL;
    // Add the control to the TableCell
    cell.Controls.Add(tb);
    // Add the TableCell to the TableRow
    row.Cells.Add(cell);
    table.Rows.Add(row);
    }
mapInnerDiv.Controls.Add(table);

Add the table to the div, after it is fully built.
And make sure that mapInnerDiv is defined as such:

A:
I can see that a table is added to the div, but it is empty

This is because no rows are being added to your table.
Add the following code table.Rows.Add(row) to add the row to your table underneath this line:
row.Cells.Add(cell);


text:
Q: Standard Filters for Report I've been doing some work on gathering info from a report using its metadata in apex. In this picture is basically what I want to extract:

Currently, I am confused as to why my method for getting the standard filters is returning nothing. Below is my code on what I have so far.
// Get the report ID and folderName
List <Report> reportInfo = [SELECT ID, FolderName FROM Report where Name = 'Some New Report'];

// Get report ID
String reportId = (String)reportInfo.get(0).get('Id');

// Use report ID to get report Metadata
Reports.ReportMetadata metadata = Reports.ReportManager.describeReport(reportId).getReportMetadata();

// this line is the problem
System.debug('Standard Filters: ' + metadata.getStandardFilters());

The very last line simply returns () . I tried adding getName() and getValue() to the end of it but it gives me an error. Any help is much appreciated. Thanks.

A: That's because you have zero standard filters on that report.

Standard filters vary by report type. For example, standard filters
for reports on the Opportunity object are Show, Opportunity Status,
and Probability.

Based on your screenshot,

*

*Show Me is scope which you can see in the Report metadata. You can get this with getScope()

Defines the scope of data on which you run the report. For example,
whether you want to run the report against all opportunities,
opportunities you own, or opportunities your team owns. Valid values
depend on the reportType. For example, for Accounts reports:

*

*MyAccounts

*MyTeamsAccounts

*AllAccounts

*

*Created Date, as it's a date filter that was provided with the report automatically, will be returned by getStandardDateFilters() which has a distinction from standard filters.

Contains information about standard date filter available in the
report—for example, the API name, start date, and end date of the
standard date filter duration as well as the API name of the date
field on which the filter is placed.

Any other filters you customize on that report will be retrieved with getReportFilters()


text:
Q: Improved way to build nested array of unique values in javascript The setup:
I have a nested html table structure that displays hierarchical data, and the individual rows can be hidden or shown by the user. Each row has a dom id that is comprised of the level number plus the primary key for the record type on that level. I have to have both, because each level is from a different database table, so the primary key alone is not unique in the dom.
example: id="level-1-row-216"

I am storing the levels and rows of the visible elements in a cookie, so that when the page reloads the same rows the user had open are can be shown automatically. I don't store the full map of dom ids, because I'm concerned about it getting too verbose, and I want to keep my cookie under 4Kb.
So I convert the dom ids to a compact json object like this, with one property for each level, and a unique array of primary keys under each level:
{
    1:[231,432,7656],
    2:[234,121],
    3:[234,2],
    4:[222,423],
    5:[222]
}

With this structure stored in a cookie, I feed it to my show function and restore the user's previous disclosure state when the page loads.
The area for improvement:
I'm looking for better option for reducing my map of id selectors down to this compact format. Here is my function:
function getVisibleIds(){

    // example dom id: level-1-row-216-sub

    var ids = $("tr#[id^=level]:visible").map(function() {
        return this.id;
    });

    var levels = {};

    for(var i in ids ) {
        var id    = ids[i];
        if (typeof id == 'string'){
            if (id.match(/^level/)){

                // here we extract the number for level and row
                var level = id.replace(/.*(level-)(\d*)(.*)/, '$2');
                var row   = id.replace(/.*(row-)(\d*)(.*)/, '$2');

                // *** Improvement here? ***
                // This works, but it seems klugy. In PHP it's one line (see below):

                if(levels.hasOwnProperty(level)){
                if($.inArray(parseInt(row, 10) ,levels[level]) == -1){
                        levels[level].push(parseInt(row, 10));
                }
                } else {
                    levels[level] = [parseInt(row, 10)];
                }

            }
        }
    }

    return levels;
}

If I were doing it in PHP, I'd build the compact array like this, but I can't figure it out in javascript:
foreach($ids as $id) {
    if (/* the criteria */){
         $level = /* extract it from $id */;
         $row   = /* extract it from $id */;
         $levels[$level][$row];
    }
}

A: so there is some duplicate/unneed stuff in your function:
if you do this
var ids = $("tr#[id^=level]:visible").map(function() {

and this
for(var i in ids ) {

you are looping twice over your matching ids
isnt id always a string here???
if (typeof id == 'string'){

this shouldnt be necessary, because of your jQuery-Selector: "tr#[id^=level]:visible"
your matching elements should ALWAYS start with 'level'
if (id.match(/^level/)){

all in all i think this should be shorter (couldnt test it, please provide a jsfiddle next time, would be easier ;-))
function getVisibleIds(){

  // example dom id: level-1-row-216-sub
  var level, parsed, levels = {};

  $("tr#[id^=level]:visible").map(function() {
    // here we extract the number for level and row
    level   = this.id.replace(/.*(level-)(\d*)(.*)/, '$2');
    parsed  = parseInt(this.id.replace(/.*(row-)(\d*)(.*)/, '$2'), 10);

    // i like this more
    if(!levels.hasOwnProperty(level)) { levels[level] = []; }
    if($.inArray(parsed, levels[level]) === -1) {
        levels[level].push(parsed);
    }
  });

  return levels;
}

A: My attempt
function getVisibleIds() {

    var parts, level, row, levels = {};

    var ids = $("tr#[id^=level]:visible").each(function (index, el) {

        parts = el.id.split("-"); // no regex :)
        level = parts[1];
        row = parts[3];

        if (!levels[level]) { levels[level] = []; }
        if ($.inArray(row, levels[level]) + 1) { levels[level].push(row); }

    });
    return levels;
}

A: function getVisibleIds(){

    // example dom id: level-1-row-216-sub

    var levels = {};

    var ids = $("tr#[id^=level]:visible")
                    .map(function() {

                        return this.id;
                    })
                    .each(function (index, id) {

                        if (!id || typeof id !== 'string') {
                            return;
                        }

                        if (id.match(/^level/) === false) {
                            return;
                        }

                        var level = id.replace(/.*(level-)(\d*)(.*)/, '$2');
                        var row   = id.replace(/.*(row-)(\d*)(.*)/, '$2'),
                            primaryKey = parseInt(row, 10);

                        if (!levels[level]) {
                            levels[level] = [];
                        }

                        var arr = levels[level];

                        if (arr.indexOf(primaryKey) === -1) {
                            levels[level].push(primaryKey);

                        }
                    });

    return levels;

}

The key point to note is, you can access a property of an object either using . (dot notation) or as an accessor [].


text:
Q: How i can disable JPanel when JFrame Start I want to disable a JPanel at the start of JFrame
I know the code that I have to use but I do not know where I should put it
public class Fenetre1 extends JFrame {
//code JFrame
    private class Affichage implements ActionListener {
//action
}
}
public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
Fenetre1 f = new Fenetre1 ();
f.panel.setEnabled(false);

    }

A: You can setEnabled(false) when you create the JPanel.  If you want to toggle enabling the JPanel, you should probably use a listener.
Notes from Java documentation (https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html)

*

*Note: Disabling a component does not disable its children.

*Note: Disabling a lightweight component does not prevent it from receiving MouseEvents.
JFrame jframe = new JFrame();

JPanel jpanel = new JPanel();
jpanel.setEnabled(false);

jframe.add(jpanel);

A: Maybe JPanel can't be focused but Objects like JTextField or JTextArea are focus-able.
If you have some objects like those in the JPanel , then use textArea.setFocusable(false).
And you can try jPanel.setEnabled(false).

A: Your answer inspired me a bit, I use a component table in the JPanel
so,I went through the entire table and disabled each component
I put the code in the class inheriting the JFrame:
 for(int j= 0;j<tab_component.length;j++)
            {
                    tab_buttonsOperateur[j].setEnabled(false);
            }

thanks anyway


text:
Q: Using another project's methods using createProcess Lets say I have a ".c" file with some methods, and I create a new project where I need to make a process that uses the methods from the previouse project....All under the same solution.
In the current project that I'm working on I create a process with the method "createProcess",
and then I pass to the "CommandLine"  parameter the ".exe" file that belong for the 1st project,the one with the ".c" file (where all my methods are).
How is it possible to access these methods & use them?

A: The common 'methods' (in C these are called functions) should extracted to be in their own source-code file without a 'main'.  The function prototypes should be in their own header file.  Make sure the functions are not declared as 'static'.
Now #include the header file in the two main source files.  Each project should have two C source files, the one containing 'main' and the one containing the common functions - so the common functions source file is in two (or more) projects.
Longer term it would be better to put the common functions into their own DLL - but that's maybe for another day.


text:
Q: Let G be an affine connected algebraic  group.  When a subvariety of G with codimension one  is a subgroup.    Let G be an affine connected algebraic group, and K[G] be its coordinate ring. Let Y  be a subvariety of G defined as a zero set for some  f in K[G]. For which f,  Y is a closed subgroup of G

A: It is perhaps easiest to express this in terms of Hopf algebras. The coordinate ring $K[G]$ has the structure of a Hopf algebra; the subvariety $Y$ is a closed subgroup of $G$ if and only if the ideal $(f)$ is a Hopf ideal, i.e.
\begin{align*}
\Delta(f) &\in (f) \otimes K[G] + K[G] \otimes (f); \\\\
\epsilon(f) &= 0; \\\\
S(f) &\in (f),
\end{align*}
where $\Delta$, $\epsilon$ and $S$ are the comultiplication, counit and antipode of the Hopf algebra $K[G]$, respectively.
(See, for instance, Milne's freely available course notes on linear algebraic groups.)


text:
Q: Displaying the elements in a list of expressions I have a list containing expressions of the form: a-I-J-K (those are not expressions but rather a codification of variables, but that's not the point for this question).
I want to write every expression in the list by using the following code:
display(L) :- member(p-I-J-K, L), write(I), nl, fail.
display(_).

With this, I'm trying to make Prolog unify p-I-J-K with all the elements in L, and it works, because it prints them. The only problem is that this code keeps printing the elements in a loop that doesn't stop, and I can't really understand why.
In the example I'm just writing I to illustrate the problem, in the real problem I'm writing a meaningful string.
So basically, why does this code never stop, and what would be the proper way to do it?

A: Not reproducible. The following executes with swipl just nicely:
:- initialization(main).

d(L) :- member(p-I-J-K, L), write(I), nl, fail.
d(_).

main :- d([p-a-c-k,p-o-l-l,p-i-c-k]),halt.

prints 'a', 'o', 'i' on separate lines. Please post a runnable example, ideally a stand-alone script that does not require any messing around with the interactive interpreter.
The proper way to do it would be not to reinvent square wheels in the first place:
foreach(member(p-I-J-K, L), write(I))

should do it.


text:
Q: distributions of the test statistic when the null hypothesis is false In null hypothesis significance testing, when a specific alternative hypothesis is specified (e.g., power analysis), why the distribution of the test statistic when the alternative hypothesis is true becomes flattened (and asymmetric) as effect size increases?
For example, in the one-sample t-test, the test statistic is
$t=\frac{\bar{x}-a}{s/\sqrt{n}}$ where $a$ is the value from the null hypothesis. From this formula, it looks like the test statistic values are only shifted by its mean as $s$ is independent of the effect size. However, when I plot them, I see the distributions are skewed and flattened.
n <- 10  # sample size
s <- 10  # standard deviation
nsim <- 10000
tval1 <- tval2 <- rep(NA,nsim)
for(i in 1:nsim){
x1 <- rnorm(n,mean=20,sd=s)    # effect size 20
x2 <- rnorm(n,mean=40,sd=s)    # effect size 40
tval1[i] <- (mean(x1)-0)/(sd(x1)/sqrt(n))
tval2[i] <- (mean(x2)-0)/(sd(x2)/sqrt(n))
}

hist(tval1,breaks=25,freq=FALSE,xlim=c(-10,40),ylim=c(0,0.4),col=rgb(0.1,0.1,0.1,0.5),main="",xlab="test statistic")
hist(tval2,breaks=50,freq=FALSE,add=TRUE, col=rgb(0.8,0.8,0.8,0.5))
curve(dt(x,df=n-1),add=TRUE) # null distribution

A: Both $\bar{x}$ and $s$ are random variables here, although as you noted, they are independent. In general, there's no rule that says the ratio of two independent variables should be symmetric. This is particularly the case when neither your numerator $\bar{x}$ nor denominator $s$ have mean 0. FYI, there is a known distribution for the $t$ statistic under the alternative: https://en.wikipedia.org/wiki/Noncentral_t-distribution.


text:
Q: How to loop in a function? I wanted to loop my code with function but i don't know how to. I already tried using the while() loop and place it before int main () { but resulting in an error, since I only know how to loop but without the functions. What I meant is to where to put the for,while or do loop in the code, is it inside before int main() or after? I am still new in C++.
code:
 #include <iostream>
#include <string>

using namespace std;

string getName();

string getproductCategory ();

char getproductCode ();

int getproductQuantity ();

int customerDistance (int,int);

int calculatetotalPrice (string,char,int);

int distanceInKM (int);

void displayALL (int totalprice);

int main () {

    string name123,category;
    int quantity,priceperkm,totalprice,km,price;
    char productcode;

    name123 = getName();

    category = getproductCategory ();

    productcode = getproductCode ();

    quantity = getproductQuantity();

    priceperkm = customerDistance(km,price);

    totalprice = calculatetotalPrice(category,productcode,quantity);

    displayALL (totalprice);

    return 0;}

string getName (){
    string name123;
    cout << "Enter name : ";
    cin >> name123;
    return name123;
}

string getproductCategory (){
    string category;
    cout <<"Enter category : ";
    cin >> category;
    return category;}

char getproductCode(){
    char productcode;
    cout <<"Enter product code : ";
    cin >> productcode;
    return productcode;
}

int getproductQuantity(){
    int quantity;
    cout <<"Enter quantity : ";
    cin >> quantity;
    return quantity;
}

int customerDistance(int km, int price){
    int priceperkm;
    cout <<"Enter distance (km) : ";
    cin>>km;

    if (km >= 20)
    priceperkm = 1.00*km;
    else if (km >= 20 && km <= 80)
    priceperkm = 1.50*km;
    else if (km > 100)
    priceperkm = 2.00*km;

    return priceperkm;
}

int calculatetotalPrice (string category,char productcode,int quantity){
    int price,totalprice,priceperkm;
    string description1,description2;

    if (category == "NP456" && productcode == 'P'){
    price = 158.50*quantity;
        description1 = "Promising Love";
            description2 = "New Product";}
    else if (category == "NP456" && productcode == 'E'){
    price = 198.50*quantity;
        description1 = "Endless Love" ;
            description2 = "New Product";}
    else if (category == "BS123" && productcode == 'F'){
    price = 58.50*quantity;
        description1 = "Ferrero Choclate Foil Balloon";
            description2 = "Best Seller";}
    else if (category == "BS123" && productcode == 'B'){
    price = 188.50*quantity;
        description1 = "Birthday Cake Mania";
            description2 = "Best Seller";}

totalprice = price * priceperkm;

return totalprice;
}

void displayALL(int totalprice){
    string name123,description1;
    int quantity;
    cout <<"WELCOME TO HARMONY GIFT SHOP - "<<name123<<endl;
    cout <<"You have purchased : "<<description1<<endl;
    cout <<"Quantity :"<<quantity<<endl;
    cout <<"You should pay : RM "<<totalprice<<endl;
}

A: Check out the while loop. You can have it run while a boolean evaluates to true and everytime the while runs std::cin (read console) and check if it is equivalent to a phrase, like stop and if it is set the aformentioned boolean to stop, halting the loop.


text:
Q: How to add some horizontal space unless it is the end of the line? I am looking for a command \customhspace{} such that

*

*AAA \customhspace{2pt} BBB is the same as AAA \hspace{2pt} BBB: it adds some space between AAA and BBB.

*\hfill AAA \customhspace{2pt} is the same as \hfill AAA: in this case, there is no space added after AAA.
So, in a way \customhspace{} adds space only if we are not at the end of a line, "pushed" by a \hfill.
Is it possible to have such a command? If yes, how to do it?

A: This question isn't really about removing spaces at the end of a line, but about removing them at the end of a paragraph.
All skips at the end of a line are already ignored automatically.
A possible solution would be to define \customhspace as follows:
\newcommand*\customhspace[1]{\unskip\hspace{#1}\ignorespaces}

This doesn't quite behave like an ordinary \hspace in the middle of a line, however, since it removes a space preceding or following it (which includes ordinary spaces).
Whether this is an advantage or a disadvantage depends on how you intend to use this macro.
Demonstration:
Here is a little sample document that demonstrates how this works.
Note that it matters whether an \hspace{...} is surrounded by spaces, while it does not for \customhspace.
\documentclass{article}

\newcommand*\customhspace[1]{\unskip\hspace{#1}\ignorespaces}

\begin{document}

AAA \hspace{2em} BBB

AAA \hspace{2em}BBB

AAA\hspace{2em} BBB

AAA\hspace{2em}BBB

AAA \customhspace{2em} BBB

\hfill AAA \hspace{2em}

\hfill AAA\hspace{2em}% % <- see explanation below

\hfill AAA\customhspace{2em}

\hfill AAA

\end{document}

Explanation:
TeX removes the last item in a paragraph if it is glue (a skip/space), but only one piece of glue will be removed in this way.
This means that if you have multiple consecutive spaces at the end of a paragraph, all but the last one will still be there.
A paragraph produced by \hfill AAA \hspace{2pt}, followed by a newline, actually ends with three pieces of glue:

*

*The explicit space character preceding \hspace.

*The \hspace{2pt} itself

*The newline also produces a space.

If you remove the preceding space and comment out the newline (see What is the use of percent signs (%) at the end of lines?), \hspace{2pt} will be the last item in the paragraph and will be removed.
The following paragraph will not have a space at the end:
\hfill AAA\hspace{2pt}%

You don't want to do this every time, of course.
In the definition for \customhspace above, I instead included an \ignorespaces to make TeX ignore skips directly following this command, and \unskip to remove the preceding space, if there is one.

A: This would seem to do it except in one regard which may or may not be of concern to the OP.  Spaces following \customhspace{}, if they exist, are gobbled.  And I only mention this exception because the OP, in providing code snippets, had spaces surrounding the invocation of \customhspace.  In general, I would not be adding extra spaces around an \hspace type command.
\documentclass{article}
\makeatletter
\newcommand\customhspace[1]{\@ifnextchar\par{}{\hspace{#1}}}
\makeatother
\begin{document}
    AAA\customhspace{2pt}BBB no extra spaces

    AAA\hspace{2pt}BBB

    \smallskip

    AAA \customhspace{2pt} BBB spaces before/after

    AAA \hspace{2pt} BBB

    \smallskip

    AAA\customhspace{2pt} BBB space after

    AAA\hspace{2pt} BBB

    \smallskip

    AAA \customhspace{2pt}BBB space before

    AAA \hspace{2pt}BBB

    \smallskip

    no space before\hfill AAA\customhspace{2pt}

    \hfill AAA

    \smallskip

    space before\hfill AAA \customhspace{2pt}

    \hfill AAA
\end{document}


text:
Q: How to control 3D CSS cube with controls I'm trying to control the cube with arrows (up, down, left, right arrow controls). The problem i'm having is nothing is going on when i press the arrows i'm not sure if it's a Javascript issue or CSS keyframe issue. Another problem i'm having is that once the cube rotates i cant get it to rotate in the same direction when the key is pressed again or keep it in state. No JQuery please. This is what i have tried:

window.addEventListener('load', function(){
    let rotate = document.querySelectorAll('.rotate');
    let container = document.querySelector('.container');

function rotLeft (key) {
    element.animate(rotateLeft);
}

function rotRight (key) {
    element.animate(rotateRight);
}

function rotUp (key) {
    element.animate(rotateUp);
}

function rotDown (key) {
    element.animate(rotateDown);
}

if (key.keyCode == "37"){
    rotLeft();
}
else if (key.keyCode == "39"){
    rotRight();
}
else if (key.keyCode == "38"){
    rotUp();
        }
else if (key.keyCode == "40"){
    rotDown();
}

});
.cube {
  width: 200px;
  height: 200px;
  position: relative;
  transform-style: preserve-3d;
  transform: translateZ(-100px);
  transition: transform 1s;
}

.cube.show-front  { transform: translateZ(-100px) rotateY(   0deg); }
.cube.show-right  { transform: translateZ(-100px) rotateY( 90deg); }
.cube.show-back   { transform: translateZ(-100px) rotateY(-180deg); }
.cube.show-left   { transform: translateZ(-100px) rotateY(  -90deg); }
.cube.show-top    { transform: translateZ(-100px) rotateX( -90deg); }
.cube.show-bottom { transform: translateZ(-100px) rotateX(  90deg); }

html, body {
  height: 100%;
}

.side,
.container {
  width: 160px;
  height: 160px;
}

.side {
  position: absolute;
  height: 160px;
  width: 160px;
  border: 2px solid white;
}

.back {
  transform: translateZ(-80px);
  background-color: gold;
}

.left {
  transform: translateX(-80px) rotateY(90deg);
  background-color: gold;
}

.right {
  transform: translateX(80px) rotateY(90deg);
  background-color: gold;
}

.top {
  transform: translateY(-80px) rotateX(90deg);
  background-color: gold;
}

.bottom {
  transform: translateY(80px) rotateX(90deg);
  background-color: gold;
}

.front {
  transform: translateZ(80px);
  background-color: gold;
}

.container {
  transform-style: preserve-3d;
}

.animate {
  position: fixed;
  top: 10px;
  color: wheat;
  display: flex;
}

.rotate {
  padding: 30px;
  background-color: lightgrey;
  margin: 5px;
  cursor: pointer;
  border-radius: 50%;
  color: black;
}

.rotateCube {
  animation-duration: 1s;
  animation-name: rotateLeft;
}

@keyframes rotateLeft {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(0,1,0,90deg);
  }
}

@keyframes rotateRight {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(0,-1,0,-90deg);
  }
}

@keyframes rotateUp {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(1,0,0,90deg);
  }
}

@keyframes rotateDown {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(0,-1,0,-90deg);
  }
}

back

left

r

t

b

Front

Thanks

A: In order to catch an arrow key event you need to use:
document.onkeydown = function(e) {
  e = e || window.event;
  console.log("keyCode is: " + e.keyCode);
};

I've added the code to the functions in order to rotate the cube (I've just added the class already defined in the css with js). This is the result:

let cube = document.getElementById("rotateCube");

function rotLeft() {
  resetCube()
  cube.className += " " + "show-left";
}

function rotRight() {
  resetCube()
  cube.className += " " + "show-right";
}

function rotUp() {
  resetCube()
  cube.className += " " + "show-top";
}

function rotDown() {
  resetCube()
  cube.className += " " + "show-bottom";
}

function resetCube() {
  cube.className = "cube";
}

document.onkeydown = function(e) {
  e = e || window.event;
  if (e.keyCode == "37") {
    rotLeft();
  } else if (e.keyCode == "39") {
    rotRight();
  } else if (e.keyCode == "38") {
    rotUp();
  } else if (e.keyCode == "40") {
    rotDown();
  }
};
.cube {
  width: 200px;
  height: 200px;
  position: relative;
  transform-style: preserve-3d;
  transform: translateZ(-100px);
  transition: transform 1s;
}

.cube.show-front  { transform: translateZ(-100px) rotateY(   0deg); }
.cube.show-right  { transform: translateZ(-100px) rotateY( 90deg); }
.cube.show-back   { transform: translateZ(-100px) rotateY(-180deg); }
.cube.show-left   { transform: translateZ(-100px) rotateY(  -90deg); }
.cube.show-top    { transform: translateZ(-100px) rotateX( -90deg); }
.cube.show-bottom { transform: translateZ(-100px) rotateX(  90deg); }

html, body {
  height: 100%;
}

.side,
.container {
  width: 160px;
  height: 160px;
}

.side {
  position: absolute;
  height: 160px;
  width: 160px;
  border: 2px solid white;
}

.back {
  transform: translateZ(-80px);
  background-color: gold;
}

.left {
  transform: translateX(-80px) rotateY(90deg);
  background-color: gold;
}

.right {
  transform: translateX(80px) rotateY(90deg);
  background-color: gold;
}

.top {
  transform: translateY(-80px) rotateX(90deg);
  background-color: gold;
}

.bottom {
  transform: translateY(80px) rotateX(90deg);
  background-color: gold;
}

.front {
  transform: translateZ(80px);
  background-color: gold;
}

.container {
  transform-style: preserve-3d;
}

.animate {
  position: fixed;
  top: 10px;
  color: wheat;
  display: flex;
}

.rotate {
  padding: 30px;
  background-color: lightgrey;
  margin: 5px;
  cursor: pointer;
  border-radius: 50%;
  color: black;
}

.rotateCube {
  animation-duration: 1s;
  animation-name: rotateLeft;
}

@keyframes rotateLeft {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(0,1,0,90deg);
  }
}

@keyframes rotateRight {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(0,-1,0,-90deg);
  }
}

@keyframes rotateUp {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(1,0,0,90deg);
  }
}

@keyframes rotateDown {
  0% {
    transform: rotate3d(0);
  }

  100% {
    transform: rotate3d(0,-1,0,-90deg);
  }
}

back

left

r

t

b

Front


text:
Q: How can I add a table with multi-row cells to a readme in VSTS? How can you add tables with multi-row cells to markdown in Microsoft VSTS?
I have previously used asciidoc for readme files on github as it is both richer and less ambiguous. The company now has projects on VSTS which does not support asciidoc so I need to use markdown instead.
However, it is unclear what flavour of markdown is actually supported
This page says that github flavoured markdown can be used
https://learn.microsoft.com/en-us/vsts/collaborate/markdown-guidance
I found another page saying they use commonmark via the markdown-it library.

Q: Does VS Code support GitHub Flavored Markdown?
A: No, VS Code targets the CommonMark Markdown specification using the
  markdown-it library. GitHub is moving toward the CommonMark
  specification which you can read about in this update.

I've been using a combination of asciidoctor and pandoc to convert files but nothing gets it quite right.
(Asciidoctor converts to docbook which pandoc can then parse)
asciidoctor -b docbook -v -o "$OUTPUT".xml "$INPUT" &&
pandoc -f docbook -t markdown_github -i "$OUTPUT".xml -o "$OUTPUT"

I have to re-add the title manually.
My current stumbling block is multi-row cells.
Github supports grid tables,
see Newline in markdown table?:
+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

But neither this nor embedded html seem to work in VSTS.
I would be happy to use html readmes instead if that was permitted.
Update 17-Nov-2017:
I found the link to markdown-it and added it above. I've raised an issue there for clarification (or enhancement). Its unclear which version VSTS actually uses under the hood.
I would like to ask the question of Microsoft themselves but their ask a question link goes straight to stack overflow.
The markdown-it library does support the usage suggested by @Waylan:
| Fruit         | Price                   | Advantages              |
| ------------- | ----------------------- | ----------------------- |
| Bananas       | first line
next line | first line
next line |
| Bananas       | first line
next line | first line
next line |

See https://github.com/markdown-it/markdown-it/issues/406.
The issue is most likely Microsoft disabling html.
A solution thus waits on a reply to @starian's suggestion: https://visualstudio.uservoice.com/forums/330519-visual-studio-team-services/suggestions/32312290-multi-line-in-the-cell-of-a-table-in-markdown-in-v

A: In short, each row must be on one line and should use
 to indicate a line break. Like this:
| Fruit         | Price                   | Advantages              |
| ------------- | ----------------------- | ----------------------- |
| Bananas       | first line
next line | first line
next line |
| Bananas       | first line
next line | first line
next line |

Below is an explanation of each tool with an analysis of that tool's documentation:
GitHub
CommonMark is a Markdown variant with a strict spec. GitHub-Flavored Markdown (GFM) is an extension of CommonMark (which adds features to CommonMark such as tables), with its own spec. Therefore, to say that an implementation supports GFM is to say that it supports CommonMark with extensions. Note that GitHub adopted the current spec on March 14, 2017, so any information older that that may not be relevant for the current implementation.
Whether VSTS actually uses a CommonMark/GFM implementation or a close approximation is unclear from the documentation. However, as the documentation clearly states that "GitHub-flavored extensions" are supported, that would indicate to me that the GFM Spec would be a good reference. Regardless, the GFM Spec is the controlling spec for any Markdown rendered on github.com.
The Tables section of the GFM Spec plainly states:

Block-level elements cannot be inserted in a table.

And gives this simple example:

| foo | bar |
| --- | --- |
| baz | bim |

While the spec does not specifically mention multiple line cells, there are no examples with any cells that contain multiple lines. It is my understanding that that is not supported by GFM. Therefore, the only way to include line breaks in GFM Table cells is with the
 tag, which is not a block-level element.
Pandoc
Pandoc supports multiple different styles of table syntax. If you are passing your Markdown to both Pandoc and GFM, then you need to use Pandoc's table style which most closely matches GFM's style. For example, GFM Tables do not include support for + at the corners. That syntax is specific to Pandoc's Grid Tables. Fortunately, Pandoc's documentation tells us which style most closely matches GFM.
Pandoc has support for various "Markdown Variants", one of which is gfm. The docs have this to stay about that variant:

We also support gfm (GitHub-Flavored Markdown) as a set of
  extensions on commonmark:
: pipe_tables, raw_html, fenced_code_blocks, auto_identifiers,
  ascii_identifiers, backtick_code_blocks, autolink_bare_uris,
  intraword_underscores, strikeout, hard_line_breaks, emoji,
  shortcut_reference_links, angle_brackets_escapable.

Note that the gfm variant of Pandoc uses Pipe Tables. It is also noteworthy that the markdown_github variant of Pandoc is deprecated since GitHub adopted Commonmark. But even the markdown_github variant uses Pipe Tables.
Pandocs' documentation for Pipe Tables states (emphasis added):

The cells of pipe tables cannot contain block elements like paragraphs and lists, and cannot span multiple lines.

And gives this example:

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
|   12  |  12  |    12   |    12  |
|  123  |  123 |   123   |   123  |
|    1  |    1 |     1   |     1  |

That is clearly the same as GFM tables and does not include any support for block level elements or multi-line cells.
VSTS
The VSTS Documentation for Tables closely matches GFM and Pandoc Pipe Tables with this example:

| Heading 1 | Heading 2 | Heading 3 |
|-----------|:---------:|----------:|
| Cell A1   | Cell A2   | Cell A3   |
| Cell B1   | Cell B2   | Cell B3   |

While the the VSTS Documentation makes no specific mention of block-level elements or multiple lines, is seems safe to assume that it is in fact the same style.
We can make that assumption because in all three instances (VSTS, GFM and Pandoc Pipe Tables), the syntax does not provide a divider between individual rows of the table (compare with Pandoc Grid Tables, which supports row dividers). While there is a divider between the header and data rows, with no divider between individual data rows, there is no way to indicate how many lines of text belong to each row. Therefore, each row can only be represented by one line of text.
Conclusion
Given the above, to be parsed properly by VSTS, GFM and Pandoc (gfm variant), your table should be formatted like this:
| Fruit         | Price                   | Advantages              |
| ------------- | ----------------------- | ----------------------- |
| Bananas       | first line
next line | first line
next line |
| Bananas       | first line
next line | first line
next line |

And when using Pandoc, be sure to use the gfm format (pandoc -f gfm ...).

A: It is not supported in markdown of VSTS, I submit a user voice here: multi-line in the cell of a table in markdown in VSTS, you can vote and follow it.


text:
Q: capture and retrieve image in iphone? I am new to iOS 5.0,
I want to know that,
Is there any method to capture the image from camera and retrieve it in application in iOS ?

A: Take a look at the Camera Programming Guide.


text:
Q: Mongo Compass is not able to connect with hostnaame but IP Address : MongoDB not running on the provided host and port Using mongo compass community edition, I am able to connect to MongoDB with server's IP address xx.xx.xx.xx but when I try to connect to it with hostname, it throws the error :

MongoDB not running on the provided host and port


text:
Q: How does C++ keep the const value? #include <iostream>
using namespace std;
int main() {
    const int a = 10;
    auto *b = const_cast<int *>(&a);
    *b = 20;
    cout << a << " " << *b;
    cout << endl << &a << " " << b;
}

The output looks like:
10 20
0x7ffeeb1d396c 0x7ffeeb1d396c

The a and *b are at the same address, why do they have different value?

A: Most probably this is caused by optimization.
As molbdnilo already said in his comment: "Compilers trust you blindly. If you lie to them, strange things can happen."
So when optimization is enabled, the compiler finds the declaration
const int a = 10;

and thinks "ah, this will never change, so we don't need a "real" variable and can replace all appearances of a in the code simply with 10". This behavior is called constant folding.
Now in the next line you "cheat" the compiler:
auto *b = const_cast<int *>(&a);
*b = 20;

and change a, although you have promised not to do so.
The result is confusion.
Like a lot of people have already mentioned and Christian Hackl has thoroughly analyzed in his excellent in-depth answer, it's undefined behavior. The compiler is generally allowed to apply constant folding on constants, which are explicitly declared const.
Your question is a very good example (I don't know how anyone can vote it down!) why const_cast is very dangerous (and even more when combined with raw pointers), should be only used if absolutely necessary, and should be at least thoroughly commented why it was used if it was unavoidable. Comments are important in that case because it's not only the compiler you are "cheating":
Also your co-workers will rely on the information const and rely on the information that it won't change. If it DOES change though, and you didn't inform them, and did not comment, and did not exactly know what you were doing, you'll have a bad day at work :)
Try it out: Perhaps your program will even behave different in debug build (not optimized) and release build (optimized), and those bugs are usually pretty annoying to fix.

A: I think it helps to view const like this:
If you declare something as const it is actually not the compiler that ensures that you dont change it, but rather the opposite: you make a promise to the compiler that you wont change it.
The  language helps you a bit to keep your promise, eg you cannot do:
const int a = 5;
a = 6;            // error

but as you discovered, you indeed can attempt to modify something that you declared const. However, then you broke your promise and as always in c++, once you break the rules you are on your own (aka undefined behaviour).

A:
The a and *b are at the same address, why do they have different
  value?

They don't, not according to C++. Neither do they, according to C++.
How can that be? The answer is that the C++ language does not define the behaviour of your program because you modify a const object. That's not allowed, and there are no rules for what will happen in such a case.
You are only allowed to use const_cast in order to modify something which wasn't const in the first place:
int a = 123;
int const* ptr1 = &a;
// *ptr1 = 456; // compilation error
int* ptr2 = const_cast<int*>(ptr1);
*ptr2 = 456; // OK

So you've ended up with a program whose behaviour is not defined by C++. The behaviour is instead defined by compiler writers, compiler settings and pure chance.
That's also what's wrong with your question. It's impossible to give you a correct answer without knowing exactly how you compiled this and on which system it runs, and perhaps even then there are random factors involved.
You can inspect your binary to find out what the compiler thought it was doing; there are even online tools like https://gcc.godbolt.org/ for that. But try to use printf instead of std::cout for such an analysis; it will produce easier-to-read assembly code. You may also use easier-to-spot numbers, like 123 and 456.
For example, assuming that you even use GCC, compare these two programs; the only difference is the const modifier for a:
#include <stdio.h>
int main() {
    int const a = 123;
    auto *b = const_cast<int *>(&a);
    *b = 456;
    printf("%d", a);
    printf("%d", *b);
}

#include <stdio.h>
int main() {
    int a = 123;
    auto *b = const_cast<int *>(&a);
    *b = 456;
    printf("%d", a);
    printf("%d", *b);
}

Look at what the printf("%d", a); call becomes. In the const version, it becomes:
mov esi, 123
mov edi, OFFSET FLAT:.LC0
mov eax, 0
call printf

In the non-const version:
mov eax, DWORD PTR [rbp-12]
mov esi, eax
mov edi, OFFSET FLAT:.LC0
mov eax, 0
call printf

Without going too much into the details of assembly code, one can see that the compiler optimised the const variable such that the value 123 is pushed directly to printf. It doesn't really treat a as a variable for the printf call, but it does do so for the pointer initialisation.
Such chaos is the nature of undefined behaviour. The moral of the story is that you should always avoid undefined behaviour, and thinking twice before casting is an important part of allowing the compiler to help you in that endeavor.

A: Compiling your code once with const and once without const using gcc, shows that there either no space is allocated for a, or it's content is being ignored in const version. (even with 0 optimization) The only difference in their assembly result is the line which you print the a. Compiler simply prints 10 instead of refering to memory and fetching contents of a: (left side is const int a and right side is int a version)
movl    $10, %esi     |     movl    -36(%rbp), %eax
                      >     movl    %eax, %esi

As you can see there is an extra memory access for non-const version, which we know is expensive in terms of time. So the compiler decided to trust your code, and concluded that a const is never to be changed, and replaced its value wherever the variable is referenced.
Compiler options: --std=c++11 -O0 -S