Length of a sequence of numbers using seq in shell

Question: I am new to shell scripting and I am trying a simple task of getting the length of a sequence of numbers generated using seq.
With the help of a related post here: How to find the array length in unix shell? I was able to do this -
a=(1 2 3 4 5)
echo ${#a[@]}  #length of a
5              #length of a = 5 (This is fine !!)

However when I try to do a similar thing using seq ..
b=$(seq 1 1 10)
echo $b
1 2 3 4 5 6 7 8 9 10
echo ${#b[@]}
1              #the length of b is 1, while I expect it to be 10

Why does this happen ? Are the variable types a and b different? is b not an array ?
I am sure I am missing something very trivial here, help is greatly appreciated.
Thanks
Ashwin
Answer: You need to store the output in an array to find the length of the array:
$ b=($(seq 1 1 10))
$ echo ${#b[@]}
10

Saying b=$(seq 1 1 10) doesn't produce an array.
Answer: Try
echo ${b[0]}
It will be 1 2 3 4 5 6 7 8 9 10 because all your values are stored in first element of array a as a string.
b=($(seq 1 1 10))

will do what you want.


How to add product categories in my own div?

Question: I've created a div called nav_container and I'd like the Magento product categories to be placed in that div instead of in the default header.
What is the simplest way to do this? I've researched this for a long time with no solution. Thanks for any advice. I'm using Magento 1.7.
Comment: You might want to give your question a more relevant title. Now it only tells us it's about something Magento related, which is already a tag.
Answer: There are several ways to achieve this:

Copy app/design/frontend/base/default/page/html/topmenu.phtml to app/design/frontend/your_package/your_theme and simply add in your wrapping div.
Edit app/design/frontend/your_package/your_theme/page/html/header and find the line: <?php echo $this->getChildHtml('topMenu') ?> and simply surround it with you div
You could also use layout xml, specifically a page/html_wrapper block - but for this simple example option 1 or 2 would most likely be the best option

EDIT
Please see below the correct solution after realising your confusion regarding blocks
Ok, so first of all, blocks have a very specific meaning in Magento, entirely different to that of an html tag.  You can find a definition of blocks here: http://www.magentocommerce.com/design_guide/articles/magento-design-terminologies4#term-blocks
Now, to move the top nav in 1.7 CE:
As ever with layouts in Magento, you have two main options: Copy over base layout files into your current theme and edit, or use a local.xml file in your theme for all base layout overrides.
There are pros and cons to each - though I would advocate you use local.xml unless there is specific reason not to.  But it is entirely up to you which method you choose :)
1. Using local.xml
app/design/frontend/your_package/your_theme/layout/local.xml

<layout version="0.1.0">

    <reference name="header">
        <action method="unsetChild"><alias>topMenu</alias></action>
    </reference>

    <reference name="nav_container">
        <action method="insert"><alias>top.menu</alias></action>
    </reference>

</layout>

2. Copying over base files
First, copy app/design/frontend/base/default/layout/page.xml to app/design/frontend/your_package/your_theme/layout/page.xml
Find the header block, which if untouched will be exactly as follows:
<block type="page/html_header" name="header" as="header">
    <block type="page/template_links" name="top.links" as="topLinks"/>
    <block type="page/switch" name="store_language" as="store_language" template="page/switch/languages.phtml"/>
    <block type="core/text_list" name="top.menu" as="topMenu" translate="label">
        Navigation Bar
        <block type="page/html_topmenu" name="catalog.topnav" template="page/html/topmenu.phtml"/>
    </block>
    <block type="page/html_wrapper" name="top.container" as="topContainer" translate="label">
        Page Header
        <action method="setElementClass"><value>top-container</value></action>
    </block>
</block>

and change to:
<block type="page/html_header" name="header" as="header">
    <block type="page/template_links" name="top.links" as="topLinks"/>
    <block type="page/switch" name="store_language" as="store_language" template="page/switch/languages.phtml"/>
    <block type="page/html_wrapper" name="top.container" as="topContainer" translate="label">
        Page Header
        <action method="setElementClass"><value>top-container</value></action>
    </block>
</block>

At this point, you have simply removed the top.menu block from the layout.
Next, you need to add the block back into the layout under the correct node: nav_container.
So, wherever you are currently declaring your nav_container block add as a child node the xml you just removed i.e.:
<block type="core/text_list" name="top.menu" as="topMenu" translate="label">
    Navigation Bar
    <block type="page/html_topmenu" name="catalog.topnav" template="page/html/topmenu.phtml"/>
</block>

Finally clear your cache and reload the page.
Comment: The first two don't work: what happens is it simply encases the nav menu in a div with the same id, but still nested inside the header div. Could you please elaborate on option 3?
Comment: So you want to move the navigation out of the header completely and into another, separate block altogether?
Comment: Yes, I made a custom template, what you refer to as 'block' I just refer to as a div. So i'd like it in a div that I've named 'left_container'.
Comment: Thanks for the detailed update! I'd like to use the local.xml method, one confusion... in the second part where I add it back in, which part of that specifies where it is getting added to?
Comment: name="nav_container" specifies the block new containing block and top.menu does the inserting


Create iso/image/installation from Windows XP-installation

Question: I'm using VMware and want to create a virtual machine with Windows XP. For this I want to use the Windows XP-installation of another computer, I don't have the cd, so I want to create a iso/image (or whatever) of this Windows-installation. How can I do this?
Comment: Don't forget, Windows XP is no longer supported, it's past time to move on.
Comment: Sure. But I only want to test some issues for a application only working with Windows XP.
Answer: You only need to use Vmware Converter (http://www.vmware.com/products/converter/) to create an image so you can use it on other Vmware Platforms (vSphere, Workstation,...).
There are a lot of guides on the net about how to use the software. This one may help you:
http://www.petri.co.il/virtual_convert_physical_machines_to_virtual_machines_with_vmware_converter.htm
Regards,
Comment: Thanks a lot. I try to download VMware Converter but I'm asked to create an account and fill in name, organization, phone number and so on. It's only for private use. Suggestions?
Comment: Just register with a private account. You can use that account later to test new Vmware products.
Comment: This one? https://my.vmware.com/web/vmware/evalcenter?p=converter#tab_register
Comment: You should find the download link under License & download. You need to have logged in into your account to get the download link.


Is this an Offside according to FIFA rules?

Question: I was looking at fifa offside rules which are here. In the slide/page 26 it explains about a NO offside scenario like this

Do I need to consider that direction of the pass which in this case is backwards (B2 passing backwards to C)
To be more clear is this allowed?

As you can see the passing direction is forward. If this is allowed (not offside) then I have another follow-up question
Comment: As clearly said, yes this is allowed. C appears to be leveled or slightly behind the ball, and thus can never be in an offside position.
Comment: Dupe or not? http://sports.stackexchange.com/questions/3/how-is-offside-determined-in-soccer
Comment: @Don_Biglia: I don't think it is a duplicate. The other question is asking a very general question, and I think it is fine (maybe even better) to ask about specific aspects of the offside law too.
Comment: I was in doubt. But in the end even specific cases are going to refer to the general rules. I'm also starting to doubt if this is even a good question at all. He's asking if this is so according to Fifa rules while his images are in the fifa rules. The document he refers to is kind of the answer to his question and at the same time te source of his question. Feels like moving in circles or something like that :D
Answer: The problem with your second scenary is not the pass per se.. is the position of player C. if player C is behind the ball, there is no problem if the pass go foward or backward, since the ball in that case is the line that mark offside position.
Answer: From page 36 of the 2015/16 FIFA Laws of the Game (emphasis mine):

A player is in an offside position if:

he is nearer to his opponents' goal line than both the ball and the second-last opponent

In the first example provided in the question, player C is nearer to his opponents' goal line than the second-last opponent, but not the ball when the ball is last touched by a teammate. He is therefore not in an offside position and will not be penalised when he touches the ball.
In the second example provided in the question, in which player C is nearer to his opponents' goal than both the ball and the second-last opponent when the ball is last touched by a teammate (in the image provided by OP, player C is probably still just behind the ball even though I believe this is not what the original question intended). He is therefore in an offside position and will be penalised for interfering with play when he touches the ball.
Contrary to other answers (which since have been deleted), neither the direction that the ball is played nor where the player is standing when he touches the ball have any relevance on whether an offside offence has occurred.
Comment: Are you talking about the OP's examples?
Comment: @Don_Biglia - yes. I'll make an edit to ensure this is clearer.
Comment: Well then, C is not in an offside position, he is leveled with the ball. It's even said so: "No offside offence" is cleary in the example.
Comment: The second picture is just the first one edited by OP. The fact it says "no offside offence" bears no relevance. You may be right, the goalside edge of the ball is probably just ahead of the front edge of C's toe, but I don't believe this is what OP was trying to show. I will make this edit however.
Comment: As an aside, it's practically impossible for anyone to be level, given that the assistant referee should be comparing two infinitely thin lines across the field. The reason this is written into the laws is so that if they're so close that the AR can't tell, he rules the player onside.


GCE Protocol Forwarding, use IP for outgoing requests

Question: I have a GCE instance that has multiple protocol-forwarding rules to it.
All the forwards work prefectly, but when the instance creates a request from itself to the internet, how do I specify which ip address to use when doing, for example, a wget from the instance?
Answer: You can add IP addresses of forwarding rules to the network interface and then configure using iptables setup Source Network Address Translation (SNAT) to change the source IP address of your outgoing traffic.
Example:

IP address of forwarding rule: A.B.C.D
Add this IP to your network interface (sub-interface):
Open interface file
$ sudo nano /etc/network/interfaces

Add these lines and save it
auto eth0:0
allow-hotplug eth0:0
iface eth0:0 inet static
address A.B.C.D
netmask 255.255.255.255

Restart the networking service
$ sudo service networking restart

Create an iptables SNAT rule:
$ sudo /sbin/iptables -t nat -I POSTROUTING -d DES_IPs -j SNAT --to A.B.C.D


Create node from custom form using ajax

Question: How do I add a node from a custom form using ajax? I want it to be submitted in the backend. How will it be if there are custom fields?
Answer: in drupal you can create node using node_save function as below
<code>$node = new StdClass();//creating a bare node
$node->type = 'answer';//giving it type
$node->status = 1;//give it a published staus
$node->title = "Step up to the FLava";//gives title
$node->body = "Body Body body"; //gives body

node_save($node);
//save it and give it the rest of the attributes`
</code>
Comment: For custom fields, you just add them in the node before saving it :
    $node->field_my_custom_field['und'][0]['value'] = 'my value';

Create node from custom form using ajax


Yii2 gridview + filtering without activerecord

Question: I have a model (but I dont't have a table behind because I want to select information about the database itself):
namespace app\models;

use Yii;
use yii\base\Model;

class OracleTables extends Model {

    public $table_name;

    public static function getDb() {return Yii::$app->get('db_o');}
}

a controller:
namespace app\controllers;

use app\models\OracleTablesSearch;
use yii\web\Controller;
use yii\helpers\Url;
use dmstr\bootstrap\Tabs;

class OracleTablesController extends Controller {

    public function actionIndex() {
        $searchModel = new OracleTablesSearch;
        $dataProvider = $searchModel->search($_GET);

        Tabs::clearLocalStorage();

        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->render('index', [
                    'dataProvider' => $dataProvider,
                    'searchModel' => $searchModel,
        ]);
    }

}

a search model:
namespace app\models;

use Yii;
use yii\base\Model;
use app\models\OracleTables;
use yii\data\SqlDataProvider;

class OracleTablesSearch extends OracleTables {

    public function rules() {return [[['table_name'], 'safe'],];}

    public function search($params) {
        $totalCount = Yii::$app->db_o
                ->createCommand('SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE NUM_ROWS > 0')
                ->queryScalar();

        $dataProvider = new SqlDataProvider([
            'db' => Yii::$app->db_o,
            'sql' => 'SELECT TABLE_NAME FROM USER_TABLES WHERE NUM_ROWS > 0 ORDER BY TABLE_NAME ASC',
            'totalCount' => $totalCount,
        ]);

        $this->load($params);

        return $dataProvider;
    }

}

a view file:
GridView::widget([
    'dataProvider' => $dataProvider,
    'pager' => ['class' => yii\widgets\LinkPager::className(), 'firstPageLabel' => Yii::t('app', 'First'), 'lastPageLabel' => Yii::t('app', 'Last'),],
    'filterModel' => $searchModel,
    'tableOptions' => ['class' => 'table table-striped table-bordered table-hover'],
    'headerRowOptions' => ['class' => 'x'],
    'columns' => [
        [
            'attribute' => 'TABLE_NAME',
            'contentOptions' => ['nowrap' => 'nowrap'],
            'filter' => AutoComplete::widget([
                'model' => $searchModel,
                'attribute' => 'table_name',
                'clientOptions' => [
                    'source' => [],
                    'autoFill' => true,
                    //'minLength' => 2
                ],
                'options' => ['class' => 'form-control']
            ]),
        ],
    ],
]);

it works, but without filtering, and I want filtering also. I know how to populate filter source, that's not the problem. The problem is, I can't add $sql->andFilterWhere(['like', 'table_name', $this->table_name]); to search model, because then I would need to transfer sql command outside SqlDataProvider, but then it doesn't work anymore. Look at this please (search model):
public function search($params) {
    $totalCount = Yii::$app->db_o
            ->createCommand('SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE NUM_ROWS > 0')
            ->queryScalar();
    $sql = Yii::$app->db_o
            ->createCommand('SELECT TABLE_NAME FROM USER_TABLES WHERE NUM_ROWS > 0 ORDER BY TABLE_NAME ASC')
            ->queryColumn();

    $dataProvider = new SqlDataProvider([
        'db' => Yii::$app->db_o,
        'sql' => $sql,
        'totalCount' => $totalCount,
    ]);

    $this->load($params);

    $sql->andFilterWhere(['like', 'table_name', $this->table_name]);

    return $dataProvider;
}

if I'm doing like so, I get the following error message:
PHP Warning
preg_match() expects parameter 2 to be string, array given
in ...\vendor\yiisoft\yii2\data\SqlDataProvider.php

131        }
   $sql = $this->sql;
   $orders = [];
   $limit = $offset = null;

   if ($sort !== false) {
       $orders = $sort->getOrders();
       $pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
       if (preg_match($pattern, $sql, $matches)) {
           array_unshift($orders, new Expression($matches[1]));
           $sql = preg_replace($pattern, '', $sql);
       }
   }

   if ($pagination !== false) {
       $pagination->totalCount = $this->getTotalCount();
       $limit = $pagination->getLimit();
       $offset = $pagination->getOffset();

I don't find what parameter is he talking about. Or what kind of dataProvider else should I use instead? Can you please point me to the right direction? Thanks a lot!
Answer: I've solved it this way:
public $table_name;

public function search($params) {
    isset($_GET['wts']['table_name']) ? $table_name = $_GET['wts']['table_name'] : $table_name = "";

    $totalCount = Yii::$app->db_o
            ->createCommand('SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE NUM_ROWS > 0 AND LOWER(TABLE_NAME) LIKE LOWER(:table_name)')
            ->bindValue(':table_name', '%' . $table_name . '%')
            ->queryScalar();

    $dataProvider = new SqlDataProvider([
        'db' => Yii::$app->db_o,
        'sql' => 'SELECT TABLE_NAME, NUM_ROWS FROM USER_TABLES WHERE NUM_ROWS > 0 AND LOWER(TABLE_NAME) LIKE LOWER(:table_name) ORDER BY TABLE_NAME ASC',
        'params' => [':table_name' => '%' . $table_name . '%'],
        'totalCount' => $totalCount,
        'pagination' => [
            'pageSize' => 15,
        ],
    ]);


Non-Abelian group of order 64 with an order-4 quotient group the Klein four-group

Question: Are there some examples of the non-Abelian group of order 64 say $G$ with a Klein four-group  ($\mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/2\mathbb{Z} $) quotient group? What are these examples? (Incomplete and partial examples are OKAY.) What is the corresponding normal subgroup $N$ then? For $Q/N=\mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/2\mathbb{Z} $?
Comment: How about $G = N \times \mathbb Z/2\mathbb Z \times \mathbb Z/2\mathbb Z$, for some nonabelian group $N$ of order $16$?
Comment: Every non-cyclic group of order a power of $2$ has the Klein four-group as a quotient group.
Comment: Proof of Derek's claim (since it gave me a pause): if the group is abelian, then the classification of finite abelian groups gets you there. Otherwise, take the quotient $G/Z(G)$ by the center, which we know is nontrivial. If the resulting group is cyclic, then it's a standard theorem that $G$ is abelian, and we handled that case. Otherwise, $G/Z(G)$ is a strictly smaller non-cyclic group of order a power of $2$. Apply induction.
Comment: That is one convenient example. What else?
Answer: Suppose you have a direct product of groups, say $G = A \times B$.  You can check that the standard projection maps $\pi_1:G \rightarrow A$ and $\pi_2:G \rightarrow B$ defined by $\pi_1(a, b) = a$ and $\pi_2(a, b) = b$ are group homomorphisms.  It's also easy to check that $\ker(\pi_1) \cong B$ and $\ker(\pi_2) \cong A$.
Applying this fact to the problem at hand, we just need to find a nonabelian group of order that divides $64/| \mathbb{Z}_2 \times \mathbb{Z}_2| = 16$.  The quaternion group of order $8$ fits the bill.  So by letting $G$ be an appropriate direct product, we can arrive at an example you're looking for.
Comment: Is your example here fitted into my construction here: http://math.stackexchange.com/questions/1947201?
Answer: One way of generating examples of non-abelian groups of order a power of two is to consider upper triangular matrices over the field of two elements $F=\Bbb{Z}/2\Bbb{Z}$. If we let $G$ be the set of such 4x4 matrices
$$
G=\left\{\left(\begin{array}{cccc}1&a&b&c\\0&1&d&e\\0&0&1&f\\0&0&0&1\end{array}\right)\bigg\vert\,a,b,c,d,e,f\in K\right\},
$$
then we clearly get a group (a subgroup of $GL_4(F)$. There are six variables ranging over $F$, so there are $64$ elements in $G$. The subsets where certain entries are set to zero form normal subgroups (IIRC if we set some position to zero, we also need to do the same between the entries of the diagonal and that position). So for example if we define $H$ to be the set of elements of $G$ such that $a=d=0$, then $H$ will be a normal subgroup of $G$. Furthermore, it is
easy to see that $G/H$ is the Klein 4-group because the multiplication of cosets of $H$ amounts to addition of pairs $(a,d)$ in $F^2\simeq V_4$.
Comment: You could also do the analogous thing with 3x3-matrices over the field of four elements.
Comment: Does your example also include the specific construction here: http://math.stackexchange.com/questions/1947201? Thank you.


How to search a string in a sheetname?

Question: I am trying to search a particular string in all sheet names of a workbook using For each loop as follows:
 For Each Sheet In ActiveWorkbook.Sheets
  Name = ActiveSheet.Name
  Next Sheet

But i am not able to get all the sheet names using above code as it gets stuck up only one sheet name.
After getting the sheet name i want to search a particular string in the sheet name So it would be great if any one can help me in searching a string in all sheets.
Comment: how do you want to list search results ?
Answer: For Each sheet In ActiveWorkbook.Sheets
    If sheet.Name Like "*" & strSearch & "*" Then
        Debug.Print "Found! " & sheet.Name
    End If
Next

You iterate over all sheets, but you always use ActiveSheet.Name in your loop.
To search for a pattern, you can use Like with the * wildcard.
Answer: You can use the InStr function as well... or maybe I didn't get your question correctly.
Sub CheckSheets()
    Dim oSheet As Excel.Worksheet
            For Each oSheet In ActiveWorkbook.Sheets
        If InStr(UCase(oSheet.Name), UCase("Sheet")) Then
            Debug.Print oSheet.Name
        End If
    Next oSheet
End Sub

How to search a string in a sheetname?


Let $\sigma,\tau \in S_n$. Prove that $\sigma \tau$ and $\tau \sigma $ have the same cycle type.

Question: Let $\sigma,\tau \in S_n$. Prove that $\sigma \tau$ and $\tau \sigma $ have the same cycle type.
I was thinking that you could rewrite $\sigma=g_1\cdots g_k$ with $g_i$ disjoint cycles and $\tau=h_1\cdots h_l$ with $h_i$ disjoint cycles. But I don't know what to do next, as $g_i$ and $h_j$ doesn't have to be disjoint.
Edit: Could I prove it like this ?
We can write $σ$ in disjoint cycles: $σ=σ_1...σ_r$ with lenghts $l_1,...l_r$. So you get: $σ_1=(a_1...a_{l_1}), σ_2=(b_1...b_{l_2}), σ_3=...$.
Which gives:
\begin{align*}
τστ^{-1}&=τσ_1...σ_rτ^{-1}\\
&=τσ_1(τ^{-1}τ)σ_2(τ^{-1}τ)...(τ^{-1}τ)σ_rτ^{-1}\\
&=τ(a_1...a_{l_1})τ^{-1}τ(b_1...b_{l_2})τ^{-1}τ...τσ_rτ^{-1}\\
&=(τ(a_1)...τ(a_{l_1}))(τ(b_1)...τ(b_{l_2}))...τσ_rτ^{-1}\\
\end{align*}
Therefore $σ$ and $τστ^{-1}$ have the same cycle type. So $τσ$ and $στ$ have the same cycle type.
Answer: Hint: they are conjugate elements of the group.
Comment: My book introduces conjugates in the next chapter.
Answer: First consider the case that $\tau$ is a single cycle, say $\tau = (i_1,i_2,\ldots,i_k)$. You should be able to compute $\sigma\tau$ and $\tau\sigma$ explicitly in this case. Then figure out how to generalize when $\tau$ is a product of disjoint cycles: for this try inserting copies of $\sigma^{-1}\sigma$ in various places of the product $\sigma\tau\sigma^{-1}$ when $\tau$ is written as a product of disjoint cycles.
Comment: Let $σ=σ_1...σ_r$ with $σ_1=(a_1...a_{l_1}), σ_2=(b_1...b_{l_2}), σ_3=...$.
Then you get:
\begin{align*}
τστ^{-1}&=τσ_1...σ_rτ^{-1}\\
&=τσ_1(τ^{-1}τ)σ_2(τ^{-1}τ)...(τ^{-1}τ)σ_rτ^{-1}\\
&=τ(a_1...a_{l_1})τ^{-1}τ(b_1...b_{l_2})τ^{-1}τ...τσ_rτ^{-1}\\
&=(τ(a_1)...τ(a_{l_1}))(τ(b_1)...τ(b_{l_2}))...τσ_rτ^{-1}\\
\end{align*}
Comment: This one did it ! Thanks
Comment: I hope that this is what you meant.
Comment: Since this answer worked for you, @90intuition, please accept it by clicking the checkmark :)
Answer: First, it suffices to prove that $\tau\sigma\tau^{-1}$ and $\sigma$ have the same cycle type.
Suppse one of the cycles in $\sigma$ is $(a_1,a_2,\dots,a_n)$. Then, try to prove that there is a corresponding cycle in $\tau\sigma\tau^{-1}$ that is $\big(\tau(a_1),\tau(a_2),\dots,\tau(a_n) \big)$.
If $\sigma$ sends $a_1$ to $a_2$, what does $\tau\sigma\tau^{-1}$ send $\tau(a_1)$ to?
Comment: Specifically, it suffices to show $\alpha\beta\alpha^{-1}$ and $\beta$ have the same cycle type, because then one can set $\beta=\tau\sigma$ and $\alpha=\sigma^{-1}$ to conclude $\sigma\tau$ and $\tau\sigma$ have the same cycle type. Which is also the hint of Robert's answer. (Sorry for the anachronistic comment.)
Answer: In the light of @Robert's answer, if $x$ and $y$ are two permutations of a set $\Omega$, and $x=(\xi_1,\xi_2,...,\xi_k)$ then $$y^{-1}xy=(\xi_1^y,\xi_2^y,...,\xi_k^y)$$ In fact, in the product $xy$ we expect to have the result of first applying the mapping $x$ and then the mapping $y$. This is what @Robert's trying to tell you.
Comment: Nice! $\quad \ddot \smile \quad +1 \quad$
Answer: Suppose that $\sigma \tau=(a_1a_2\cdots a_k)(b_1b_2\cdots b_{\lambda})\cdots$.
Then $\tau\sigma(\tau(a_i))=\tau(\sigma\tau(a_i))=\tau(a_{i+1})\ldots$
Show that $\tau\sigma=\left(\tau(a_1)\tau(a_2)\cdots\tau(a_k)\right)\left(\tau(b_1)\tau(b_2)\cdots\tau(b_{\lambda})\right)\cdots$.


Ideal Way to Create a Python "Library"

Question: I want to create a "library" of Python modules which I will be able to access from several separate project folders.
For example, I want the Python scripts in /proj1/ and /proj2/ to have access to /lib/.
/lib/help.py
/lib/more_help.py

/proj1/script.py
/proj1/script2.py

/proj2/this_script.py
/proj2/another_script.py

I don't want a single directory with all the Python scripts, as this seems rather disorganized. I also definitely don't want to copy the same /lib/ script into each of the different projects.
What is the ideal way to handle this in Python? Is it appending to Python's path? Or is this more of a hack? This seems to have the disadvantage of making the files less portable. Or is it this question/answer about using relative paths? Or something else?
I should add that I'm interested in Python 2.x rather than 3.x, if it matters.
Answer: Turn lib/ into a package, then put it in one of the directories in sys.path (or add a new entry). You can then import e.g. lib.help into your projects.
Answer: Follow the standard road that everyone takes: make your code a proper Python package with a proper setup.py. The benefits are: easy_install'able, easy distributable, easy generation of command line script (through console_scripts entry point) etc....
Answer: I think the best tool you can use to keep under control the environment of your project is virtualenv. You create a new virtual environment and install there your packages, then you run your project using the python executable that virtualenv provides you.
Probably you should use distutils in your library, in this way installing it with virtualenv is really easy, because virtualenv installs setuptools or distribute in the virtual environment, thus allowing you to install in the virtual environment packages from pypi or from your local machine.
There is also the possibility to create a custom bootstrap script that automatically installs some libraries after the virtual environment creation.
Comment: I hadn't heard of this tool, but will definitely look it up. Thanks for the recommendation!

Ideal Way to Create a Python "Library"


How to call local variable outside of function using OOP in Python?

Question: I know there's multiple ways of calling a variable outside of a function, but I'm trying to do this using OOP. Here's my code:
import re
import os.path as p
import sys
from contextlib import contextmanager
import os

def main(file_in):

    v_pat = re.compile(r"^v\s[\s\S]*")
    vertices = ['None']

    with open(file_in, 'r') as f_in:
        for line in f_in:
            v = v_pat.match(line)

            if v:
                vertices.append(v.group())

if __name__ == '__main__':
    file_in = sys.argv[1]
    main(file_in)

I'd like to call the vertices array outside of the function using OOP. What would my code look like if I were to implement that?
Comment: Please don't make more work for others by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under a [CC BY-SA license](//creativecommons.org/licenses/by-sa/4.0), for SE to distribute the content (i.e. regardless of your future choices). By SE policy, the non-vandalized version is distributed. Thus, any vandalism will be reverted. Please see: [How does deleting work? …](//meta.stackexchange.com/q/5221). If permitted to delete, there's a "delete" button below the post, on the left, but it's only in browsers, not the mobile app.
Comment: So in that case, it is probably best to return it. If you don't want to do that, you can make it a global variable, or a class variable of a global class. But returning it is probably best.
Comment: What do you mean by "call"ing it? You can't call a list
Comment: Do you want to return it?
Comment: I didn't understand what you are trying to do. What is not "OOP" about the multiple ways you know?
Answer: I am not sure why you don't want to return the list, but if you just want to make that function into a class and have that list as an attribute you can try this
import re
import os.path as p
import sys
from contextlib import contextmanager
import os

class MyClass:
    def __init__(self):
        self.v_pat = re.compile(r"^v\s[\s\S]*")
        self.vertices = ['None']
    def doStuff(self, file_in):
        with open(file_in, 'r') as f_in:
            for line in f_in:
                v = self.v_pat.match(line)
                if v:
                    self.vertices.append(v.group())

if __name__ == '__main__':
    file_in = sys.argv[1]
    myClass = MyClass()
    myClass.doStuff(file_in)
    print(myClass.vertices)

Comment: i would make a function for each array
or return all of them and use the ones i need


How to Split Form entries and replace text within a cell

Question: I have a form that serves as an application to receive volunteer teams for my NGO. What I want to do is create a script that sends an email to the registrar upon someone completing the form. That's the easy part which I know how to do.
I want to include in that "email notification" a few key answers from some questions for the registrar to see. This I also know how to accomplish.
here is my current code that works:
function Team_ApplicationMailer(e) {
   var recipient = "firstname.lastname@example.com";
   var timestamp = e.values[0];
   var name = e.values[3];
   var country = e.values[1]
   var subject = e.values[1]+' wants to Volunteer!' ;
   var startdate = e.values[12];
   var enddate = e.values[13]
   var hyperlink = "mylink.com"
   htmlBody = ''+name+' from: '+country+'just completed the Teams Application Form for these dates: '+startdate+' to '+enddate+'

Form completed on: '+timestamp+'

View the Form: Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}

Here's the tricky part I want to add: I want to also add data found in e.values[19] and e.values[20], but these values are from either a multiple choice (e.values[19]) or checkbox (e.values[20]) and I need the values both simplified—i.e. some text deleted—and possibly split when emailed.
The two questions are basically identical. e.values[19] is "What do you want to do: 1st Priority" with some multiple-choice options. and e.values[20] is "What else do you want to do" with some checkbox options. Both questions have the same 7 choices and each choice has a long description (hence the need to shorten)
Basically I want e.values[19] which value looks like this:
optionX: (Long Description)
to look like this in the email:
What do you want to do: optionX.
I don't want the long description of the option in the "()" to be included.
For e.values[20] I want the values to look like this in the email:
What else do you want to do: optionA, optionB, optionC
INSTEAD of This:
optionA: (Long Description),optionB: (Long Description),optionC: (Long Description)
I've looked into the .replace and .split functions but don't know how to make them work together, especially for the checkbox option.
Thanks for the help!
Answer: I wrote a function for this. It just removes anything inside parentheses (). This seems to be what you're looking for.
var s = e.values[19];
s = s.replace(/\([^)]*\)/g,"");

If you have parentheses inside parentheses, let me know, and I will have to make a quick edit.
So what's happening here.

It's looking for a (.
It's looking for as many characters as it can while matching a ) at the end. This is without having a ) inside.

If you had allowed a ) inside, it would match optionA:(...), optionB: (...), optionC: (...). We want to avoid this, so we do not allow ) inside. That's what [^)] means.

The g flag means to match "globally", or everywhere in the string.
Comment: regular expressions are always tricky to start with. if you have used parentheses for your question only and they aren't present, then you can adapt Phil's pattern to look instead for a pair of `optionX:` and `,` or end of line
Comment: I completely understand where you're coming from. So I threw together an example that works with `String.slice()`. http://jsfiddle.net/r2Zr4/
Comment: Exactly! `s` is a string. You can insert it anywhere you'd like in the HTML body.


Centre of mass moves with constant velocity

Question: The centre of mass of the Newton $n$-body problem is given by $$S=\frac{1}{M} \sum m_ix_i$$ with $M=\sum m_i$.
Show that it moves with contant speed and hence has no acceleration.
I don't understand as if I differentiate, I'll surely just get $$S'=\frac{1}{M} \sum m_ix'_i$$ which is not constant...is it?
Comment: Conservation of linear momentum?
Comment: Yes I guess so.
Answer: This system is closed, that is $\sum\overrightarrow{F}=\vec{0}=\sum m_i\ddot{x}_i=M\ddot{S}$ which implies $\dot{S}=constant$
Answer: You need to differentiate twice to get the acceleration $\ddot{S}$(by doing it only once, you get the velocity $\dot{S}$, which will be constant — not necessarily $0$); once this is done, you should also use the expression of the forces (which for an isolated $M$-body system are only the pairwise gravitation forces between the $M$ bodies) to show that $\dot{S}=0$.
Edit: metacompactness' solution above is more straightforward and elegant.


Give permissions of LDAP group files to specific user

Question: Here is the situation:

I want user usr to have the same permissions of a group grp, anywhere in the system.
grp is not a local group, it comes from a LDAP server, of which I have no control over.

I don't have much experience with Linux, so I did some research and found two possible ways to accomplish this:

Create a local group with the same name and make usr a part of it. However, I'm  not too sure about how this would impact remote users from the original grp. Would I need to make changes to the NSS configuration file in order for this to work correctly? In that case, what should the configuration be?
Use ACL to give usr permissions. My problem with this is that it seems kind of complicated. As far as I know, there's no automatic way to do what I want, I would have to make a script that traverses the filesystem, checking the group permissions of every file and directory, and then giving usr the same permissions. Am I missing something or this would be the only way?
Comment: Why not add _usr_ to group _grp_?
Comment: I'm new to this, so I'm sorry if I'm not understanding it correctly. But *grp* comes from a LDAP server, it's not actually a local group defined in /etc/group. I don't have access to the LDAP server so I can't change its database.
Answer: It cannot be done without modifying the LDAP database. You can add local users to LDAP groups, but it must be done on the LDAP server.
The problem is that local groups and LDAP groups are different "worlds". A system can be configured to use both, but one of them will be a primary, and the other a secondary. If something is found in the primary source, the secondary will not be asked. This makes your first way a no-go: the local grp would overshadow the LDAP group (or, if the LDAP is the primary, it would just be ignored altogether).
The second approach could work, however, it is as you said: complicated, resource-extensive (traversing the filesystem can generate a lot of IO), fragile, and more like a hack than an actual solution.
I think the best way would be to ask the admin of the LDAP server to include the user in the grp group. Also, I might be wrong here, but it feels like an XY problem to me.
Comment: Please, I want to make something clear: I never thought you to be lazy, or your question not to be well written to describe the problem. I apologize if it sounded this way, it wasn't my intention. I thought this to be an XY problem, because you asked about getting access, and getting access is _usually_ a means, not an end. but it might well be that you were just curious, so again, I can be wrong about the XY part.
Comment: Oh, thanks for the clarification, I understand your point. I was indeed curious to learn more about how things work, apart from solving the original problem. Your answer was very helpful :)
Comment: I found your answer pretty useful, but I don't think my question qualifies as a XY problem (although I didn't even know the expression before and I might be wrong). I offered my attempted solution but I also stated what is the general problem I'm trying to solve. I try to do that in order to show I was not lazy, but maybe it'd be better to just describe the problem instead. Thanks.


Is a symmetric linear transformation necessarily invertible?

Question: Let $L: V \rightarrow V$ be a symmetric linear transformation. Does this imply that $L$ is invertible?
Comment: Take $L=0$ the zero transformation.
Answer: No. Let $L$ be the trivial endomorphism. That is, $L=0$.
Comment: Yes, $\det(L)=\pm 1$ for orthogonal transformations, because of $LL^t=Id$.
Comment: But is ($L$ orthogonal $\Rightarrow$ L is invertible) correct?
Answer: More generally, take a diagonal transformation $L$ with at least one zero on the diagonal. Then $L$ is symmetric and  $\det(L)=0$.


Get current class test methods before class started in TestNG

Question: I would like to get a list of test methods from the current test class before it is started. When I tried to extend TestListenerAdapter for this, testContext.getAllTestMethods() returned all test methods from all classes. But how to get only methods from the current class?
Comment: What do you want to do with those test methods?
Comment: First of all, I would like to have a list of their names. After that I would like to get their test description info.
Comment: Already used. But would like to see a simpler solution than given.
Answer: I found a partial answer on the question. First of all, I can get all test methods by extending TestListenerAdapter
public class MyListener extends TestListenerAdapter {
<code>@Override
public void onStart(ITestContext testContext) {
    super.onStart(testContext);
    ITestNGMethod[] methods = testContext.getAllTestMethods();
    // here we can save methods into some object
}
</code>
Then, in our test class in @BeforeClass() we can access the object and get the only methods from the this.getClass().getName() class. So, we filter the only methods from the current class. In this case we can access all required information like description and other important test attributes.
Answer: If you don't have a listener, you can also use the <code>@BeforeClass</code> annotation similar way as specified by OP's own answer:
<code>@BeforeClass
public void setup(ITestContext context) {
    for (ITestNGMethod method : context.getAllTestMethods()) {
        if(method.getRealClass() == this.getClass()) {
            // do what you have to do
        }
    }
}
</code>


Making a simple program that show desktop and quit

Question: I put this code:
<code>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [[NSWorkspace sharedWorkspace] hideOtherApplications];// Insert code here to initialize your application
    [NSApp terminate:self];
}
</code>
If I comment out [NSApp terminate:self]; then yea all other applications are hidden. However, if I quit the application they show up again.
Also if I make the code like that the program doesn't do anything actually. It hides all other applications and then quit showing all other applications again.
The program is simple.
Hide all application
Quit
After quitting I want all applications to remain hidden. it's so simple. How?
Comment: `-[NSWorkspace hideOtherApplications]` hides all applications except _yours_.
Comment: _Some_ application has to be shown at all times; if you do this via the application menu (⎇⌘H) in any application, and then quit it, I believe Finder is brought to the front. It also looks like Xcode re-shows itself when the debugger is attached to this process. Other than that, this code works as I'd expect it to.
Answer: What you want, I believe, is actually to minimize all other windows, not hide them.  There isn't a truly simple way to do this that I know of, but the simplest way IMO would be to call an applescript that would go through each window of each app and issue the cmd-m command.  If minimize is implemented by all of the apps then it should work fine (you could choose to close those that don't minimize if you wanted to).  It may take a bit of tinkering to get working exactly right, but the script below, taken from macscripter.net, works 80% of the time for me:
<code>tell application "System Events"
   set currentProcesses to name of every application process whose visible = true
end tell

set tmpWindows to 0

repeat with tmpProcess in currentProcesses
   tell application tmpProcess
       activate
       try
           set tmpWindows to count windows
       on error
           set tmpWindows to 1 --> # of windows to try to force closed if it doesn't 'appear' to have any windows
       end try
   end tell

   if tmpWindows > 0 then
       tell application "System Events"
           tell application tmpProcess
               repeat tmpWindows times
                   try
                       keystroke "m" using command down
                   end try
               end repeat
           end tell
       end tell
   end if

   set tmpWindows to 0

end repeat
</code>
The other option would be to use Cocoa Accessibility API to get the windows of each running app and set the AXMinimized .  Be forewarned:  It can get pretty sticky!  These 2 other stackoverflow questions should help you on the way:
Mac / Cocoa - Getting a list of windows using Accessibility API
Cocoa accessibility API, can I click a window in the background without activating it?


How can I add two spaces after each line on a given text in EMACS?

Question: Seeking how could add two spaces after each line on a given text buffer in EMACS.
This is a way for add LINE BREAKS on EMACS export via org-mode.
Comment: You could also do this with the `multiple-cursors` package in one fell swoop, but it starts to bog down after 500 plus cursors depending upon what else is going on inside the buffer.
Answer: First off, make sure you (or some package you've installed) haven't added delete-trailing-whitespace on a hook.  It's not on any hooks by default, but it's fairly common to add it to before-save-hook.
Quick and dirty:
C-M-< C-M-% $ RET SPACE SPACE RET !.

This will go to the beginning of the buffer (C-M-<),
start query-replace-regexp (C-M-%),
replacing end of line ($) with two spaces and
applying it to the every match (!).

Above, RET means press the return key and SPACE means press the space bar.  Replace $ with [^ ][^ ]$ and SPACE SPACE with \& SPACE SPACE to only work on lines that end in less than two spaces (this will also make the operation idempotent).  \& means the entire matched string (in this case, the last two characters).

Function:
(defun ensure-trailing-spaces ()
  "Ensure there are two spaces at the end of every line."
  (interactive "*")
  (save-excursion
    (goto-char (point-min))
    (while (not (eobp))
      (end-of-line)
      (unless (looking-back "  $")
        (insert "  "))
      (forward-line))))

Note that this unconditionally inserts two spaces at the end of every line, even if there is already one space, thus there will either be two or three spaces at the end of every line.


Limits under integrals and uniform convergence.

Question: I'm asked to discuss uniform and pointwise convergence of this sequence:
$$f_n(x)=\frac{1+nx}{2+nx^2}$$
It's easy to see that
$$\lim_{n \to \infty}f_n(x)=\frac{1}{x} \qquad \forall x \in \mathbb{R}\setminus\{0\}$$
and that $f_n(0)=\frac{1}{2}$ so we have that:
$$f_n \to f(x)=\begin{cases}\frac{1}{2} \qquad x=0 \\
\frac{1}{x} \qquad x \neq 0 \end{cases}$$
and clearly the convergence can't be uniform on $\mathbb{R}$ as $f_n(x)$ is continuous for all $n \in \mathbb{N}$ and $f(x)$ is not.
Now I try to study where it converges uniformely.  We can easily note that $f_n(x) \geq f_{n+1}(x)$ if $x\in (-\infty,0] \cup[2,+\infty) = A$ so the function converges uniformely in every compact contained A. As converse, $f_n(x) \leq f_{n+1}(x) \ \forall x \in A^C$ so we can declare that $f_n$ converges uniformely to $f$ in $\mathbb{R}\setminus\{0\}$.

First question: Until now is everything true and correct? I am not convinced about the last part.

Now I am asked to evaluate
$$\lim_{n\to \infty} \int_0^{\infty} \frac{1+nx}{2+nx^3}$$
as before, we have uniform convergence at $f=\frac{1}{x^2}$ in $\mathbb{R} \setminus \{0\}$ (if my previous solution was correct) and so we can divide the integral into two pieces: the one in $[a,+\infty)$ and the other one in (0,a]. As we can't talk about uniform convergence in $0$, how am I supposed to act? I intuitively think that as $f$ is $\frac{1}{x^2}$ that I'm expected to find that the limit does not exist but I'm not sure about it (the first piece, $[a,+\infty)$ is convergent, the other one I don't know).
Thanks in advance!
Thanks in advance.
Answer: You are correct that $f_n(x)=\frac{1+nx}{2+nx^2}$ does not converge uniformly on $\mathbb{R}$.  But, the convergence is not uniform on $\mathbb{R}\setminus\{0\}$, as you have asserted.
Rather, $f_n(x)$ converges uniformly on all compact sets that do not contain $\{0\}$.  So, for all $\varepsilon_1>0$ and $\varepsilon_2>0$, we have uniform convergence on compact subsets of $(-\infty,-\epsilon_1]\cup [\varepsilon_2,\infty)$.
The reason that the convergence fails to be uniform on, say $(0,2]$ is that for $x\in (0,2]$
$$\limsup_{n\to \infty}\left|\frac{1+nx}{2+nx^2}-\frac1x\right|\ne 0$$
Note that for $x\in [\varepsilon_2,2]$ we have
$$\limsup_{n\to \infty}\left|\frac{1+nx}{2+nx^2}-\frac1x\right|=0$$
and the convergence is uniform on $[\varepsilon_2,2]$.

Now, let's have a look at the limit
$$\lim_{n\to\infty}\int_0^\infty \frac{1+nx}{2+nx^3}\,dx$$
The integral converges for any $n\in \mathbb{N}$, $n>0$.  Furthermore, we can write
$$\begin{align}
\int_1^\infty \frac{1+nx}{2+nx^3}\,dx&=\int_1^\infty \frac1{x^2}\,dx+\int_1^\infty \frac{x^2-2}{x^2(2+nx^3)}\,dx\\\\
&=1+\int_1^\infty \frac{x^2-2}{x^2(2+nx^3)}\,dx\\\\
\end{align}$$
It is easy to see that
$$\lim_{n\to \infty}\left|\int_1^L \frac{x^2-2}{x^2(2+nx^3)}\,dx\right|\le \lim_{n\to \infty}\frac1n \int_1^L \frac{|x^2-2|}{x^5}\,dx=0$$
So that we assert
$$\lim_{n\to\infty}\int_1^\infty \frac{1+nx}{2+nx^3}\,dx=1$$
However, note that
$$\int_0^1 \frac{1+nx}{2+nx^3}\,dx\ge \frac12+\frac14n$$
And so, $\lim_{n\to \infty}\int_0^1 \frac{1+nx}{2+nx^3}\,dx=\infty$
Comment: Thanks a lot! For the first part that's what I wanted to say but could not. Again, thanks!
Comment: You're welcome.  My pleasure.


Extracting Phrase After A Special Character In Big Query

Question: Please see one of the phrases as example below
Start -> vendor-i (06/06/2017 09:07:18 PM) -> vendor-p (06/08/2017 04:44:47 PM) -> vendor-p (06/12/2017 11:32:33 AM) -> vendor-p (06/13/2017 04:49:47 PM)
From the above phase i need to extract vendor-i as a new variable and then vendor-p as another new variable.
There could be scenario where I have only one of the vendor names.
The code I have built is:
regexp_extract(GROUP_NAMES,r'([a-z\._]*)\.') as integrations,
      regexp_extract(GROUP_NAMES,r([vendor_que]) as vendor_que
Please suggest how we can achieve this as the vendor name can appear anywhere so we cant also define a length.
Answer: Since you want all of the names, you can use REGEXP_EXTRACT_ALL to get an array of them. For example,
#standardSQL
SELECT REGEXP_EXTRACT_ALL(GROUP_NAMES, r'-> ([^ ]+)')
FROM (
  SELECT 'Start -> vendor-i (06/06/2017 09:07:18 PM) -> vendor-p (06/08/2017 04:44:47 PM) -> vendor-p (06/12/2017 11:32:33 AM) -> vendor-p (06/13/2017 04:49:47 PM)' AS GROUP_NAMES
);

The output is the array ["vendor-i", "vendor-p", "vendor-p", "vendor-p"].
Comment: Yeah, sure. What that will do is to match every character until the next space. The `[^ ]` indicates any character except space, and the `+` means at least one match. The parentheses mean to capture the contents that are selected by the expression. You might be able to find some regular expression tutorials online that will help.
Comment: Perfect this is what i was after, but if you dont mind explaining what is this part of the formula doing ([^ ]+)'). Sorry but tried searching a lot of supporting document cannot apprehend.


Como criar um botão toggle on e toggle off?

Question: Tenho visto que em alguns cadastros, estão usando muito o botão toggle.

Alguém saberia como faz isso?
Comment: Uma sugestão sem a tag `` e mais simplificada https://pt.stackoverflow.com/q/277235/3635
Answer: Sugiro separar a pergunta em duas e ter uma pergunta à parte para a parte do servidor. Aí creio aliás que há bastantes exemplos de como fazer.

Nota: Acabei por fazer um componente destes em React no Github

A parte do lado do cliente podes fazer como no exemplo em baixo:

var estado = document.getElementById('estado');
$('#onoff1').on('change', function() {
    var el = this;
    estado.innerHTML = el.checked ? 'ligado' : 'desligado';

    // aqui podes juntar a lógica do ajax
    $.ajax({
        url: "some.php",
        data: {
            estado: this.checked
        }
    }).done(function(msg) {
        if (msg == 'failed') return el.checked = !el.checked; // caso o servidor retorne "failed" mudar o estado do botão
        else alert("Info gravada: " + msg);
    });
});
.onoff input.toggle {
    display: none;
}

.onoff input.toggle + label {
    display: inline-block;
    position: relative;
    box-shadow: inset 0 0 0px 1px #d5d5d5;
    height: 60px;
    width: 100px;
    border-radius: 30px;
}

.onoff input.toggle + label:before {
    content: "";
    display: block;
    height: 60px;
    width: 60px;
    border-radius: 30px;
    background: rgba(19, 191, 17, 0);
    transition: 0.1s ease-in-out;
}

.onoff input.toggle + label:after {
    content: "";
    position: absolute;
    height: 60px;
    width: 60px;
    top: 0;
    left: 0px;
    border-radius: 30px;
    background: #fff;
    box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.2);
    transition: 0.1s ease-in-out;
}

.onoff input.toggle:checked + label:before {
    width: 100px;
    background: #13bf11;
}

.onoff input.toggle:checked + label:after {
    left: 40px;
    box-shadow: inset 0 0 0 1px #13bf11, 0 2px 4px rgba(0, 0, 0, 0.2);
}

    <input type="checkbox" class="toggle" id="onoff1">

desligado

jsFiddle: https://jsfiddle.net/d2a9vLpj/
A parte de mudar e colorir o botão é somente HTML + CSS. O JavaScript seria somente para saber quando o botão muda e enviar para o servidor.
Comment: O problema maior é saber se o servidor reconheceu o comando (por exemplo, caso o Ajax não tenha sucesso, ou o servidor ativamente recuse a mudança, seja por permissão ou qq outra coisa, restaurar o toggle na posição anterior). Eu percebo que esse é um dos maiores problemas nestas aplicações Ajax, e nas com angular e similares. A pessoa acha que mudou o dado pelo feedback na tela, mas no servidor ainda está o dado antigo.
Comment: @Bacco bem visto. Acho que esta pergunta devia separar a lógica do servidor e browser. Vou juntar essa lógica na parte do browser.
Comment: @Bacco essa também é uma boa variante. Seria possivel também juntar um debounce  para evitar demasiados cliques e permitir baralhar o resultado. Vou esperar o comentário do AP entretanto.
Comment: Parabéns @Sergio grande resposta +1
Comment: Funcionou perfeitamente. Muito obrigado!
Comment: @RenanCavalieri um captcha é uma opção, diria que mais indicado quando a mudança on/off é "definitiva". Um debounce para impedir cliques multiplos demasiado imediatos é também uma opção. Depende de caso para caso, mas pessoalmente acho que elementos que mudam de aparência visualmente (este, um select ou um checkbox) não devem ser manipulados e impedidos de mudar de estado, por questão de UX.
Comment: Apenas uma dúvida em relação a ficar enviando dados desta forma para o servidor. E o flood, como fica? Mesmo com um debounce, ainda é possível, e sem um "submit", mesmo que por ajax, não teria como usar nenhum captcha (já que as requisições são enviadas por um simples on/off). Ao meu ver a única saída é um limite de requests, mas aí começamos a complicar o que poderia ser simplificado apenas com um botão "enviar".
Answer: Um exemplo com CSS puro seria assim https://codepen.io/andreasstorm/pen/ZGjNwZ, fiz uma versão mais simplificada https://codepen.io/brcontainer/pen/RpdgLz, o legal dele é que funciona conforme o atributo (propriedade) checked e disabled assim adaptando o comportamento :checked e :disabled
Ficando assim:

body {
    background: #eee;
}

.toggle {
    margin-bottom: 40px;
}

.toggle > input {
    display: none;
}

.toggle > label {
    position: relative;
    display: block;
    height: 20px;
    width: 44px;
    background: #898989;
    border-radius: 100px;
    cursor: pointer;
    transition: all 0.3s ease;
}
.toggle > label:after {
    position: absolute;
    left: -2px;
    top: -3px;
    display: block;
    width: 26px;
    height: 26px;
    border-radius: 100px;
    background: #fff;
    box-shadow: 0px 3px 3px rgba(0,0,0,0.05);
    content: '';
    transition: all 0.3s ease;
}
.toggle > label:active:after {
    transform: scale(1.15, 0.85);
}
.toggle > input:checked ~ label {
    background: #6fbeb5;
}
.toggle > input:checked ~ label:after {
    left: 20px;
    background: #179588;
}
.toggle > input:disabled ~ label {
    background: #d5d5d5;
    pointer-events: none;
}
.toggle > input:disabled ~ label:after {
    background: #bcbdbc;
}

    <input type="checkbox" id="foo">

    <input type="checkbox" id="bar" checked>

    <input type="checkbox" id="baz" disabled>

Versão semelhante ao iOS
Para ficar semelhante ao iOS

body {
    background: #eee;
}

.toggle {
    margin-bottom: 20px;
}

.toggle > input {
    display: none;
}

.toggle > label {
    position: relative;
    display: block;
    height: 28px;
    width: 52px;
    background-color: #f7f7f7;
    border: 1px #a2e3e6 solid;
    border-radius: 100px;
    cursor: pointer;
    transition: all 0.3s ease;
}
.toggle > label:after {
    position: absolute;
    left: 1px;
    top: 1px;
    display: block;
    width: 26px;
    height: 26px;
    border-radius: 100px;
    background: #fff;
    box-shadow: 0px 3px 3px rgba(0,0,0,0.05);
    content: '';
    transition: all 0.3s ease;
}
.toggle > label:active:after {
    transform: scale(1.15, 0.85);
}
.toggle > input:checked ~ label {
    background-color: #4cda64;
    border-color: #4cda64;
}
.toggle > input:checked ~ label:after {
    left: 25px;
}
.toggle > input:disabled ~ label {
    background-color: #d5d5d5;
    pointer-events: none;
}
.toggle > input:disabled ~ label:after {
    background-color: rgba(255, 255, 255, 0.3);
}

    <input type="checkbox" id="foo">

    <input type="checkbox" id="bar" checked>

    <input type="checkbox" id="baz" disabled>

Comment: Bonito esse css. Valeu por compartilhar a sua resposta.
Comment: @MatheusMiranda fico realmente muito agradecido =)


What is the CIDR of ds.us-east-1.amazonaws.com

Question: I am attempting to join a VM to a domain using a SSM document containing the aws:domainJoin  command. My outbound security group is closed to the internet and there is no VPC endpoint for Active directory. The AWS endpoint is ds.us-east-2.amazonaws.com and I can see in the logs:
Domain Join failed, ... A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 18.104.22.168:443
on another attempt I see:
Domain Join failed, ... A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 220.127.116.11:443
The question is, what is the IP address range that supports the various endpoints such as ds.us-east-2.amazonaws.com.
Answer: No simple answer here unfortunately. There are multiple superblocks and also a number of smaller allocations for us-east-2 service region.
The good news is you can download a json file that contains all the AWS IP blocks and get the ones that you're looking for.
https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html
Comment: Likely no. Many blocks are not contiguous.
Comment: I found a CIDR block in that file that matches. Unfortunately, the Service is listed as AMAZON (506 entries). So I got the idea to create a prefix list using the 506 AMAZON entries, but hit the 100 item limit. Is there an AWS owned Prefix list that encompasses the set of CIDRs? I cannot find one.
Comment: But are you running the AWS managed AD? Doesn't it have ENIs in your VPC's subnets? why not use those? or if you're using your own AD have you considered using AD connector, it will have ENIs in your VPC and you can connect to those.
Comment: Per docs, the aws:domainJoin command must have access to ds.*.Amazon aws.com.  This appears to be the case even when that command is provided my ADs DNS AND the VM can join the AD manually.


ViewModel fica NULL quando efetuado um submit na View Principal - Asp.Net Core MVC

Question: Tenho uma ViewModel (FilialViewModel) que possui uma propriedade do tipo PessoaViewModel. A View principal está atrelada à FilialViewModel e sempre que eu faço um submit, a propriedade do tipo PessoaViewModel fica NULL. Isso se dá pelo fato de que, no momento que chamo a PartialView Pessoa, Eu passo FilialViewModel.PessoaViewModel... Ao efetuar o submit, são carregados apenas os campos de FilialViewModel... Alguém sabe como resolver isso?
public class FilialViewModel
{
    [Key]
    public int PessoaFilialId { get; set; }

    [DisplayName("Tipo de Filial")]
    [Required(ErrorMessage = "Escolha um Tipo de Filial")]
    public FilialTipo FilialTipo { get; set; }

    public PessoaViewModel PessoaViewModel { get; set; }

}

public class PessoaViewModel
{
    [Key]
    public int Id { get; set; }

    [DisplayName("Natureza")]
    [Required(ErrorMessage = "Escolha uma Natureza")]
    public PessoaNatureza PessoaNatureza { get; set; }
    [DisplayName("Natureza")]
}

View Filial:
@model Retaguarda.Application.ViewModels.Filial.FilialViewModel
@{

}

            <vc:summary />
           @await Html.PartialAsync("~/Views/Pessoa/_Pessoa.cshtml", Model.PessoaViewModel)

View Pessoa:
@model Retaguarda.Application.ViewModels.Pessoa.PessoaViewModel
@using Retaguarda.Domain.Enuns.Pessoa
@{
    ViewData["Title"] = "Pessoa";
}

@Html.HiddenFor(model => model.Id, new { @class = "hidden-id" })

    Natureza
    <select id="pessoaNatureza" data-modal="" asp-for="PessoaNatureza" asp-items="Model.PessoasNaturezas" title="Selecione uma opção" class="form-control"><option value=""></option></select>

Controller:
[HttpPost]
[Authorize(Policy = "CanWriteFilialData")]
[Route("filial-gerenciar/cadastrar-novo")]
[ValidateAntiForgeryToken]
public IActionResult Create(FilialViewModel filialViewModel)
{
    if (!ModelState.IsValid) return View(filialViewModel);
    _filialAppService.Register(filialViewModel);

    if (IsValidOperation())
        ViewBag.Sucesso = "Filial cadastrada!";
    // return Json(new { success = true, message = "Pessoa Excuída!" });
    return View(filialViewModel);

}

Answer: PessoaViewModel vem nulo por que em nenhum momento ela foi instanciada.
Pode resolver isso instanciando em um construtor:
public class FilialViewModel
{
    public FilialViewModel()
    {
        PessoaViewModel = new PessoaViewModel();
    }

    [Key]
    public int PessoaFilialId { get; set; }

    [DisplayName("Tipo de Filial")]
    [Required(ErrorMessage = "Escolha um Tipo de Filial")]
    public FilialTipo FilialTipo { get; set; }

    public PessoaViewModel PessoaViewModel { get; set; }

}

Comment: Obrigado @George Wurthmann!


Como eu verifico se existe caractere especial ou número em uma string em C?

Question: Estou confuso na lógica para verificar se possui outros caracteres senão os alfabéticos. Eu pensei na seguinte lógica, mas creio que esteja errada:
char nome[30];
scanf("%s", nome);
int especial = 0;
for(i=0; i<strlen(nome); i++{
  if(!(nome[i] >= 'a' && nome[i] <= 'z')){
        especial = 1; // possui caractere especial ou numero
  }
}

A lógica está correta?
Comment: É uma forma, mas pode existir opções melhores, só com esse trecho meio que qualquer coisa pode servir. Também pode estar errado porque a definição está confusa.
Answer: Algumas coisas podem ser melhoradas e comentei no código porque fiz melhor.
De uns tempos pra cá adotei a postura de ensinar programar C em C mesmo. Acho errado a pessoa usar C e programar como se estive em outra linguagem. A pergunta pede o que pode ser melhorado e estou colando isto.
Já falei algumas vezes que não se deve usar strlen() quando ele não é necessário, isto é trágico para a performance, ainda mais como condição do laço. Se esse desperdício não importa então é muito simples, use outra linguagem que dá mais conforto.
Eliminei a flag que quase sempre é o mecanismo errado. Melhorei a condição.
Se puder aceitar caracteres maiúsculos terá que acrescentar mais um faixa válida.
Na verdade é possível que nem usasse esse contador do array, poderia manipular um ponteiro e mudar esse for para um while, parece ser a solução mais correta para este código.
#include <stdio.h>

int main(void) {
    char nome[30];
    scanf("%s", nome);
    int i;
    for (i = 0; nome[i] != '\0'; i++) { //sem strlen que seria péssimo
        if (nome[i] < 'a' || nome[i] > 'z') { //lógica mais adequada
            break; //encerra o laço, não tem porque continuar, achou algo que não muda mais
        }
    }
    if (nome[i] != '\0') printf("Tem caracteres inválidos"); //se não chegou ao fim
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Mantive a condição do código porque não está claro na pergunta se a intenção é diferente disto.
Comment: Muito obrigado @bigown, sempre muito útil :D
Answer: Na prática, essa "idiomática":
(!(nome[i] >= 'a' && nome[i] <= 'z'))

Não costuma ser usada por questões de padronização.
Isso acontece pois nem todos os idiomas do mundo utilizam o alfabeto latino em sua escrita.
A interface da biblioteca padrão ctypes.h fornece diversas Rotinas de Classificação de Caracteres.
São elas:

int   isalnum(int);: Testa se o caractere é alfabético ou númerco
  (alfanumérico).
int   isalpha(int);: Testa se o caractere é alfabético.
int   isascii(int);: Testa se o caractere é um dos 128 caracteres da
  tabela ASCII.
int   isblank(int);: Testa se o caractere representa um espaço em
  branco (espaço ou tab).
int   iscntrl(int);: Testa se o caractere é um comando de controle
  ASCII.
int   isdigit(int);: Testa se o caractere é um digito decimal (0-9).
int   isgraph(int);: Testa se o caractere é printável. (com exceção
  do espaço).
int   islower(int);: Testa se o caractere é alfabético minúsculo
  (a-z).
int   isprint(int);: Testa se o caractere é printável. (incluindo
  espaço).
int   ispunct(int);: Testa se o caractere é diferente de um espaço
  ou qualquer outro caractere alfanumérico.
int   isspace(int);: Testa se o caractere representa um espaço em
  branco.
int   isupper(int);:  Testa se o caractere é alfabético maiúsculo
  (A-Z).
int   isxdigit(int);: Testa se o caractere é um digito hexadecimal
  (0-9,A-F,a-f).

No seu caso, a expressão booleana:
(!(nome[i] >= 'a' && nome[i] <= 'z'))

Seria substituida simplesmente por:
(!isalpha(nome[i]))

Comment: Muito obrigado pela explicação, eu pesquei sobre o comando isalpha() depois e percebi que seria melhor utiliza-lá mesmo! Vlew pela ajuda :D


How to open a new window with target='_blank' ? My code doesn't work

Question: $html=<<<html

$i.$title	$count	$locationtext

html;
echo $html;

How to open a new window in the code above? target='_blank' doesn't work.
Answer: Your target attribute is stuck inside your href attribute. Try this:
$html=<<<html

$i.$title	$count	$locationtext

html;
echo $html;

Comment: As written, this is insecure HTML and should be updated.  It should be `Click here`.  See [The 2018 Guide to Building Secure PHP Software: Document Relationships](https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software#rel-attribute) for details.  Otherwise, you might allow the target page to take control of the original page.
Answer: look at the code output by that code. It will look like this:

$i.$title	$count	$locationtext

and you want it to be

$i.$title	$count	$locationtext

That is:
link

Answer: The reason it's not working is because you haven't separated your link attributes properly.  Try outputting the href and the target with proper separation (ie, close your quotes).
Use this:

instead of

Answer:

Answer: I have tried putting the target="_blank" in a number of places, this code comes from a rss reader but I don't want people to click and leave my site but to just open another tab
if($linked ) $msg = ''.$msg.'';  // Puts a link to the posts
Answer: Use The target="_blank" in front of the href in php
Comment: The user already has target="_blank" in their code. Their problem was a mere misplacement of the end quote on the href


How to add placeholder or 0 to Blazor Date

Question: <InputDate id="birthday" class="form-control"   placeholder=@Loc["birthday"] @bind-Value="PersModel.Pers.GeburtsDatum" />

public DateTime GeburtsDatum { get; set; }

I want the Default value to be any placeholder or Nothing only when date selected to be changed

 pers.GeburtsDatumString = pers.GeburtsDatum.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);

whenever i Change the
public DateTime? GeburtsDatum { get; set; }  to be able to be 0 i get error at

pers.GeburtsDatumString = pers.GeburtsDatum.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);

Answer: You can use the null-conditional operator to handle nullable DateTime:
pers.GeburtsDatumString = pers.GeburtsDatum?.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
//                                         ^

This returns null when pers.GeburtsDatum.HasValue is false (ie, when the value is null).
Answer: nullable Date type requires .value
pers.GeburtsDatum.Value


I cannot see the .ics file in mac desktop Calendar. Why? (iCal4j)

Question: I've created an ics file using the ical4j library, and I'm saving the file in the following directory: Users/[my name]/Library/Calendars/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.calendar/Events/
XXXXX... is the calendar which holds some of the ics files I create manually using the Calendar application, so I'm thinking this could be an appropriate place to save the ics file)
My aim is to get this ics file to show in Calendar, but it doesn't, even when I've restarted Calendar. Why is this?
By the way, this is what my ics file contains. It seems valid to me:

BEGIN:VCALENDAR
PRODID:-//Ben Fortuna//iCal4j 1.0//EN
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTAMP:20150326T104947Z
DTSTART;VALUE=DATE;VALUE=DATE:20150821
SUMMARY:testing
UID:20150326T104948Z-1@fe80:0:0:0:900c:a0ff:feba:f4a1%9
END:VEVENT
END:VCALENDAR

Any guidance or corrections would be much appreciated!
Answer: The VALUE=DATE parameter appears twice on your DTSTART property.
Have you tried to import the same event from the client to see whether it accepts it as a valid one ?
I guess even that is not a guarantee that just dropping a file under this location will work. The client may rely on some DB to keep track of the ics files it actually cares about.
Comment: Thanks I've removed the first VALUE=DATE which appears. I've also tried to parse the event but don't think I am doing it properly.
Comment: My aim is to get the ics file to show in Calendar as an event. Does Calendar store events in an external DB? Can one have access to this DB? I thought that removing an ics file within my directory lets say for a Bank Holiday would remove the event in my calendar, but it didn't.


How to connect worklight app to remote db2 DB from local worklight development server

Question: I want to connect remote db2 database to my worklight app deployed on local worklight development server.
Answer: You don't connect your 'app' to a database per se...
You either use DB2 as the database for the MobileFirst Server,
Or you use DB2 as the database that your adapter request will connect to to fetch some data.

You cannot change the database of the MobileFirst Server in your development environment (= MobileFirst Studio).
You can select which database to use for the server as part of a production installation.
To use DB2 as the database to connect an adapter to, [create an SQL adapter](https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.1/server-side-development/javascript-adapters/js-sql-adapter/.
Comment: Start adding logs then... and your code how you call the adapter, and whether it works or not in studio...
Comment: Iam using db2 database as sql adapter but my sql adapter does not invoke procedure... Sql adapter not connecting to remote db2 database... Iam deploying my adapter on my local mobile first server...


Libboost dependencies on Ubuntu 14.04 during HHVM install

Question: I'm installing HHVM following these steps on a Ubuntu 14.04 machine.
https://www.digitalocean.com/community/articles/how-to-install-hhvm-hiphop-virtual-machine-on-an-ubuntu-13-10-vps
The result I'm getting is:
The following packages have unmet dependencies:
 hhvm : Depends: libboost-filesystem1.53.0 but it is not installable
        Depends: libboost-program-options1.53.0 but it is not installable
        Depends: libboost-system1.53.0 but it is not installable
        Depends: libboost-system1.53.0 but it is not installable
        Depends: libboost-regex1.53.0 but it is not installable
        Depends: libicu48 but it is not installable
        Depends: libtasn1-3 but it is not installable
        Depends: libboost-thread1.53.0 but it is not installable

Output of: dpkg -s libboost-dev | grep 'Version' = Version: 22.214.171.124ubuntu1
What am I doing wrong?
Thanks!
Comment: Can you try this tutorial instead? https://github.com/facebook/hhvm/wiki/Prebuilt-packages-on-Ubuntu-14.04
Comment: Same with these instructions http://fideloper.com/hhvm-nginx-laravel
Answer: Those instructions are for Ubuntu 13.10. 14.04 has different requirements, so you should be following the instructions for Prebuilt 14.04 packages instead.
Comment: Damn, I assumed that it had to do with a fixed libboost or something... thanks :-)


Are jumps in the growth function of an infinite group increasing?

Question: Let $G$ be a group with a $S$ a finite subset of $G$ generating it, with $\{e\}\in S$ and $S=S^{-1}$, and let $\gamma_G^S$ be the growth function of $G$ respect to $S$, that is, $\gamma_G^S(l)$ is the number of elements of $G$ which can be expressed as a product of $\leq l$ elements of $S$. Call $J(l)=\gamma_G^S(l)-\gamma_G^S(l-1)$.
If $G$ is infinite, is it true that $J(l+1)\geq J(l)$ for $l\geq1$?
I came up with this question and it seems true, but I haven't found a way to prove it.
Comment: Not necessarily, think about finite groups.
Comment: I state in the question that $G$ is infinite, do you mean that there is some construction using finite groups?
Comment: Oh, somehow I did not notice the assumption that $G$ is infinite.
Comment: How much experimentation have you done? I'm genuinely curious about how to write a program to compute $J(l)$ quickly
Comment: I have not programmed anything, I just tried to prove that it is true for a while and considered a few very basic examples ($\mathbb{R}^n$ and infinite dihedral group with the usual generators), so it could perfectly be false. I don't know if this can be programmed for general groups
Answer: This is false: in the article
R. Grigorchuk and P. De La Harpe, On problems related to growth, entropy, and spectrum in group theory, Journal of Dynamical and Control Systems, Volume 3, Number 1, 51-89,
they provide the counterexample
$$G=\langle s,t|s^3=t^3=(st)^3=1\rangle, S=\{e,s,t,s^{-1},t^{-1}\}$$
for which $46=J(11)<J(10)=48$ (the notations you are using are related to those of the article by $\gamma^S_G(l)=\beta(G,S;l)$ and $J(l)=\sigma(l)$). (It was a very interesting question, we have been discussing it with friends since yesterday and kinda agreed that looking at the Cayley graph of the group was the best approach, until one of them found this related question on Mathoverflow which guided us to the article and so to the counterexample).
Comment: How about the same question, but for sufficiently large $l$? In other words, does $J$ always become eventually non-decreasing?
Comment: I don't know, I don't even know if the provided counterexample is "minimal" or if you can actually find another one involving lengths smaller than $10$ and $11$.


Top degree de Rham cohomology determines an orientation

Question: Let $M^n$ be a smooth, compact, orientable, connected manifold. We know then that $H^n_{dR}(M^n)\simeq \mathbb{R}$ by the map $[\omega]\mapsto \int_{M^n} \omega$. I was wondering if, given an orientation on $H^n_{dR}(M^n)$, there was a way to get an orientation on $M^n$?
Essentially, given a basis element $[\omega]\in H^n_{dR}(M^n)$ (so essentially a nonzero element of the cohomology), are we able to find a representative of this class which is an orientation form (everywhere nonvanishing)?
Any ideas?
Edit: The basic idea I had was a proof by contradiction: if for every $p\in M$, there is a representative of $[\omega]$ which vanishes at $p$. I would want to show that $\int_{M^n}\omega=0$. To do this, we would want to choose, in every coordinate neighborhood, a clever representative of $[\omega]$ which is zero on that neighborhood and sum up. Here's where I'm stuck.
Edit 2: Bott and Tu may have a sort of proof involving Poincare Duality (on pg. 87) which is a bit above my level. See also theorem 3 here (the reference is to Bott and Tu).
Comment: Do you still assume that it is orientable? (Also, in the statement $M$ should also be connected).
Comment: Yes you still assume $M$ is orientable (and yes $M$ should be connected). I'm just trying to determine when given an orientation on $H^n(M^n)$, can we find an orientation on $M$? For reference, this is problem 17-8(a) in Lee.
Answer: Well, if you know already that $M$ is orientable, then there is $\eta$ a nowhere zero $n$-form on $M$. Let
$C = \int_M \eta \in \mathbb R$.
Now for any $[\omega] \in H^n(M)$, consider $D:= \int_M \omega$. This is nonzero. Then $[\frac{D}{C} \eta] = [\omega]$ as
$$\int_M \frac DC \eta = D = \int_M \omega . $$
Note that $\frac DC \eta$ is nowhere vanishing (thus an orientation).
Comment: Yes, I was actually just about to make this comment. I guess I was just overthinking this a bit. Thank you!
Answer: You can always construct a non vanishing volume form, e.g. by choosing a Riemannian metric. Call this  $\eta$. Since $H^n_{dR}(M)$ is a one-dimensional vector space, any nonzero class $[\omega]$ is a multiple of $[\eta]$, say, $[\omega] = c[\eta]$, $c\neq 0$. So $[\omega] = [c\eta]$ and you have a nowhere vanishing representative of $[\omega]$.


How do I load a non-reentrant C++/CLI DLL twice in C#?

Question: I'm attempting to load a C++/CLI DLL into my C# program. The DLL exposes its main class as a singleton because it contains C code with a lot of global variables. So, unfortunately, the DLL is non-reentrant. The DLL can connect to a single instance of a piece of hardware (identified by a hardware ID).
However, I have multiple pieces of the same hardware attached, and I'd like to load multiple instances of the DLL into my C# program so I can access each piece of hardware.
Is it possible, in C#, to load that C++/CLI DLL multiple times into different memory spaces so that the globals in the DLL don't conflict with each other?
Let's assume for the purposes of this question that I don't have access to the source code of the C++/CLI DLL.
Comment: You can't load the same DLL multiple times. You can copy it under a different name so it's a "different" DLL, or you can farm off work to child processes that you communicate with through an IPC mechanism of your choice. The latter is probably more stable, as the DLL wasn't designed to load more than once and it might create or rely on global kernel objects that get the same name -- there's no working around that.
Comment: Can't you build the DLL multiple times, with different names, for each piece of hardware?
Comment: @sturcotte06 Yes. I can build it, let's say--3 times. And then someone will come along and attach 4 of these USB dongles. Where do I stop?
Comment: @Jeroen Mostert. Does loading the DLL into different Application Domains (if that even makes sense) effectively put it in different processes?
Comment: Produce 8 DLLs so you can support 8 USB ports. Expose the limitation. That's why globals are bad; you want clear scope so you can have any numbers of scopes at runtime. Bad design gives bad results.
Comment: @watkipet A DLL is only a dynamically linked library; it links at runtime instead of compile time. It was not meant to manage object lifetime, but to load features dynamically. The one who made the DLL used the library as a lifetime. You can only link this DLL once per process. There's no notion of application domain is operating systems; it's purely a usermode invention of microsoft.
Comment: @sturcotte06 To make multiple copies of a managed DLL that don't collide, I'll need to change the name, the namespace, and the assembly GUID, right? Can you post an answer showing how my C# program can do this for an existing assembly DLL for which I don't have the source?
Comment: While AppDomains do offer some form of separation (less so than processes) whether or not your assembly would work with that is an open question. The unmanaged parts (i.e. the code that the C++/CLI is wrapping) do not know or care about AppDomains and will not be isolated by them -- and moreover, all this is still running in the same process. All instances would share the same C runtime heap and the same kernel handles. There are many ways such a setup can fail.
Comment: Anyone care to put this info into an answer? Something that mentions AppDomains (and why they wouldn't work in this scenario), IPC (doesn't have to go into implementation details), and copying / modifying the DLL (without having access to the source) would be great.
Answer: It's possible by loading same dll twice to RAM, but you will need to use different virtual .dll filename for each time.
See following project as example:
https://github.com/tapika/dllloader
test_managed_dllloader-project.
Comment: Does this load the DLL's variables into an entirely separate memory space? i.e. does this comment still hold? `All instances would share the same C runtime heap and the same kernel handles. There are many ways such a setup can fail.`
Comment: If you copy same dll to different dll filename and load it - they will get different set of globals. I guess it's not necessary to load them additionally into ram.
Comment: See also https://github.com/tapika/dllloader/issues/1#issuecomment-1279689837


How to add and associate Paragraphs to Media Library Images Programmatically

Question: Good day everyone,
Our client wants to have this feature where he can upload/reuse multiple images for an article content type. This can be achieved using a Media Library, where I find it tricky is each images will have additional fields(Alt, Copyright, Description fields), I've tried adding the additional fields to the Image Media Type but once the node is saved, their value will be associated to the image's metadata. The proper functionality should be is when the node is saved, the Alt and Description of the images should be associated to the node's metadata because Images can be reusable to another node, and the values of Alt and Description varies to each node.
So I talked with someone who really knows a lot about Drupal. He suggested that I keep the Media Library, and create a Paragraph Type. I called it 'Image Library Paragraphs', this paragraph has Image, Alt, Copyright, and Description fields. This way the Paragraph can hold the id of the image, alt, description and the node's ID. In theory, what we're trying to do here is everytime the user uploads/select an image. We must find a way to associate that image and add corresponding paragraph for each of those images. So if the user uploads/selects 3 images. It will also automatically create 3 paragraphs for those images. We also would need to reconstruct the layout of the form to somehow "blend" the image and its corresponding paragraphs. And since the position of the images can be changed, we also need to somehow reposition its paragraph accordingly to the image.
It's tricky and a lot of work, honestly it's even beyond my Drupal skills. But any help to the right direction will truly be appreciated. I haven't even tried creating a really complex custom module. But would really want to learn how this can be done. Thank you in advance.
In theory this is what it's gonna look like
Comment: Article only has paragraph field (no media field, no file field). Paragraph has media reference field (NOT file; set cardinality to 1) and whatever meta data fields. Exacltly one media per paragraph. Advantage: No coding required at all. Disadvantage: No multi upload, you must create one paragraph and can select/upload exactly one image.
Comment: hi @Hudri, thank you very much for taking time to help me. indeed we have tried that approach as well. but the user's use case involves multiple upload/select images. thats why we couldnt use only paragraphs.
Comment: Sorry, but I can't see any chance for multi-upload without _a lot_ of custom coding. This site is for narrow Q&A, not for tutorials, and your requirements are well beyond both.
Comment: @Hudri it's okay I understand. Really appreciate your responses!
Comment: Why don'y you write a presave hook for a media item to write its field data back to the parent entity? Better yet, why can this data not be extrapolated through the reference? You can even do it right in the UI if you install display suite and display suite chains module.
Comment: @RyanHartman, I'm truly happy someone like you shared an idea about this as I've ran out of my own. There are some pracitces that I'm not familiar yet as I've only been using Drupal for about a few months. I'm gonna check the display suite and display suite chains module.
Comment: @RyanHartman, I've just installed the modules and looking around for a little. Is it possible to enable it in the create article forms? the one I saw in their screencast is enabling and customizing it for the frontend. :)
Answer:
Create a paragraph "Node Image".
Within the Paragraph type, add your media reference field and various text fields for your image metadata. Set them all to required, this is key for later.
Go back to your Node type and add a new Paragraphs field called "Node Images", set to unlimited cardinality. Restrict the field to only allow the "Node Image" Paragraph type.
On the Node's Form Display, set to the new field to "Paragraphs Experimental".
Configure the settings (the gear icon) to suit your needs. AKA override the single/plural to be "Node Image" and "Node Images", set to closed, use button, default value...etc. Fiddle with it.
Create a Test Node with 2 of these paragraphs. Ensure theme debugging and cache is off. Otherwise you will have to flush each time.

At this point you have all the ability to add the data needed to
Drupal. The rest can be handled via traditional theming methods, or
Display Suite. Within display suite there are even various routes to
accomplish this. I will explain what I feel is the simplest method.
This method relies on the fact that all your fields are
required, unless you are OK with possibly printing things like empty
tags. Remember from earlier when I said it was key?

Go to Display Suite > Fields in the admin UI and create a new "Token field" name it "SEO Image" or something fun.
Within that field, configure it to show up for Paragraphs of type "Node Image".
In the field content, build an  tag and fill in the data with values properly. You might want to brush up on tokens and reference fields with the :entity: keyword. You will need that to get the URL for the image. For the SEO fields, you can just find them in the token browser NOTE: You will need to ensure that a text format is setup that allows both HTML and tokens :)
Go to your Paragraph type, and visit the Manage Display tab. On that page, at the bottom, enable the display to be "Display Suite : Reset". Save the page to reload the form.
Remove all of the other fields from being enabled, and instead drag the new Token field we created to enabled. Save the form.
Go look at your Test node. You should see your images rendered through that token field on the front end.

If any of this doesn't work, tweak your settings. There is a bit of a learning curve here. Webwash has done some great tutorials on all of the concepts covered if you want to do some research.
The Paragraphs experimental widget is really powerfull, for your backend UI needs of reordering and side by side you can do the following:

Create a new display mode (or view mode as you might also know it) for your paragraph called "Node Image Admin".
Go you your paragraph type, and under Manage Display, you can enable that view mode. Once you have this setup, you can now alter the HTML markup to build your side by side admin UI. This would vary depending on your admin theme. You could also try using Display Suite and the Field Group module to do it all in the UI, so many options really once you digest everything.
The final step is going back to your "Manage Form Display" for your node type. Edit the settings (gear icon) for the Paragraphs field and set the closed display to the new view mode.

As stated, paragraphs experimental widget has drag and drop, mass drag and drop, and all kinds of features to discover. I have yet to find anyone who wants to pay for more that what you get out of it when they have been given a tutorial of how to use it. It is really on the developer to tweak it to work best for each use case.
Comment: How does this solve the multi-upload issue? Everything else can be done without an extra, complex, heavy-weight extension like Display Suite.
Comment: I just applied my patterns that I follow for the solution. You can of course extract the important bits and solve theming any way you would like. I do not understand your aversion to DS though? It's saved us thousands of hours when put into practice. As far as multi upload? Thats really not how media is designed to work. You wouldn't ever request to bulk add entire nodes because that is called an import. If I was OP, I would tell his client that he can solve it all, in less than a day using contrib, just without bulk. It's not a Drupalism to do something like this.
Comment: Sorry to use an extra comment. Just to drive home my point. The solution for this is to develop an entire custom module. A new custom entity type that mimics what the paragraph already does, a custom formatter for the custom field type. The whole shebang. Basically 80% of drupal core. At the end, they get to bulk add images to a page that they have to go and individually fill out anyways. This is a rabbit hole of UX troubles and weeks of work for anyone but a seasoned dev.
Comment: @RyanHartman, sorry it took me long to reply. I got busy yesterday and I've also tried out your answer. I really appreciate your help but unfortunately it didn't work for us. I've talked with my boss about the complexity of the issue. We wanted to try a different method, it still isn't easy for me. I think I will post it in another question. Thank you both of you and Hudri.


Dinamically absorb child siblings' values into the one parent's text

Question: I'm in a little trouble about how to write the dynamic part of XSLT which should happen with C elements. All values of element C must be merged into one text and separated by additional text inserts, like "name-1, name-2", etc (depending on C-siblings amount).
source
<root>

        <C> aaaa </C>
        <C> bbbb </C>
        <C> cccc </C>

</root>

desired output

my XSLT (doesn't work correctly with "C" elements)
https://xsltfiddle.liberty-development.net/ncnu9Bv/1
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
      <xsl:template match="A">

          <xsl:copy-of select="@*"/>
          <xsl:copy-of select="@*|B/@*"/>
          <xsl:copy-of select="//A/B/C"/>

      </xsl:template>
    </xsl:stylesheet>

How to imrove existing XSLT according to desired model?
Answer: How about:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="A">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:copy-of select="B/@*"/>
        <xsl:attribute name="c-text-absorbation">
            <xsl:for-each select="B/C">
                <xsl:text>name-</xsl:text>
                <xsl:value-of select="position()"/>
                <xsl:text>: </xsl:text>
                <xsl:value-of select="."/>
                <xsl:if test="position() < last()">
                    <xsl:text>, </xsl:text>
                </xsl:if>
            </xsl:for-each>
        </xsl:attribute>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


Drupal how to have certain admins only see the users they've created

Question: I use Drupal 7 and would prefer to do so but if I need to use Drupal 6 I will.  I have a Drupal 7 site that I allow "advisors" to create authenticated users. I am an admin on the site so I see and can do everything. All that an "advisor" can do is create and edit authenticated users. Is there a way to make a view that displays the users that the particular advisor has created while the advisor is logged in?
If you don't understand what I'm saying let me put it this way. I am the admin of the site so I can do everything. I created a user role called advisor. There's also an authenticated role for users. Advisors can create authenticated users. So I have Advisor 1. Advisor 1 created 10 users. I also have Advisor 2. Advisor 2 created 3 users. I'd like a page (more than likely built with views - and I've used views before on other sites so I'm familiar with them) - I'd like a page that Advisor 1 could go to once logged in and it would display all of the 10 users that they created. Advisor 1 wouldn't see the users that Advisor 2 create.
Is this possible? Any help on this would be greatly appreciated. Thank you in advance.
Comment: This certainly requires building custom features with custom permissions. There is no such features or module(s) available which offer the feature out of the box.
Answer: I have implemented something similar and I can give you some guidelines.
First of all drupal 7 doesn't store the information of the creator of the users.
So, in order to track this you will need to attach a custom field to the user to keep this information.
In such case you ll have to make sure that every creator can insert only himself in this field and not anyone else or you 'll have to find an automated way to fill it in.
I suggest you use field permission module for setting permissions to this field (users probably should not even have view, creators should not be able to change it etc ) and computed field module for automatically populate the field (eg creator_field) upon creation for example with the uid of the creator.
Finally when creating the view you could add  contextual filtering by using the logged in user on the creator_field.
You should also have a look at Organic Groups. I haven't use it but might be helpful
Hope it helps.
Updated
Add
<code>  global $user;
  $entity_field[0]['value'] = $user -> uid;
</code>
to the Computed Code (PHP) in the computed field settings and store the value as integer in "Database store settings". Then in your view you should add a view of user with  contextual filter of creator_field. In the contextual filter settings you must set "provide default value" -> "User ID from logged in user"  in the "WHEN THE  FILTER VALUE IS NOT IN THE URL" section.
Comment: Thanks, makes sense.  I will try it out and let you know how it goes.
Comment: Ok geoandri (or anyone), I need some help.  I've added the computed field as you've said but what exactly would I be putting into the "Computed Code (PHP)" field and the "Display Code (PHP)" field within my new field called "creator_field".  See this screen grab and you'll se what Drupal put in there as default.  http://michaeljbaran.com/field-setting.jpg
Comment: try     global $user;
  $entity_field[0]['value'] = $user -> uid;  in the Computed Code and set "database storage setting" to integer. I ll add it to my post also
Comment: Ok, I found an error in what I did and was wondering if anyone can help. So I have a computed field that's hidden from display on my site. I wanted to tie the admin who created it to the new user account. This computed field is called "creator_field" and I have the

Computed Code (PHP)

global $user;
$entity_field[0]['value'] = $user -> uid;

and I have the Display Code (PHP)

$display_output = $entity_field_item['value'];
Comment: This does what I want BUT if another admin (we'll call him admin2) was to edit the new user (we'll call the new user account Bob) that the admin1 created THAN the user account Bob would fall under admin2's user list because they edited it. I'm sure there is any easy fix for this and I just can't figure it out. Anyone have any ideas? Much appreciated and Happy New Year!
Answer: This could be done relatively easily in Drupal 7 by adding a field to the user profile that points back to the user creator (using the Entity Reference module). Profile2 could offer a shortcut to making this field available on a profile, though if this is the only customization that you need to add to your profiles, it would be cleaner to do this in a custom module.
A view (Views module) could be configured to output a list of users with the current logged in user as the creator.
You'll also need to add similar logic for user_access to allow/restrict profile editing (if the current user is the user referenced in the profile).  A permissions hook also could be useful if you plan to have different admin levels.
The Tokens module should work to insert this value for the new user, by inserting the current user into the field. Or you can do this before the user is saved. It would go a little something like this:
<code>function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->is_new) {
    global $user;
    $created_by = $user->uid;
    $edit['created_by'] = $created_by;
  }
}
</code>
Good luck.
Comment: on top from my comment below to geoandri, I tried what you suggested baaj and there's only one thing, how the heck would I get that new field to automatically get populated with the creators ID?  I've tried several different approaches and nothing was successful.  I don't really care how I get this done as long as I can get it done : )
Comment: Updated my answer to address your question above