text:
Q: FOSS Wipe free space (7, 35 passes) I know there are tools on linux that can do this (sfill) as well as windows (ccleaner). However I would prefer FOSS that does this. To my knowledge Eraser does not wipe free space... If it does I stand corrected.

A: Eraser by Heidi Computers can erase unused / free disk space:
http://bbs.heidi.ie/viewtopic.php?f=2&t=6307
It is released under GPL.
That said, you might want to consider your exact security needs. You should be aware that wiping free disk space may still leave remainders of files lying about:

*

*Programs may leave begin temporary files with confidential data. These are not free space to the OS and filesystem, hence will not be wiped.

*It may not be possible to wipe all unused areas because of filesystem / OS limitations. Eraser will try to warn of this, but the devs might have overlooked something.

*You might simply have forgotten that you kept a copy of a sensitive file somewhere.

*Parts of the data might be in the pagefile / swap file. Consider wiping that as well (but check how to do this correctly, otherwise your OS might refuse to boot!).

*The storage device may relocate data behind your back: Both harddrives and SSDs will relocate data transparently in case of medium errors or for wear leveling (SSDs). In that case writing new data to a sector with existing data will actually write to a new sector, instead of overwriting the original data. Of course, actually reading this "residual" data may require some hardware trickery.

In my opinion, if you ever worked with sensitive data on a partition (especially if it's an OS partition where temp and OS storage is located), the only safe option is to wipe the whole OS partition plus any data partitions you used. Modern filesystems just do too much behind your back for any other method to be safe in general.

A: I don't have access to a machine with it installed at the moment, but I'm pretty sure that Eraser has the option to wipe the unused part of a hard drive and possibly wipe something called tool tip clusters (not 100% sure about that term)?


text:
Q: What is $T^0_0(M,W)$ where $W$ is trivial vector bundle over a compact manifold $M$? Let $W=(M \times \mathbb{R}, pr, M)$ be the trivial vector bundle over a compact manifold $M$, and define $$V=T^0_0(M,W) := T^0_0M \otimes W,$$
and $V$ is called "the vector bundle of $W$-valued (0,0)-tensors on $M$".
Apparently we can identify $T^0_0(M,W) = T^0_0(M, \mathbb{R}) = T^0_0(M)$.
My question is, is there a simple way to describe $V$? Is it $V=\mathbb{R}$?
Here, $T^i_k M$ is the $(i,k)$-tensor bundle.

A: It's not very common to use the language "$(0,0)$-tensor", but by convention a $(0,0)$-tensor on a vector space $V$ is just a scalar, and so a $(0,0)$ tensor field on a manifold $M$ -- that is, an section of $T_0^0(M)$ -- is a smooth function on $M$.
Likewise, it's obvious that the smooth functions on $M$ are exactly the sections of the trivial bundle $W = M \times \mathbb{R}$. Thus $T_0^0(M) \cong W$ as bundles, and both are trivial one-dimensional bundles.
It follows from the definitions that if I take the tensor product of two one-dimensional trivial bundles over $M$, what I get is a one-dimensional trivial bundle.
So, $V \cong W \cong T_0^0(M)$ is the trivial rank one bundle over $M$, whose sections are the smooth functions on $M$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tensor product $E\otimes_{A} F$ of modules $E,F$ where $F$ has a basis
Let $A$ be a ring, $E$ a right $A$-module and $F$ a left $A$-module.
  Let $(b_\mu)_{\mu\in M}$ be  a basis of $F$. Then every element of
  $E\otimes_AF$ can be written uniquely in the form $\sum_{\mu\in
 M}(x_\mu\otimes b_\mu)$ where $x\in E^{(M)}$.

Attempt:
The mapping $v:\bigoplus_{\mu\in M}Ab_\mu\rightarrow F,\,y\mapsto\sum_{\mu\in M} y_\mu$ is an $A$-module isomorphism. Furthermore, there exits a $\mathbf{Z}$-linear bijection
$$g:E\otimes_A\bigoplus_{\mu\in M}Ab_\mu\rightarrow\bigoplus_{\mu\in M}(E\otimes_AAb_\mu)$$
such that $g(x\otimes(y_\mu)_{\mu\in M})=(x\otimes y_\mu)_{\mu\in m}$ for $x\in E$ and $y\in\bigoplus_{\mu\in M}Ab_\mu$. Thus the mapping
$$[1_E\otimes v]\circ g^{-1}:\bigoplus_{\mu\in M}(E\otimes_AAb_\mu)\rightarrow E\otimes_A F$$
is a $\mathbf{Z}$-isomorphism. At this point, I don't how to deduce the required property: that every element $z\in E\otimes_A F$ can be uniquely written in the form $\sum_{\mu\in
 M}(x_\mu\otimes b_\mu)$ where $x\in E^{(M)}$. Any suggestions?

A: Start with a pure tensor $x\otimes y$, with $x\in E$ and $y\in F$. By assumption,
$$
y=\sum_{\mu\in M}a_\mu b_\mu
$$
and therefore
$$
x\otimes y=\sum_{\mu\in M}(xa_\mu)\otimes b_\mu
$$
Now passing to generic elements of $E\otimes_A F$ is easy.
What about uniqueness? Consider the isomorphism $g\colon A^{(M)}\to F$, $g((a_\mu)_\mu)=\sum_\mu a_\mu b_\mu$
Then define
$$
\tau\colon E\times F\to E^{(M)},\qquad \tau(x,g((a_\mu)_\mu))=(xa_\mu)_\mu
$$
Prove it is balanced, so it induces a group homomorphism $E\otimes_A F\to E^{(M)}$ and show that an obvious map is its inverse.


text:
Q: Do we have to memorize the binary digits' representations for all kinds of numbers or their is a method to know how to represent each? For example: octal 3 is 011 in the binary digits, and decimal 3 is 0011.

So, is there any way to figure them out or this table must be copied and pasted in my memory?


text:
Q: Class properties for react lifecycle methods Can I write React lifecycle methods as class properties?
I've been using class properties for a while as I like the fact that I no longer have to manually bind my methods, but I'd like to keep some consistency across my components and I'm wondering if there is any drawback on writing the React lifecycle methods as class properties
import React, { Component } from 'react';

class MyComponent extends Component {

  render = () => {
    return (

Foo Bar

    );
  }

}

export default MyComponent;

For example, is the context of this class property affected compared to the context in an equivalent method. Given that the render method in the above code is written as an arrow function, this concern seems relevant.

A: In a way, the true answer depends on your build pipeline and what the resulting Javascript output looks like. There are two primary possibilities:
Input Code
Let's start by saying you are writing the following before going through any sort of pipeline transformations (babel, typescript, etc):
class Test {
    test = () => { console.log('test'); };
}

Output as class member variable.
In one possible world, your pipeline will also be outputting the test function as a member variable for the output class. In this case the output might look something like:
function Test() {
    this.test = function() { console.log('test'); };
}

This means that whenever you write new Test() the test function is going to be recreated every single time.
Output as class prototype function
In the other major possibility, your pipeline could be recognizing this as a function property and escape it from the class instance to the prototype. In this case the output might look something like:
function Test() {
}

Test.prototype = {
    test: function() { console.log('test'); }
}

This means that no matter how many times you call new Test() there will still be only one creation of the test function around in memory.
Desired behavior
Hopefully it's clear that you want your end result to have the function end up on the prototype object rather than being recreated on each class instance.
However, while you would want the function to not end up as a property, that doesn't necessarily mean you couldn't write it that way in your own code. As long as your build chain is making the correct transformations, you can write it any way you prefer.
Although, looking at the default babel settings (which your babeljs tag leads me to believe you are using) it does not make this transformation for you. You can see this in action here. On the left I've created one class with the function as a property and one class with the function as a class method. On the right hand side, where babel shows it's output, you can see that the class with the function as a property still has it being an instance-level property, meaning it will be recreated each time that class's constructor is called.
I did find this babel plugin, which seems like it might add this transformation in, but I've not used it for myself so I'm not positive.

A: In my experience, the most reason for writing a method as a class property is when the method will be passed as a callback, and you need it to always be bound to the instance. React lifecycle methods will always be called as a method, so there's no reason to bind them (and you incur a tiny memory penalty when you do). Where this makes a difference is when you're passing a function to a component as a callback (e.g. onClick or onChange).
Take this example:
class BrokenFoo extends React.Component {
    handleClick() {
        alert(this.props.message);
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                Click me
            </button>
        )
    }
}

The function represented by this.handleClick is not automatically bound to the component instance, so when the method tries to read the value of this.props it will throw a TypeError because this is not defined. Read this article if you're not familiar with this; the problem described in section 4.2 "Pitfall: extracting methods improperly" is essentially what's happening when you pass around a method without making sure it's bound correctly.
Here's the class, rewritten with the handler as a class property:
class HappyFoo extends React.Component {
    handleClick = () => {
        alert(this.props.message);
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                Click me
            </button>
        )
    }
}

Effectively, you can think of the handleClick definition in the second example as placing this code into the component's constructor (which is just about exactly the way Babel does it):
this.handleClick = () => {
    alert(this.props.message);
}

This achieves the same thing as calling bind on the function (as described in the linked article) but does it a little differently. Because this function is defined in the constructor, the value of this in this.props.message is bound to the containing instance. What this means is that the function is now independent of the calling context; you can pass it around and it won't break.
The rule of thumb that I follow: by default, write methods as methods. This attaches the method to the prototype and will usually behave the way you'd expect. However, if the method is ever written without parentheses (i.e. you're passing the value and not calling it), then you likely want to make it a class property.


text:
Q: How to make hit area for android button ? like flash hit area I want to know how to make 'hit area' for an android button.
I have a button with background image. This image is non-uniform shape. I want to make a 'hit area' and a 'non-hit area' -- the area with shape is the 'hit area', transparent area is 'non-hit area'.
The background image is composed of a transparent area and a non-transparent area.

A: The only method is to put a view transparent above it and listen for touches in this 'ghost' view.


text:
Q: Ошибка при реализации метода загрузки файла на ftp сервер, java Есть метод, который загружает файл на ftp-сервер, по нажатию кнопки.При отладке проекта на устройстве, по нажатию кнопки(запуску метода) происходить ошибка в приложении и оно вылетает.
Я использую следующий метод:
public static void FTPDownloadto() {
    String server = "192.168.0.103";
    int port = 21;
    String user = "anonymous";
    String pass = "";

    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #1: uploads first file using an InputStream
        File firstLocalFile = new File("\\storage\\ext_sd\\DCIM\\100MEDIA\\IMAG0171.jpg");

        String firstRemoteFile = "IMAG0171.jpg";
        InputStream inputStream = new FileInputStream(firstLocalFile);

        Toast.makeText(MainActivity.this, "Начало загрузки первого файла", Toast.LENGTH_SHORT).show();
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            Toast.makeText(MainActivity.this, "Первый фаил загружен успешно", Toast.LENGTH_SHORT).show();
        }

    inputStream.close();

    boolean completed = ftpClient.completePendingCommand();
    if (completed) {
    Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
    }

    } catch (IOException ex) {
    Toast.makeText(MainActivity.this, "Ошибка:" + ex.getMessage(), Toast.LENGTH_SHORT).show();
    ex.printStackTrace();
    } finally {
    try {
    if (ftpClient.isConnected()) {
    ftpClient.logout();
    ftpClient.disconnect();
    }
    } catch (IOException ex) {
    ex.printStackTrace();
    }
    }
}

При запуске метода появляется ошибка:
android.os.NetworkOnMain.ThreadExseotion

Погуглив нашёл способ устранения этой ошибки, с помощью AsyncTask, но это тоже не устранило данную проблему.
Используются библиотеки apache commons net, в манифесте android studio прописаны разрешения:
 <uses-permission android:name="android.permission.INTERNET" />

Непонятны способы устранения данной ошибки.
Попытка решения проблемы с помощью AsyncTask:
 class FTPUploadFile extends AsyncTask<Void, Integer, Void> {
//прежде чем задача выполнена
@Override
protected void onPreExecute() {
    super.onPreExecute();
    Toast.makeText(MainActivity.this, "Начало процесса", Toast.LENGTH_SHORT).show();
}

//после окончания задачи
@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    Toast.makeText(MainActivity.this, "Процесс окончен", Toast.LENGTH_SHORT).show();
}

@Override
protected void onProgressUpdate(Integer... values) {

}

//задача\
@Override
protected Void doInBackground(Void... params) {
    String server = "192.168.0.103";
    int port = 21;
    String user = "anonymous";
    String pass = "";

    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #1: uploads first file using an InputStream
        File firstLocalFile = new File("\\storage\\ext_sd\\DCIM\\100MEDIA\\IMAG0171.jpg");

        String firstRemoteFile = "IMAG0171.jpg";
        InputStream inputStream = new FileInputStream(firstLocalFile);

        Toast.makeText(MainActivity.this, "Начало загрузки первого файла", Toast.LENGTH_SHORT).show();
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            Toast.makeText(MainActivity.this, "Первый фаил загружен успешно", Toast.LENGTH_SHORT).show();
        }

        inputStream.close();

        boolean completed = ftpClient.completePendingCommand();
        if (completed) {
            Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
        }

    } catch (IOException ex) {
        Toast.makeText(MainActivity.this, "Ошибка:" + ex.getMessage(), Toast.LENGTH_SHORT).show();
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return null;
}

}

A: *

*doInBackground не имеет доступа к графическому потоку, так что Toast.makeText() здесь лишний.

*AsynсTask нужно запускать через метод execute, а не через вызов  doInBackground.


text:
Q: "Not a HASH reference" error in perl while creating a multi-dimensional hash with its key able to store multiple values I am trying to create a multidimensional hash with its keys as an array so that the same keys can store multiple values, and is not overridden.
Below is the code snippet:
my %hashR;
my @RelDiv = qw(15.4 dev ques 15.4 dev ques2 15.4 dev2 ques1 15.4 dev2 ques2
                15.2 dev3 ques2);
while (my $RName = shift @RelDiv) {
    my $ProStr = shift @RelDiv;
    push @{$hashR{$RName}}, $ProStr;
    my $BName = shift @RelDiv ;    ## Working file till here (tried printing the values)
    push @{$hashR{$RName}{$ProStr}}, $BName;   ###### Error on this line
}

The structure I want is as follows:
{
      '15.4' => {

                   'dev' => [
                                'ques',
                                'ques2'
                            ]

                  'dev2' => [
                               'ques1',
                               'ques2'
                             ]

                },
       '15.2' => {
                   'dev3' => [
                                'ques2'
                            ]
                }

};
But, I am getting an error "Not a HASH reference at file1.pl line". Can anyone please help in resolving the error?
Thanks

A: You create an array reference when you do this:
push @{$hashR{$RName}}, $ProStr;
# means: $hashR{$RName} = [ $ProStr ]

Then you try to use it as a hash ref when you do this:
push @{ $hashR{$RName}{$ProStr} }, $BName;   ###### Error on this line
#                    ^^^-- here

Its hard to tell what you want the structure to look like, so I can't really help you with recommendations. Perhaps if you explained what you are trying to achieve, I could help.

With the new structure update, this is a simple way to do it
use strict;
use warnings;
use Data::Dumper;

my %hash;
my @RelDiv = qw(15.4 dev ques 15.4 dev ques2 15.4 dev2 ques1 15.4 dev2 ques2 15.2 dev3 ques2);

while (@RelDiv) {
    my ($RName, $ProStr, $BName) = splice @RelDiv, 0, 3;
    push @{ $hash{$RName}{$ProStr} }, $BName;
}
print Dumper \%hash;

Output (the data structure):
$VAR1 = {
          '15.4' => {
                      'dev2' => [
                                  'ques1',
                                  'ques2'
                                ],
                      'dev' => [
                                 'ques',
                                 'ques2'
                               ]
                    },
          '15.2' => {
                      'dev3' => [
                                  'ques2'
                                ]
                    }
        };

The below criticism remains, however. There is something you're not telling about your data collection, and this solution with splice from an array is not very good. You should go back one step and talk about your data collection.
Its not a very good way to create a hash, though. If you are just going to assign a list of values to an array at the start, instead assign it to the hash right away and don't do this strange conversion into another structure. Or if you are, as I suspect, reading from a file, again, create the hash structure right away. If you give more detail, I can provide better recommendations.


text:
Q: Proof concerning sequence and series of functions
Let $\{s_n\}_{n=1}^{+\infty}$ be a sequence of distinct points in the interval $(a, b)$, $\{c_n\}_{n=1}^{+\infty}$ be a positive sequence such that the series $$\sum_{n=1}^{+\infty}c_n$$ converges. Define $g:[a,b]\rightarrow \mathbb R$ by $$g(x)=\sum_{n=1}^{+\infty}c_np(x-s_n)$$ where $p$ is the unit step function. Show that for every continuous function $f:[a,b]\rightarrow \mathbb R$, we have $$\int_{a}^b f(x)\,\ dg(x) =\sum_{n=1}^{+\infty}c_nf(s_n) $$

I'm having difficulty proving the Riemann-Stieltjes integral and looking for any help. Thanks!


text:
Q: How to create a Event in Django-Scheduler while creating a Object in Django? I am a total newbie in Python and new on StackOverFlow. If I am missing something please let me know
This is Django-scheduler App:- https://github.com/llazzaro/django-scheduler
It giver various options to create events and occurrences
Documentation is here:- http://django-scheduler.readthedocs.io/en/latest/
I have a model known as Product in Django. Which is defined as below
`class Products(models.Model):
 product_choice = (
    ('1' ,'sightseeing'),
    ('2','daytour'),
    ('3','activity'),
    ('3','experience'),
    ('4','rentals'),
    ('3','multidaytrip'),
)

 product_type = models.CharField(max_length=20,choices=product_choice, null=True)
 category = models.ForeignKey(Category, null=True)
 title = models.CharField(max_length=100, blank=True, default='')

 pic1 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg')
 pic2 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg')
 pic3 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg')

 shared_code = models.BooleanField(blank=True, default=False)
 age_requirements = models.CharField(max_length=100, blank=True, default='')
 time_slots = models.CharField(max_length=100 ,blank=True, default='')
 location = models.CharField(max_length=100 ,blank=True, default='')
 duration = models.CharField(max_length=100 ,blank=True, default='')

 affiliated_institutions = models.CharField(max_length=100, null=True)
 includes = models.TextField(blank=True)
 excludes = models.TextField(blank=True)
 medical_requirements = models.CharField(max_length=100, blank=True, default='')
 perks_included =  models.CharField(max_length=100, blank=True, default='')
 product_detail = models.TextField()
 vender_name = models.CharField(max_length=100, blank=False)
 user = models.ManyToManyField(settings.AUTH_USER_MODEL)
 vendor_id = models.IntegerField(blank=True)
 about_vender = models.TextField()
 price = models.IntegerField(default=0)
 child_price = models.IntegerField(default=0)
 infant_price = models.IntegerField(default=0)
 product_detail = models.TextField(blank=True)
 slug  = models.SlugField(unique=True, blank=True)
 total_slots = models.IntegerField(blank=True, null=True)
 open_slots = models.IntegerField(blank=True , null=True)

 cancellation_policy = models.TextField(blank=True)

  def __unicode__(self):
return str(self.title)

 def __str__(self):
return str(self.title)

`
I have installed the Django-Scheduler in my Django Application, however it is installed as a separate app.
I am using Django Rest Framework(DRF) and doing all these alterations via DRF.
class ProductListAPIView(ListAPIView):

 queryset = Products.objects.all()
 permission_classes = (IsAdminOrReadOnly, )
 serializer_class = ProductSerializer
 def get_queryset(self):
 return Products.objects.all()

 def get(self, request, format=None):
    snippets = Products.objects.all()
    serializer_class = ProductSerializer(snippets, many=True)
    return Response(serializer_class.data)

 def post(self, request, format=None):
    serializer = ProductSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

`
Now I need to create events with the help of Django-Scheduler while creating the Product when a new request comes via Django Rest Framework.
Thanks in anticipation, Please let me know if I am missing on any part.


text:
Q: Select Multiple Options from a dropdown list and input selected options to input field I would like to be able to make multiple selection in a dropdown list and have those selected input written onto an input field with HTML, CSS and JS. I am using bootstrap and this is what I got so far, but haven't been able to find out how to select multiple items and have those selection being written into the input field. I tried <select multiple> but doesn't seems to work.
index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nestia Umbrella</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <link rel="stylesheet" href="./app.css">

        <select class="custom-select" id="inputGroupSelect04" aria-label="Example select with button addon" placeholder="Services Rendered">
            <option value="General Cleaning">General Cleaning</option>
            <option value="Change Battery">Change Battery</option>
            <option value="Re-align Spring">Re-align Spring</option>
            <option value="Replace Spring">Replace Spring</option>
            <option value="Replace Battery Cover Screw">Replace Battery Cover Screw</option>
        </select>

A: Please find the multi-select drop-down sample code below. You can use the cdn below.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/bbbootstrap/libraries@main/choices.min.css">

if you are using react you can use with npm
npm install choices.js

with yarn
yarn add choices.js

You can initialize this drop-down using the javascript.
Refer this https://github.com/Choices-js/Choices#readme document to use options for drop-down menu.

$(document).ready(function(){

     var multipleSelectDropdown = new Choices('#inputGroupSelect04', {
        removeItemButton: true
      });

 });

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/bbbootstrap/libraries@main/choices.min.css">

Select the something
<select id="inputGroupSelect04" placeholder="Services Rendered" multiple>
        <option value="General Cleaning">General Cleaning</option>
        <option value="Change Battery">Change Battery</option>
        <option value="Re-align Spring">Re-align Spring</option>
        <option value="Replace Spring">Replace Spring</option>
        <option value="Replace Battery Cover Screw">Replace Battery Cover Screw</option>
    </select>

A: If you want to write selections to a input, you will need a script.
Having bootstrap or not, will not affect this.
You could do something like this:
var select = document.getElementById("inputGroupSelect04");
var input = document.getElementById("input");

select.addEventListener("change", function(event) {
  const selected = document.querySelectorAll('#inputGroupSelect04 option:checked');
  const values = Array.from(selected).map(el => el.value);

  input.value = values.join(', ');
})

I have created an example here:  https://codepen.io/bj-rn-nyborg/pen/WNGNwpV


text:
Q: Do login command with AppleScript Prettty straightforward–Is there a way to do the login command and then enter the login password with do shell script?
For example, I want to login into the account user with the password name. How can I get the script to do login user and then input the password name (without opening a new Terminal window)? Maybe some bash script executable with
do shell script "./mybashscript.sh"

That does the login and inputs the password. I want it to do this invisibly.

A: In case you're referring to automating logging in as a different OSX user, as opposed to running a shell command as another user: I wouldn't know how to do that.
If you're referring to running shell commands or a shell script as another user, that's doable, although it requires administrative credentials - NOT the target user's password, but the password of a user with administrative privileges.
The following solutions simply execute whoami in the context of the target user, which echoes that user's username.

*

*The SECURE way: prompt for administrative credentials:

set targetUser to "user1"
do shell script "sudo -H -s -u " & targetUser & " whoami" with administrator privileges

*

*The INSECURE way: hard-code the administrative credentials:

set targetUser to "user1"
set adminUser to "admin"
set adminPasswd to "adminPassword" # !! NOT RECOMMENDED
do shell script "sudo -H -s -u " & targetUser & " whoami" ¬
  user name adminUser password adminPasswd with administrator privileges

Omit the user name adminUser clause if you want to default to the current user, assuming it is an administrator.
As for the options passed to sudo:

*

*-s causes the command (whoami, in this case) to be executed by a (non-login) shell (an instance of the current user's shell).

*-H ensures that the $HOME environment variable is set to the target user's, which ensures that the target user's shell initialization files are read.


text:
Q: Give a null-homotopy of $2\eta :S^4\to S^3$ in coordinates where $\eta$ is the suspension of the hopf fibration.
When I say "in coordinates" I mean that $2\eta$ comes from choosing an explicit representation of $\eta :S^3\to S^2$, suspending it, composing with an explicit map of order 2 and then describing it's null-homotopy in coordinates as well.

A: You can work this out from the Pontryagin-Thom description.  $\eta$ is given by a figure-8 framed unlink in 3-space, suspending it means embedding $\mathbb{R}^3$ into $\mathbb{R}^4$ in the obvious way.  $-\eta$ is given by a figure-8 unlink with the undercrossing.  A bordism between these $1$-manifolds is given by switching an over-crossing to an under-crossing by moving a little into the 4th dimension so that you can move it past and then going back.  I've just described a framed bordism in $\mathbb{R}^4$ and applying Pontryagin-Thom will give you a homotopy between $\eta$ and $-\eta$.
Turning this into a null-homotopy of $2 \eta$ instead of a homotopy of $\eta$ with $-\eta$ is slightly annoying, but just a matter of whiskering with $\eta$ on both sides.
Translating all this into explicit coordinates is certainly tedious, but should be straightforward.  It's unlikely to me that seeing the calculation in coordinates will be more illuminating than just thinking about the bordism itself.


text:
Q: How can I generate a color keeping a consistency? I need some advice that could help me with the problem that I'm going to explain.
I have a list of lists with some values, these are some examples:
[9798, 15349596, 692, 142, 45568, 0, 1, 1, 1.9821, 3105.3198, 0.1399, 0.02872, 9.2186, 22181.4971, 4, 0, 50, 0, 5, 0, 33255, 161, 172, 0.805, 0.86, 166.275, 4943]
[0, 0, 44, 7, 0, 1, 1, 0, 0.0, 0.0, 0.06800618238021638, 0.010819165378670788, 0.0, 0.0, 15, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 647]

Each number is a feature of an user and, as you can see, there are some 1s and 0s that represent some boolean value. Obviously, the lists have the same length.
Now, I want to generate a color (or colors, like a color-mapping function) from those lists keeping a sort of "consistency" between the colors.
An example of what I mean with consistency: suppose that I have two lists that are pretty the same
[0, 0, 44, 7, 0, 1, 1, 0, 0.0, 0.0, 0.06800618238021638, 0.010819165378670788, 0.0, 0.0, 15, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 647]
[1, 0, 44, 7, 0, 1, 1, 0, 0.0, 0.0, 0.06800618238021638, 0.010819165378670788, 0.0, 0.0, 15, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 647]

as you can see in this example the difference is only the first value. If the algorithm produces the red for the first list, I want the red (or similar) for the second one.
I'm looking for a sort of idea, because I don't have any :(. As note I'm using python, but I'm not looking for the code, just an idea or references to some algorithm.
Thank you in advance :)!

A: Consider a color space along 3 axes (could be RGB, XYZ, La*b*, etc.). For each axis' endpoint define what specific "extreme" values of your feature vectors you want to map there; the unnormalized length of each axis would be the Levenshtein distance between these vectors.
Then to map a feature vector, determine its Levenshtein distance to the endpoints along each axis, normalize it, then use the value on each axis as point in your designated color space.


text:
Q: Difference between orthogonal and orthogonal to each other? I am currently examining the proposition that if the quadratic module $(V, Q)$ is nondegenerate and $V$ is the orthogonal direct sum of two subspaces then the subspaces are nondegenerate and they are orthogonal to the other.
My question is, aren't the two subspaces orthonal by definition of orthogonal direct sum? Or does orthogonal to the other mean something else?


text:
Q: Weird appearance of $$state I would want to get a data from server using http.get with this kind of format.
{"username":"my name is"}

after retrieving the data, I plan to save the value of user in a variable. Using firebug, i go to network tab and check if I get the expected output, and it was correct. But weirdly, it couldn't display the value using this {{}}. and When I checked the value of my variable using angular.element($0).scope() what I get is something like this

//controller
$scope.userDetails={};
$scope.userDetails.userName = MyService.getUserName( );
console.log($scope.userDetails.userName );

 //service
    getUserName: function( ) {
        var response = $q.defer( );

        $http.get( ENV.apiEndpoint + '/getUsername' ).success( function( data ) {
            console.log("success");
            console.log(typeof data);
            console.log( data);
            response.resolve( data[0].user.trim());
        })
        .error(function( data ) {
            console.log("reject");
            console.log(typeof data);
            console.log( data);
            response.reject( data);
        }) ;

        return response.promise;
    }

Why do I get that weird $$state object? and how can I get rid of it and get only the username


text:
Q: Re-index with Python Hi I have a student dataset consisting of their Names, Subjects and Scores.
Each student has 5 subjects to write. However the below table has data missing for some students in terms of their subjects and marks. Please find the table below:
Name    Subject Score
Harry   Math    4
Harry   Science 5
Harry   Social  3
Harry   French  5
Harry   Spanish 4
Steve   Math    5
Steve   Science 3
Steve   Social  5
Steve   French  4
Tom     Math    5
Tom     Science 4
Tom     Social  5

I would like to find Names which have scores for less than 5 subjects and append additional rows, so that all students have their individual scores for all 5 subjects. Expected output is below:
Name    Subject     Score
Harry   Math         4
Harry   Science      5
Harry   Social       3
Harry   French       5
Harry   Spanish      4
Steve   Math         5
Steve   Science      3
Steve   Social       5
Steve   French       4
Steve   Spanish      4

You can see here that Steve, Harry and Tom have scores for all 5 subjects.

A: This seems to be a perfect application of reindex
Given setup:
z=io.StringIO("""Name    Subject Score
Harry   Math    4
Harry   Science 5
Harry   Social  3
Harry   French  5
Harry   Spanish 4
Steve   Math    5
Steve   Science 3
Steve   Social  5
Steve   French  4
Tom     Math    5
Tom     Science 4
Tom     Social  5""")

df=pd.read_table(z,delim_whitespace=True)

Then
new_index = pd.MultiIndex.from_product([df['Name'].unique(), df['Subject'].unique()], names=['Name', 'Subject'])
df.set_index(['Name', 'Subject']).reindex(new_index)

                        Score
Name    Subject
Harry   Math            4.0
        Science         5.0
        Social          3.0
        French          5.0
        Spanish         4.0
Steve   Math            5.0
        Science         3.0
        Social          5.0
        French          4.0
        Spanish         NaN
Tom     Math            5.0
        Science         4.0
        Social          5.0
        French          NaN
        Spanish         NaN


text:
Q: Why can I not import statsmodels api? In a ARIMA case I want to import statsmodel.api as am to use it for SARIMAX. But when I want to import it I get some Error that PyCharm can not import name 'factorial' from 'scipy.misc' (lib\site-packages\scipy\misc__init__.py). At the moment I'm trying to update scipy via commandline under Windows (pip install --upgrade scipy) but this gives me TimeOut Errors.
Does someone know where the problem is? I read something about updates/ version errors, but didnt find a solution that worked out for me.
Thank you in advance! :)
import statsmodels.api as sm

mod = sm.tsa.statespace.SARIMAX(data.MemoryUsedPercent, trend='n', order=(0,1,0), seasonal_order=(1,1,1,144))
results = mod.fit()
print(results.summary())

Traceback (most recent call last):
  File "C:/Users/kunkelk/PycharmProjects/PE_II/Test_II.py", line 105, in
    import statsmodels.api as sm
  File "C:\Users\kunkelk\PycharmProjects\PE_II\venv\lib\site-packages\statsmodels\api.py", line 16, in
    from .discrete.discrete_model import (Poisson, Logit, Probit,
  File "C:\Users\kunkelk\PycharmProjects\PE_II\venv\lib\site-packages\statsmodels\discrete\discrete_model.py", line 45, in
    from statsmodels.distributions import genpoisson_p
  File "C:\Users\kunkelk\PycharmProjects\PE_II\venv\lib\site-packages\statsmodels\distributions__init__.py", line 2, in
    from .edgeworth import ExpandedNormal
  File "C:\Users\kunkelk\PycharmProjects\PE_II\venv\lib\site-packages\statsmodels\distributions\edgeworth.py", line 7, in
    from scipy.misc import factorial
ImportError: cannot import name 'factorial' from 'scipy.misc' (C:\Users\kunkelk\PycharmProjects\PE_II\venv\lib\site-packages\scipy\misc__init__.py)


text:
Q: SpringBoot Controller Not Being Mapped I am trying to create a basic SpringBoot web-app with one endpoint called /movies. I followed some of the docs on the site and also a basic Youtube tutorial on it.
The app returns 'it works' when I run curl localhost:8080 from the command line but when I attempt to access my endpoint /movies I see that 'The requested URL /movies was not found on this server.'
Main Class:
@SpringBootApplication
public class Main
{
    public static void main( String[] args )
    {
       SpringApplication.run(Main.class, args);
    }
}

Controller Class:
@RestController
@RequestMapping("/movies")
public class MovieController {

    @Autowired
    private MovieService movie_service;

    @RequestMapping(method = RequestMethod.GET)
    public Collection<Movie> getAllMovies(){
        return movie_service.getAllMovies();
    }
}

POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com</groupId>
  <artifactId>MovieDCU</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I have tried almost every suggested answer on this site for similar questions posted but nothing seems to fix it. One unusual thing is that I don't see the mappings when I run the app, in the command line:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.1.RELEASE)

2019-11-23 13:27:19.243  INFO 30238 --- [           main] com.Main                                 : Starting Main on Conors-MB with PID 30238 (/Users/eclipse-workspace/Movie/target/classes started by x in /Users/eclipse-workspace/Movie)
2019-11-23 13:27:19.249  INFO 30238 --- [           main] com.Main                                 : No active profile set, falling back to default profiles: default
2019-11-23 13:27:20.011  INFO 30238 --- [           main] com.Main                                 : Started Main in 1.209 seconds (JVM running for 1.611)

Any help is appreciated.

A: Try to change your class like this.
Just have the GetMapping at the method level. Also notice I have renamed your service to the standard Java naming convention (camelCase).
@RestController
public class MovieController {

    @Autowired
    private MovieService movieService;

    @GetMapping("/movies")
    public Collection<Movie> getAllMovies(){
        return movieService.getAllMovies();
    }
}

A: if you are on Linux machine, then you could have default apache server started.


text:
Q: Running command via ssh also runs .bashrc? In my reading of the bash manpage, .bashrc should only be executed when the shell is run interactively.  The manpage defines interactive as:

An  interactive  shell  is one started without non-option arguments
  and without the -c option whose standard input and error are both
  connected to  terminals  (as determined by isatty(3)), or one started
  with the -i option.  PS1 is set and $- includes i if bash is
  interactive,  allowing a shell script or a startup file to test this
  state.

Yet, executing a command with ssh also causes .bashrc to be run, contrary to what I would expect, given that the command is not run interactively.  So, this behavior seems like a bug, but it also seems pervasive on all the versions of Red Hat and bash that I've tried.  Can someone explain why this behavior is correct?
One additional point:  even though .bashrc is run, $- and $PS are set as if the shell is non-interactive (as I would expect).
$ grep USER /etc/passwd
USER:x:UID:GID:UNAME:/home/USER:/bin/bash

$ cat ~/.bashrc
echo bashrc:$-,$PS1

$ bash -c 'echo $-'
hBc

$ ssh localhost 'echo $-' </dev/null 2>/dev/null
USER@localhost's password:
bashrc:hBc,
hBc

$ ssh localhost 'ps -ef | grep $$' </dev/null 2>/dev/null
USER@localhost's password:
bashrc:hBc,
USER 28296 28295 0 10:04 ? 00:00:00 bash -c ps -ef | grep $$
USER 28297 28296 0 10:04 ? 00:00:00 ps -ef
USER 28298 28296 0 10:04 ? 00:00:00 grep 28296

I am currently working around this by testing [[ $- = *i* ]] in .bashrc, but it seems as if I shouldn't have to do that.
One example server, containing no other files in my home directory than .bashrc (and .ssh) has this configuration:
$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.7 (Tikanga)

$ bash --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.

Versions of bash that I've tried this on:  3.00.15, 3.1.17, 3.2.25, 4.1.2 (the latter on Red Hat 6.3).

A: From the Bash manual:

Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the remote shell daemon, usually rshd, or the secure shell daemon sshd. If Bash determines it is being run in this fashion, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified.

The workaround in the default Debian bashrc skeleton is to put the following at the top of .bashrc:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return


text:
Q: jmx command line tool that does not require JDK I am trying to find a JMX cli client that can be used instead of jconsole.
I have tried jmxterm and really liked it.
However, is there a JMX command line tool out there similar to jmxterm that does not require JDK for its usage ?


text:
Q: Graph plotting libraries for Java What are the best graph plotting libraries for Java? (preferably also supporting 3D graphs)

A: JFreeChart seems to come highly recommended (or at least is often used).

A: So i needed something like that a few years ago. I used Jgraphplot
http://jmathtools.berlios.de/doku.php?id=faq_beginners
the project itsself seems to be fallen asleep but i don't think there was to much change to maths sience since 2003 :-)
So if i google for tools like that there is no newer tool at all. It covers 3d Graphs as well.

A: My open source project, DataDisplay, does just what you want.
https://sourceforge.net/p/msu-doe-dd/


text:
Q: Problems creating a xml parser for windows phone in C# I'm not an expert programmer, mostly self-trained. Currently my Project is to create a XML parser for an application im writing in C# for Windows phone.
To learn that, I'm trying the demo posted here: http://www.developer.nokia.com/Community/Wiki/Parse_Local_XML_file_in_Windows_Phone
all is good until I get to the following part:
     private void btnparse_Click(object sender, RoutedEventArgs e)
    {
             this._parser = XMLParser.Instance;
             StreamResourceInfo strm = Application.GetResourceStream(new Uri("/LocalXmlParsing;component/States.xml",UriKind.Relative));
     //needs to be done only once
             StreamReader reader = new StreamReader(strm.Stream);
             string data = reader.ReadToEnd();
             _parser.DataToParse = data;
             _parser.ParseStateData();
             lstStates.ItemsSource = _parser.StateCollection;
}

I get the Error: "Error 2 The name '_parser' does not exist in the current context"
I will take any advice you guys can give me.

A: this is always a reference to the current object (whose member functions are executing against). So this._parser is called a "field" or "member variable". These fields have to be defined in the class definition. You're not showing us the full class definition, but it certainly doesn't exist. And that's what the compiler is complaining about.
It should look something like this:
class Foo {
    private XMLParser _parser;

    // your functions, like btnparse_Click
}

Or, if you're only going to use the parser in the context of that one function, just make it a local variable:
private void btnparse_Click(object sender, RoutedEventArgs e)
{
    XMLParser parser = XMLParser.Instance;
    ...

You can also use an implicitly typed local variable:
private void btnparse_Click(object sender, RoutedEventArgs e)
{
    var parser = XMLParser.Instance;
    ...

A: check if the _parser is defined as class variable Or if it is a variable in the parent class (in case your class has inherited a base class). I have not looked at the entire code but that is what the error suggests.


text:
Q: When I hit play Unity removes Game Objects from scripts I'm making an android game, but the game objects are dropped from the scripts when I hit play. I can't find a way to fix it. I uninstalled and reinstalled Unity, I reset my whole computer, but every time I hit play all game objects are dropped from the script. I even made a new project with a game object that I attached to a script and it still gets removed when I hit play.
This is before
This is after

A: It's not getting removed. It is because you have a rigidbody2d component and it is reacting to gravity. If you don't want it to be affected by gravity but want to move it yourself then change the body type to kinematic. If you gravity but don't want it to fall through then make sure you have something at the bottom that can collide with it.


text:
Q: Why does GitHub Desktop auto-resolve conflicts? I am not a programmer, but a game artist. I have limited knowledge on Git and Git LFS so this might be a bad question.
When doing a merge, GitHub Desktop will over say it has s=resolved a conflict for me, instead of letting me choose which version to use. This has in fact become such a problem with many programmers I work with, that we do all of our merges in Sourcetree.
Why would GitHub Desktop do this? It's incredibly annoying. Can I disable it?


text:
Q: AWS S3 not returning specified number of records I'm reading the file from S3 bucket by specifying the range. But it is not giving me a specified length of data and always giving me lesser data. It might be due to S3 ignoring/skipping a few of the characters while reading which I'm not able to understand why.
  val stringBuilder = new StringBuilder

  val s3Client = AmazonS3ClientBuilder.standard.withRegion("us-east-1").withCredentials(new ProfileCredentialsProvider).build
  val rangeObjectRequest = new GetObjectRequest("test_bucket", "test_key")
    .withRange(0, 25738)

  val s3object = s3Client.getObject(rangeObjectRequest)

  System.out.println(s3object.getObjectMetadata.getContentType)
  System.out.println("content length: " + s3object.getObjectMetadata.getContentLength)

  val reader = new BufferedReader(new InputStreamReader(s3object.getObjectContent))
  var line = ""

  while ({line = reader.readLine; line != null}) {
    System.out.println(line + "  \nLength: " + line.length)
    stringBuilder.append(line).append("\n")
  }

**Output:
binary/octet-stream
content length: 25739
< 3/4 of line read from the file printed here.>
Length: 25341**

How can I read the specified number of bytes from the file? If I read the file without specifying the range, the entire line is printed without any issue.


text:
Q: Python | Load list data into a class Is there a way to pass a List variables to class. I am trying below which doesn't seems to be the right way.
class data():
    def __init__(self, fname, lname, email):
        self.fname = fname
        self.lname= lname
        self.email = email
data_1 = data('Steve','Harvy','steve.harvy@gmail.com')
print(data_1.fname)

This prints Steve
However if I try below, it doesn't work.
class data():
    def __init__(self, fname, lname, email):
        self.fname = fname
        self.lname= lname
        self.email = email
list = ['Steve','Harvy','steve.harvy@gmail.com']
data_1 = device(list)
print(data_1.fname)

A: you have to unpack the list while passing into the class object, try the below code.
class data():
    def __init__(self, fname, lname, email):
        self.fname = fname
        self.lname= lname
        self.email = email

my_list = ['Steve','Harvy','steve.harvy@gmail.com']
#unpack the list using *
data_1 = data(*my_list)
print(data_1.fname)

out[] : Steve

#update : read from a txt file list like values
with open ("file.txt","r") as f:
    lines = f.readlines()

for line in lines:
    mylist = eval(line)
    data_1 = data(*mylist)
    print(data_1.fname)


text:
Q: Fix style of DefaultStyledDocument I am wondering if it is possible to fix the style of StyledDocument in java. According to my observation, the style will change depending on style of previous position.
So I can key in the content with my defined style without being affected by the style of previous position.
Many thanks for the response!


text:
Q: Drupal view - new filter criteria resetting from dropdown to autocomplete I've created a new filter criteria within a view but want it to show as a drop-down not autocomplete.
I click on settings (next to the name of the new criteria) select Drop down then click Apply (all displays) yet on the preview it shows as an autocomplete filter and on re-clicking the settings of the filter it shows as autocomplete!!?
It seems the filters criteria is resetting to autocomplete from dropdown.
Could this be due to the field I created?

A: Tried again this morning (problem was yesterday) and seemed to fix itself?
I did initially tick "Show hierarchy in dropdwon" on the extra settings for fiter criterion. Then deselected it later. Not sure if that impacted the proceedings or not.


text:
Q: How to apply multiple template definitions where each of them is changing the same XML structure In this code example I have 2 challenges one is to set B1 node after B node and before node C, D and E and the second challenge is to Add the second KEY node to the /ROOT/E/OTHER/DEAL/KEYS structure.
This XML sample:
        <ROOT>
          some A text
          some B text
          <C>some C text</C>
          <D>some D text</D>
          <E>
            <OTHER>
              <DEAL>
                <KEYS>
                  <KEY>
                    <KeyIdentifierType>KeyIdentifierTypeA</KeyIdentifierType>
                    <KeyValue>123456|1</KeyValue>
                  </KEY>
                </KEYS>
              </DEAL>
            </OTHER>
          </E>
        </ROOT>

after the transformation:
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <xsl:strip-space elements="*"/>
        <xsl:output method="xml" indent="yes"/>

        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates  select="@*|node()"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="ROOT" name="add-B1">
            <xsl:variable name="elements-after" select="C|D|E"/>
            <xsl:copy>
                <xsl:copy-of select="* except $elements-after"/>
                <B1>some B1 text</B1>
                <xsl:copy-of select="$elements-after"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="ROOT/E/OTHER/DEAL/KEYS" name="add-KEYS">
            <xsl:param name="KeyIdentifierTypeB">654321|1</xsl:param>
            <xsl:copy>
                <xsl:copy-of select="*"/>
                <KEY>
                    <KeyIdentifierType>KeyIdentifierTypeB</KeyIdentifierType>
                    <KeyValue>
                        <xsl:value-of select="$KeyIdentifierTypeB"/>
                    </KeyValue>
                </KEY>
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>

become:
        <?xml version="1.0" encoding="UTF-8"?>
        <ROOT>
            some A text
            some B text
            <B1 xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">some B1 text</B1>
            <C>some C text</C>
            <D>some D text</D>
            <E>
                <OTHER>
                    <DEAL>
                        <KEYS>
                            <KEY>
                                <KeyIdentifierType>KeyIdentifierTypeA</KeyIdentifierType>
                                <KeyValue>123456|1</KeyValue>
                            </KEY>
                        </KEYS>
                    </DEAL>
                </OTHER>
            </E>
        </ROOT>

why the second template definition has been completely ignored?
The first code college has been resolved B1 node is set after B node and before node C, D and E or in the other words B1 node is set and nodes that must be places after it are: C, D and E.
The second template match="ROOT/E/OTHER/DEAL/KEYS" that should satisfy the second challenge part: to Add the second KEY node to the /ROOT/E/OTHER/DEAL/KEYS structure, has been ignored completely.
In addition to this fact, if you comment the first template match over the ROOT node, the second template match="ROOT/E/OTHER/DEAL/KEYS" will work correctly, it will actually add the additional key, but I don't know why the first template match always overrides the second one. I try the xsl:template match="ROOT/E/OTHER/DEAL/KEYS... and the xsl:for-each select=... and xsl:call-template name="add-KEYS" but nothing helped me out.
I actually understand, that apply-templates, match nodes templates with higher structure with highest priority. Changing template place in the XSLT file will not have any impact, it will not read it in the exact line sequence, instead it will process it by matching priority.
"apply-templates" for each matching template will made a change on the XML structure, implicitly it will made the "for-each" for us, but I don't how to "advice" the second template that the structure has been changed, and why I should do it, because the second template match is looking for a different XPath location, that btw has never been touched from the first template. Should I apply the template sequencing in my case?... and what is the best practice how to do it?
Expected result:
        <?xml version="1.0" encoding="UTF-8"?>
        <ROOT>
            some A text
            some B text
            <B1>some B1 text</B1>
            <C>some C text</C>
            <D>some D text</D>
            <E>
                <OTHER>
                    <DEAL>
                        <KEYS>
                            <KEY>
                                <KeyIdentifierType>KeyIdentifierTypeA</KeyIdentifierType>
                                <KeyValue>123456|1</KeyValue>
                            </KEY>
                            <KEY>
                                <KeyIdentifierType>KeyIdentifierTypeB</KeyIdentifierType>
                                <KeyValue>654321|1</KeyValue>
                            </KEY>
                        </KEYS>
                    </DEAL>
                </OTHER>
            </E>
        </ROOT>

A:
The second template match="ROOT/E/OTHER/DEAL/KEYS" that should
  satisfy the second challenge part: to Add the second KEY node to the
  /ROOT/E/OTHER/DEAL/KEYS structure, has been ignored completely.

The problem is that in the template matching ROOT there isn't any xsl:apply-templates. A template only gets selected for execution in result of an xsl:apply-templates instruction. In your code there isn't any xsl:apply-templates, therefore the XSLT processor doesn't apply templates any more and finishes execution.
It would be different if you replaced xsl:copy-of with xsl:apply-templates.
Here is how to do this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <xsl:copy>
    <xsl:apply-templates select="@*|B/preceding-sibling::node()"/>
    <xsl:apply-templates select="B"/>
    <B1>some B1 text</B1>
    <xsl:apply-templates select="B/following-sibling::node()"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="KEY">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
   <KEY>
    <KeyIdentifierType>KeyIdentifierTypeB</KeyIdentifierType>
    <KeyValue>
     <xsl:value-of select="'654321|1'"/>
    </KeyValue>
   </KEY>
   </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:
<ROOT>
    some A text
    some B text
    <C>some C text</C>
    <D>some D text</D>
    <E>
        <OTHER>
            <DEAL>
                <KEYS>
                    <KEY>
                        <KeyIdentifierType>KeyIdentifierTypeA</KeyIdentifierType>
                        <KeyValue>123456|1</KeyValue>
                    </KEY>
                </KEYS>
            </DEAL>
        </OTHER>
    </E>
</ROOT>

the wanted, correct result is produced:
<ROOT>
   some A text
   some B text
   <B1>some B1 text</B1>
   <C>some C text</C>
   <D>some D text</D>
   <E>
      <OTHER>
         <DEAL>
            <KEYS>
               <KEY>
                  <KeyIdentifierType>KeyIdentifierTypeA</KeyIdentifierType>
                  <KeyValue>123456|1</KeyValue>
                  <KEY>
                     <KeyIdentifierType>KeyIdentifierTypeB</KeyIdentifierType>
                     <KeyValue>654321|1</KeyValue>
                  </KEY>
               </KEY>
            </KEYS>
         </DEAL>
      </OTHER>
   </E>
</ROOT>


text:
Q: Consulta para tener solo los nombres de registros Necesito una consulta que me muestre de una tabla nombre en la cual están juntos apellidos y nombres separados por una coma ejemplo :
Martinez Nutero, Juan Alberto
y necesito que sólo me muestre el valor a partir de la coma. Probé con esta consulta pero no me funciona. ¿Alguien me puede ayudar por favor?
 select right(nombre,select locate(',',nombre) from asd_personas) from asd_personas

A: Para lo que necesitas puede servirte SUBSTRING_INDEX, prueba asi:
SELECT SUBSTRING_INDEX(nombre, ',', 1) as nombre,SUBSTRING_INDEX(nombre, ',', -1) as apellido FROM asd_personas


text:
Q: Regex match string by one delimiter, and then another im struggling to find an regex which will do what I need.
I just want to first split the following by each pipe, and then split that match be each colon.

partx_registration:DL66 LNH|test:value|test2:helloworld

So I would be left with 3 groups, and 2 values within them 2 groups.
Currently got the following:
/([^|]+)/g

However not too sure on how I would go about doing the second check.
Edit:
Using PHP, and I would expect:
(2) [Array(2), Array(2)]
   0:
   (2) ["partx_registration", "DL66 LNH"]
   1:
   (2) ["test", "value"]

Edit 2:
The following code:
preg_match_all("~([^|:]+):([^|:]+)~", "partx_registration:DL66 LNH|test:value|test2:helloworld", $post_array);
echo "<pre>";
var_dump($post_array);
echo "</pre>";
die();

Outputs:
array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(27) "partx_registration:DL66 LNH"
    [1]=>
    string(10) "test:value"
    [2]=>
    string(16) "test2:helloworld"
  }
  [1]=>
  array(3) {
    [0]=>
    string(18) "partx_registration"
    [1]=>
    string(4) "test"
    [2]=>
    string(5) "test2"
  }
  [2]=>
  array(3) {
    [0]=>
    string(8) "DL66 LNH"
    [1]=>
    string(5) "value"
    [2]=>
    string(10) "helloworld"
  }
}

This isn't the case on regex101 :S

A: You may use
'~([^|:]+):([^|:]+)~'

See the regex demo
Details

*

*([^|:]+) - Group 1: any one or more chars other than | and :

*: - a colon

*([^|:]+) - Group 2: any one or more chars other than | and :
PHP demo:
$str = 'partx_registration:DL66 LNH|test:value|test2:helloworld';
preg_match_all('/([^|:]+):([^|:]+)/', $str, $matches, PREG_SET_ORDER, 0);
print_r($matches);

Results:
Array
(
    [0] => Array
        (
            [0] => partx_registration:DL66 LNH
            [1] => partx_registration
            [2] => DL66 LNH
        )

    [1] => Array
        (
            [0] => test:value
            [1] => test
            [2] => value
        )

    [2] => Array
        (
            [0] => test2:helloworld
            [1] => test2
            [2] => helloworld
        )
)

A: You don't need regex for such a simple task. Split the initial string by | then each piece by : and you're almost there. All you need is explode() and foreach. And the resulting code is more clear than using regex.
$input = 'partx_registration:DL66 LNH|test:value|test2:helloworld';

$output = array();
foreach (explode('|', $input) as $piece) {
    $output[] = explode(':', $piece);
}
print_r($output);

The output is:
Array
(
    [0] => Array
        (
            [0] => partx_registration
            [1] => DL66 LNH
        )

    [1] => Array
        (
            [0] => test
            [1] => value
        )

    [2] => Array
        (
            [0] => test2
            [1] => helloworld
        )
)


text:
Q: How can I configure ASP.NET MVC routing in C#? Got a question about routing in ASP.NET MVC.
I want to have nice URLs in my app and that's why I use routing like
context.MapRoute(
     name: "ManageProducts_Home",
     url: "Eshop/ManageProducts/{eshopId}",
     defaults: new { controller = "ManageProducts", action = "Home", AreaName = "Eshop" }
);

which gives me nice urls like
https://localhost:44381/Eshop/ManageProducts/22

which is great!
Then I have another route:
context.MapRoute(
     name: "ManageProducts_AddProduct",
     url: "Eshop/ManageProducts/AddProduct/{eshopId}/{topCategoryId}",
     defaults: new { controller = "ManageProducts", action = "AddProduct", AreaName =  "Eshop" }
);

Which produces this URL:
https://localhost:44381/Eshop/ManageProducts/AddProduct/22/1

Ok, so far so good.
But on the second page (AddProduct), I need to refresh some partial view via AJAX which I call like this
$("._SelectCategory").load("/Eshop/ManageProducts/_SelectCategory", { categoryId: categoryId });

There is of course an action _SelectCategory in the controller which takes a parameter categoryId.
The problem is, this call is caught by the first routing and fails with exception missing eshopId in action Home, meaning this call doesn't go to the default routing I have there
context.MapRoute(
     "Eshop_default",
     "Eshop/{controller}/{action}/{id}",
     new { action = "Index", id = UrlParameter.Optional }
);

I need some advice how to configure the routing in view AddProduct works the ajax call.
Thank you

A: use a Web API Empty Controller and give your routes there that is more efficient
eg:
in ManageProducts controller
[HttpGet]
[Route("api/Eshop/ManageProducts/{eshopId}")]

In your Startup.cs configure meathod
add this:   app.UseMvc();


text:
Q: Arrange & Display Parts of Grids in Mathematica In order to find quickly the location of my data, I display a table with my variables names as well as informations about each.
Since I have a lot of columns (variable) I copy and paste blocks of it in a cell to have them all on 1 screen.
I would like to code this, such that I would input several range of Rows to be extracted and efficiently displayed some how on a Grid that would fit an area of the screen ? I have failed yet to display 2 grid nicely together.
In case I did not express my problem properly above, here is a simple example:
How can I move the blue part to the side of the pink one if the output of laList is what we have to deal with ?
co1    = Range[6];
co2    = Range[11, 16];
co3    = {"A", "B", "C", "D", "E", "F"};

laList = Join[{co1}, {co2}, {co3}] // Transpose;

laListGraph = Grid[laList,
Dividers -> All,
Alignment -> {Left, Center},
ItemSize -> Automatic,
ItemStyle -> Directive[FontSize -> 14, Black, Italic, Bold],
Spacings -> {2, 1},
 Background -> {None, None, {
     {{1, 3}, {1, 3}} -> LightRed,
     {{4, 6}, {1, 3}} -> LightBlue
   } } ]

A: EDIT:
On second thoughts, what I had earlier is not what you wanted... you want it displayed as columns, but with the second half of the rows split and displayed beside the first. The following code should do that. Let me know if this is what you had in mind...
(Grid[#1, Dividers -> All, Alignment -> {Left, Center},
     ItemSize -> Automatic,
     ItemStyle -> Directive[FontSize -> 14, Black, Italic, Bold],
     Spacings -> {2, 1},
     Background -> {None,
       None, {{1, 3}, {1, 3}} -> #2}] &) @@@ {{laList[[;; 3, All]],
    LightRed}, {laList[[4 ;;, All]], LightBlue}} // Row

A: As I understood your question, the coloring was there just to show us which portion you want to "move up". So:
showG[l_List] :=
  Grid[Join[
    l[[ ;; IntegerPart[Length@l/2]]],
    l[[IntegerPart[Length@l/2] + 1 ;;]]
    , 2], Frame -> All];

showG[laList]

Edit
Or more to @Mr.'s taste:
showG[l_List] :=
  Grid[Join[l[[ ;; #]], l[[# + 1 ;;]], 2], Frame -> All] &@ Floor[Length@l/2];

A: Here is how I would do it.  Starting with your laList as defined in the question:
laList2 = ArrayFlatten @ {Partition[laList, 3]};

Grid[laList2,
Dividers -> All,
Alignment -> {Left, Center},
ItemSize -> Automatic,
ItemStyle -> Directive[FontSize -> 14, Black, Italic, Bold],
Spacings -> {2, 1},
 Background -> {None, None, {
     {{1, 3}, {1, 3}} -> LightRed,
     {{1, 3}, {4, 6}} -> LightBlue
   } }
]

Please notice:

*

*the value 3 within Partition will need to be adjusted according to your list.

*the region specification for the LightBlue area was reversed.

A variation of yoda's code I like is:
subgrid= Grid[#1,
         Dividers  -> All,
         Alignment -> {Left, Center},
         ItemSize  -> Automatic,
         ItemStyle -> Directive[FontSize -> 14, Black, Italic, Bold],
         Spacings  -> {2, 1},
         Background-> #2] &;

MapThread[subgrid, {Partition[laList, 3], {LightRed, LightBlue}}] //Row

Also, with this method you can partition a list that does not divide evenly:
MapThread[subgrid, {
  Partition[laList, 4, 4, 1, {}],
  {LightRed, LightBlue}
}] //Row


text:
Q: SQLCMD, when called from Powershell, returns ExitCode == 1, even if successful I have a Powershell script that calls sqlcmd to run a sql script that backs up a database:
function RunSqlScriptWithErrorMessage
{
    param([string]$sqlServer, [string]$sqlUserName, [string]$sqlPassword, [string]$scriptName, [string]$errorMessage)

    $commandName = "sqlcmd"
    $startInfo = New-Object Diagnostics.ProcessStartInfo($commandName)
    $startInfo.UseShellExecute = $false
    $startInfo.Arguments = "-S $sqlServer -U $sqlUserName -P $sqlPassword -i `"${sqlScriptName}`""
    $process = [Diagnostics.Process]::Start($startInfo)
    $process.WaitForExit()
    $exitCode = $process.ExitCode
    if($exitCode -ne 0 ) { throw $errorMessage}
}

The strange thing is that process.ExitCode == 1 even though the back up is successful. Any ideas why this would be - shouldn't the exitcode be 0 if successful?
Thanks!

A: Sorry - it was an error.


text:
Q: locate cannot search /dev?
As the picture shows, I can use 'find' to search for a JPEG file in '/dev'. However, trying to do the same thing with 'locate' fails. It seems that 'locate' can search anywhere except '/dev' Can anyone tell me why?

A: /dev is for device files, not user files. As such, updatedb is told to not index anything in there, since users would not be storing files there.


text:
Q: exhaustive search matlab 4 variables I used genetic algorithm to find the minimum of a 4 variable(x1,x2,x3,x4) objective function(output result1). Now, to evaluate the results i need to run an exhaustive search in the following manner:I will keep x1,x2 constant and x3 x4 will take n values between their upper and lower bounds with a fixed step.I will need to store the results to different vectors to see the combination of x1,x2,x3,x4 that minimizes result1(the output of the objective function). X1,x2,x3,x4 have also linear and non linear contraints which are implemented in the genetic algorithm. Any ideas are welcome.

A: It seems like you are stuck on a basic level.
Try looping over all values of x3 and x4 that you want to check and evaluate the value in each point. Keep track of he best value and the location where you found it, and update this each time you find a better one.
If this works, you can start thinking about efficiency (vectorization, gradient search).


text:
Q: "unterminated address regex" using variable in sed I'm trying to use a variable in a sed append and hitting an issue.
The following command works as expected:
sed -i "\:#file = /mnt/var/log/hadoop-yarn/containers/application_1495965866386_0001/container_1495965866386_0001_01_000002/stderr:a file = /path/to/other/file" /etc/conf/service.conf

However if I replace the pattern with a variable I'm hitting an error:
$ echo $item
#file = /mnt/var/log/hadoop-yarn/containers/application_1495965866386_0001/container_1495965866386_0001_01_000002/stdout

$ sed -i "\:$item:a file = /path/to/other/file" /etc/conf/service.conf
sed: -e expression #1, char 122: unterminated address regex

EDIT for more info: So the 'item' variable is being populated from an array. That array is created from a readarray and grep:
$readarray LINES < <(grep "#file = /mnt/var/" /etc/conf/service.conf)
$item=${LINES[1]}

$echo $item
#file = /mnt/var/log/hadoop-yarn/containers/application_1495965866386_0001/container_1495965866386_0001_01_000002/stdout

However I've found if i populate 'item' manually it then works e.g:
$item="#file = /mnt/var/log/hadoop-yarn/containers/application_1495965866386_0001/container_1495965866386_0001_01_000002/stdout"
$sed -i "\:$item:a file = /path/to/other/file" /etc/conf/service.conf
$

So something strange seems to be happening with the readarray/grep

A: So the problem here turned out to be newline characters that were being pulled in as part of the grep.
This is why populating $item manually worked - no '\n'
Thanks to Ed Morton for pointing me in the right direction. While
echo "$item" | cat -v

did not show anything I added '-t' to the readarray command to trim newline characters:
$readarray -t LINES < <(grep "#file = /mnt/var/" /etc/conf/service.conf)

After that things worked as expected.


text:
Q: Multi-level meta-anlaysis I'm conducting a meta-analysis in which some of studies reported multiple effect size as they examined the outcome on multiple groups of glucose-lowering drugs. So, a three-level meta-analysis was applied using study_id and effect_id to define the model.
Code used:
rma.mv(logOR, Vi, random = list(~ 1 | effect_id, ~ 1 | study_id),
       tdist= TRUE, data = Gender, method = 'REML')

I have three questions:
A- Is it suitable to use only study_id in the model in such case?
 rma.mv(logOR, Vi, random = ~ 1 | study_id, tdist= TRUE, data = Gender, method = 'REML')

B- The heterogeneity was calculated using the following code:
 W <- diag(1/Gender$Vi)

 X <- model.matrix(full.model)

 P <- W - W %*% X %*% solve(t(X) %*% W %*% X) %*% t(X) %*% W

 100 * sum(full.model$sigma2) / (sum(full.model$sigma2) +
     (full.model$k - full.model$p) / sum(diag(P)))

 100 * full.model$sigma2 / (sum(full.model$sigma2) +
    (full.model$k - full.model$p) / sum(diag(P)))

[1] 79.15468 20.80714

The result showed that within-study heterogeneity was greater than between-study heterogeneity. How this can be interpreted and does it need any additional consideration in the analysis?
C- For testing the publication bias, it was firstly visualized using a funnel plot and I followed the recommendations of extending the tests which are usually used for testing the asymmetry in the funnel plot as Egger test to be used for rma.mv model by including Vi, Se, or sample size as a moderator in the model. since the outcome here is binary and presented as logOR, using SE to test for funnel asymmetry is not recommended because of the mathematical linkage between SE of logOR and the size of logOR. Which measure of moderator is the best to be used in this case? Is it more suitable to use sample size for testing funnel asymmetry of binary outcome?
I'm aware of Harbord and Peter test for binary outcome, but could not find a way to apply either one in rma.mv model.
I've used the sample size as moderator and the result showed significant value. How the sensitivity of the result can be tested since trim and  fill method could not be applied for rma.mv model?


text:
Q: webpy with mod_wsgi on apache2 - weird pymongo bson error I'm running webpy with apache2. This is a really weird error that has got me flummoxed. Have never seen such an error before and I'm wondering what might be the cause.
The error is in the bson pymongo module.
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52] mod_wsgi (pid=27117): Target WSGI script '/var/www/webpy-app/borg/src/app.py' cannot be loaded
as Python module.
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52] mod_wsgi (pid=27117): Exception occurred processing WSGI script '/var/www/webpy-app/borg/src/ap
p.py'.
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52] Traceback (most recent call last):
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/var/www/webpy-app/borg/src/app.py", line 1, in <module>
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]     import web,json,csv,pymongo,pdb,sys
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/opt/python2.7/lib/python2.7/site-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/pymongo
/__init__.py", line 61, in <module>
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/opt/python2.7/lib/python2.7/site-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/pymongo
/connection.py", line 39, in <module>
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/opt/python2.7/lib/python2.7/site-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/pymongo
/mongo_client.py", line 44, in <module>
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/opt/python2.7/lib/python2.7/site-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/bson/__
init__.py", line 41, in <module>
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/opt/python2.7/lib/python2.7/site-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/bson/_c
bson.py", line 7, in <module>
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52]   File "/opt/python2.7/lib/python2.7/site-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/bson/_c
bson.py", line 6, in __bootstrap__
[Wed Jan 30 11:40:28 2013] [error] [client 111.93.158.52] AttributeError: PyCapsule_Import "datetime.datetime_CAPI" is not valid

Here's the WSGI config in httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /borg /var/www/webpy-app/borg/src/app.py/
WSGIPythonPath /opt/python2.7/lib/python2.7/site-packages/
Alias /borg/static /var/www/webpy-app/borg/src/static/
AddType text/html .py

<Directory /var/www/webpy-app/>
      Order deny,allow
      Allow from all
</Directory>

Is the error because of a python library incompatibility issue ? Am not sure. Any help will be greatly appreciated.

A: Figured this out by setting WSGIPythonHome to the appropriate location. WSGI was looking at an old Python library.


text:
Q: symfony2 configuring the firewall - weird behaviour at login I am using symfony2 with FOSUserBundle and i am trying to set up correctly my firewall.
I want the major part of my website to not be available to anonymous users. Home page (the $ in the public pattern) and some others should be available according to a pattern.
With my current configuration, after login I am redirected to the home page but still as anonymous. If i directly type a url of a page not allowed to anonymous directly afterwards, I can access it and I am logged (in the profiler).
My configuration:
dev:
    pattern:  ^/(_(profiler|wdt)|css|images|js)/
    security: false
public:
    pattern:        /(login$|register|resetting|public|$)
    anonymous:      true
main:
    pattern:        ^/
    anonymous:      false
    provider:       main
    form_login:
        login_path: fos_user_security_login
        check_path: fos_user_security_check
    logout:
        path:       fos_user_security_logout
        target:     /

What can I do to make it work properly (logged correctly after login).
EDIT:
I understand better what is happening: after login, I am being redirected to the home page=root address. This falls first into the public firewall and that's whay I'm not seen as connected.

A: Done! Solution involves the context property of the firewall which is better described here :
Authenticate multiple symfony2 firewalls with one login form
My configuration now becomes:
firewalls:
dev:
    pattern:  ^/(_(profiler|wdt)|css|images|js)/
    security: false
guest:
    pattern:        /(user/login$|user/register|user/resetting|$)
    anonymous:      true
    context:        main_auth
main:
    pattern:        ^/(?!user/login$)
    anonymous:      false
    provider:       main
    context:        main_auth
    form_login:
        login_path: fos_user_security_login
        check_path: fos_user_security_check
    logout:
        path:       fos_user_security_logout
        target:     /
    remember_me:
        key:      "%secret%"
        lifetime: 86400 # 365 jours en secondes
        path:     /
        domain:   ~ # Prend la valeur par défaut du domaine courant depuis $_SERVER
    oauth:
        remember_me: true
        resource_owners:
            facebook:           "/loginhwi/check-facebook"
            github:             "/loginhwi/check-github"
            google:             "/loginhwi/check-google"
            twitter:            "/loginhwi/check-twitter"
            linkedin:           "/loginhwi/check-linkedin"
            flickr:             "/loginhwi/check-flickr"
        login_path:        fos_user_security_login
        check_path:        fos_user_security_check
        failure_path:      fos_user_security_login
        success_handler:  foodmeup_user.handler_auth
        oauth_user_provider:
            service: fosubuser.provider

A: Well you always can hardcode the path that you're redirected after login (in your security.yml file). You can read more here
security:
    firewalls:
        main:
            form_login:
                default_target_path: default_security_target


text:
Q: How to use route for html file already served as static I use passport.js to authenticate user after he enters login page. To keep user logged in when he returns to home page i'm going to use something like:
app.use(express.static(__dirname + '/public'));

app.get('/', function(req,res){
   if(req.user){
   // connect to database ....
} else{
    res.sendFile(__dirname +'/index.html');
   }
});

Note that index.html file is inside "public" folder. Recently i realized that having a code like above, node.js doesn't use app.get('/'....) route but it serves index.html directly. So i'm unable to check if req.user exists. Any suggestion?

A: As You might understand express.static handles index.html before Your router.
But You cannot avoid express.static also (otherwise You have to use nginx or write own static file output).
So You've to re-think Your folder structure or have to develop 2 separate apps: api (backend) and frontend (that will request to api for data)
In context of Your question I wrote an example app where I organize assets, html files and app routes:
1) Have such folder structure:

2) and example app.js :
'use strict';

const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

app.set('trust proxy', 1);

// attaching renderer
app.engine('.html', require('ejs').renderFile); // ejs renderer will render .html files as ejs files
app.set('view engine', 'html');          // views has .html extension
app.set('views', __dirname + '/public'); // views live in public folder

// attaching common middlewares
app.use('/assets', express.static('public/assets')); // our static assets will live in public/assets folder
app.use(cookieParser());
app.use(bodyParser());

// implement and attach passport auth somewhere (:
// remove it after passport has been attached:
const authorizeUser = (req, res, next) => {
  req.user = {id: 1, username: 'test'};
  next();
};

app.get('/', authorizeUser, (req, res) => {
  res.render('index', {user: req.user});  // render get index.html from views folder (see above)
});

app.listen(8080, () => {
  console.log('App listening');
});

p.s. download example app from here (don't forget to call npm i inside extracted folder (;  )
p.s. implement passport.js Yourself


text:
Q: asp.net core razor dropdown list with input I'm looking for dropdown list with possibility to input value.
Let's say a have a default list of items, but user can input its own.

I have the following code in controller
 ViewBag.JobTypes = new SelectList(await _mediator.Send(new GetJobTypesQuery()), "Id", "Name");

and view

      <select asp-for="JobTypeId" asp-items="ViewBag.JobTypes"></select>

but in this case user can only select value from dropdown. How to allow custom input? I can't google the answer anywhere.

A: As @Yegor said,you could use autocomplete,here is a working demo:
1.Model:
public class Job
{
    public int Id { get; set; }
    public string Name { get; set; }
}

2.View:
<form asp-action="Search" method="post">

            SearchName
            <input type="text" name="search" id="tags" />

            <input type="submit" value="Search" class="btn btn-primary" />

</form>
@section Scripts{
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

}

3.Controller:
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public IActionResult Test()
    {
        var name = HttpContext.Request.Query["term"].ToString();
        var jobnames = new List<Job>() {
            new Job(){ Id = 1, Name="aaa"},
            new Job(){ Id = 2, Name="abc"},
            new Job(){ Id = 3, Name="acd"},
            new Job(){ Id = 4, Name="ade"},
            new Job(){ Id = 5, Name="bcd"},
            new Job(){ Id = 6, Name="bef"},
        };
        var data = jobnames.Where(j => j.Name.Contains(name)).Select(j => j.Name).ToList();
        return Ok(data);
    }
    [HttpPost]
    public IActionResult Search(string search)
    {
        //do your stuff...
    }
}

Result:

A: For example (Razor pages):
1. Edit.cshtml

    <input asp-for="EmailDomain.To" list="textsearch"
        class="form-control" />
    <datalist id="textsearch">
       @foreach(var item in Model.ListAccounts)
       {
          <option>@item.Text</option>
       }
    </datalist>

2. Edit.cshtml.cs
public SelectList ListAccounts { get; set; } = null!;

ListAccounts = new SelectList(_context.Accounts,
   nameof(Account.Id), nameof(Account.Email), email.To);


text:
Q: How to check if a specific Windows security update is installed? Given that the WannaCry ransomware exploit is going around I wanted to check if my computer has the specific security update that should stop the vulnerability - apparently, MS17-010, assuming I'm understanding the vulnerability and that is indeed the right patch. How would one check that detail?
Microsoft tries to give some detail but it's gibberish to someone who's not well versed with registry keys (I think I touched them once before to dig out a stubborn virus back when XP was still a thing - that's it.) Other searches give some clues regard command line options but they're not all that clear and I don't like running commands I don't understand.

A: You have given the answer yourself.
Open a powershell prompt and type this:
get-hotfix | out-string -stream | select-string   "KB00112233"

This snippet will only read datas, so nothing wrong can happen with it.
You only have to adjust with the KB you want to check.
As specified in the MS Security bulletin MS17-010 (https://technet.microsoft.com/en-us/library/security/ms17-010.aspx), the KB number depends of your OS.
For example, the KB number for Windows 10 v1607 is KB4013429
As mentionned in https://superuser.com/a/1209007/264313, hotfix are regularly replaced by newer one. So a specific fix might be present but the original hotfix be missing.

A: Here is a way to check this for windows 10 (Version 1607):
As noted here https://support.microsoft.com/en-us/help/4013389/title in section "Windows 10 (all editions)", the security update file name for MS17-010 must be Windows10.0-KB4013429-x64.msu, so the kb number for this patch will be KB4013429.

Then in the windows 10 update history check for an entry containing the KB4013429. At my system this patch was successfully installed in the mid of march and is named cumulative update for windows 10 version 1607 for x64 based systems (KB4013429).

A: Checking for a specific KB is BAD, because Updates get replaced with newer updates and the disk cleaner deletes such old replaced/superseded Windows Updates.
You need to check the KB page and look for file version data of the update for each Windows you use and now look if the user has at least this file version or a newer one.
This will always return the correct result. If the update gets replaced and removed the check always shows "you are insecure", but the issue is already fixed.
If you use Windows 10, make sure you have the latest Update rollup installed

In May 2017 those are

*

*for 1511: KB4019473 (OS Build 10586.916)

*for 1607: KB4019472 (OS Build 14393.1198)

*for 1703: KB4016871 (OS Build 15063.296)
The last Update rollup always includes all older updates so here you are safe.
Pro tip: to quickly check your Windows version, just type winver in the Windows 10 search or 'Run' command and hit Enter.

A: For Lansweeper users: Lansweeper released a report that can be used to find machines that do not have the hotfixes installed to mitigate the SMB vulnerability.


text:
Q: Match link patterns in HTML code with a RegEx I'm using a linkify function, which detects link-like patterns by using regex and replaces those with a-tags to reveal a clickable link.
The regex looks like that:
    // http://, https://, ftp://
    var urlPattern = /\b(?![^<]*>|[^<>]*<\/)(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
    /* Some explanations:
    (?!     # Negative lookahead start (will cause match to fail if contents match)
    [^<]*   # Any number of non-'<' characters
    >       # A > character
    |       # Or
    [^<>]*  # Any number of non-'<' and non-'>' characters
    </      # The characters < and /
     )      # End negative lookahead.
    */

and replaces the link like this:
 return textInput.replace(urlPattern, '$&')

The regex works perfectly for in-text links. However, I am using it in HTML-Code also, such as

Link: https://www.link.com

 //linkify not working

Link: https://www.link.com

 //linkify working

where just the secont example is working. I dont't know why the behavior is different and would be very glad to get some help from you. What should my regex look like, to linkify without the break in list elements?

A: If I understood correctly your issue I think that this regex should be ok to detect the links in both the scenarios:
\b(?![^<]*>)(?:https?|ftp):\/\/([a-z0-9-+&@#\/%?=~_|!:,.;]*)

Essentially with the first part we are segmenting in this way:

Then we go and grab the different parts of interest: the first part is a non-capturing group as in your original expression to strip the protocol later, if really unneeded. The last part takes the remaining part of the URL
For the way we created the regex we can now decide if taking the entire URL or just the second part. This is evident looking to the bottom-right of this screenshot:

Now in order to log the two parts we can take this nice snippet:
const str = '

Link: https://www.link.com

';
var myRegexp = /\b(?![^<]*>)(?:https?|ftp):\/\/([a-z0-9-+&@#\/%?=~_|!:,.;]*)/gim;
var match = myRegexp.exec(str);
console.log(match[0]);
console.log(match[1]);

Possible variations:

*

*in a situation like the one presented above you can simplify further your regex to:
(?:https?|ftp):\/\/([a-z0-9-+&@#\/%?=~_|!:,.;]*)
getting the same output

*

*if the full URL is enough you can remove the round parentheses of the second group
(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*
PS - I'm assuming that your examples were meant to be:

Link: https://www.link.com

Link: https://www.link.com

i.e. with https, http or ftp which makes the second case work with your original regex


text:
Q: How to change numbers to letters How do I do then following. There are no spaces or dashes in the card_number column
A column that displays the last four digits of the card_number column in this format: XXXX-XXXX-XXXX-1234. In other words, use Xs for the first 12 digits of the card number and actual numbers for the last four digits of the number.

A: select 'XXXX-XXXX-XXXX-' + substring(card_number, 16) as masked_card_number
from your_table

SQLFiddle demo

A: With the help of substring and concat function you can do that
SELECT CONCAT('XXXX-XXXX-XXXX-', SUBSTRING(card_number, -4) AS masked_cc
FROM table;


text:
Q: How to simulate SHORTCUT in C#? I don't want to use input simulator.
I wanna send messages to the Process in the background.
I can't find exact documentation of
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

My problem is I want to send shortcut, but it doesn't work when I Press CTRL
-> then press buttons/release and release CTRL
static class Program
{
    const UInt32 WM_KEYDOWN = 0x0100;
    const int VK_F5 = 0x74;

    [DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

    [STAThread]
    static void Main()
    {
        while(true)
        {
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
                PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);

            Thread.Sleep(5000);
        }
    }
}


text:
Q: Recursive Method for Array Indexing XML Files Trying to Recursively Index XML
Been altering listed code but no dice.
public function hasChildren($node) {
    if (sizeof($node) != 0) {
        foreach ($node as $value) {
            $value = $this->nodeToIndexedArray($value);
            return $this->hasChildren($value);
        }
    } else {
        return $node;
    }
}


text:
Q: ActiveRecord joining nested associations on non default values Before you ask, I have no control over creating any views or join tables in the database I'm working with.
I found in the ActiveRecord docs where you can do multi-level joining:
12.2.4 Joining Nested Associations (Multiple Level)

Category.joins(articles: [{ comments: :guest }, :tags])
This produces:

SELECT categories.* FROM categories
  INNER JOIN articles ON articles.category_id = categories.id
  INNER JOIN comments ON comments.article_id = articles.id
  INNER JOIN guests ON guests.comment_id = comments.id
  INNER JOIN tags ON tags.article_id = articles.id

And where you can specify what to join on
Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')

What I want to do is something that combines the 2
Client.joins('Inner Join addresses on addresses.client_name = client.name').joins('Inner Join state on state.abreviation = addresses.state_abreviation)

or in raw sql
Select client.* from client
Inner Join addresses on client.client_name = addresses.client_name
Inner Join state on addresses.state_abreviation = state.abreviation

and If I can do this using associations instead of joins that would be great!:
class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category
  has_many :comments
  has_many :tags
end

class Comment < ActiveRecord::Base
  belongs_to :article
  has_one :guest
end

class Guest < ActiveRecord::Base
  belongs_to :comment
end

class Tag < ActiveRecord::Base
  belongs_to :article
end

A: Using Arel:
c = Client.arel_table
a = Adress.arel_table
s = State.arel_table
query = Client.all.arel
         .join(a)
           .on(a[:client_name].eq(c[:client_name]))
         .join(s)
           .on(s[:abreviation].eq(a[:state_abreviation]))
Client.find_by_sql(query.to_sql)

A: You could use 'through'
for your Category model these will be like this
class Category < ActiveRecord::Base
  has_many :articles
  has_many :comments, through: :articles
  has_many :tags, through: :articles
end

Category.last.tags
=> tags
Category.last.articles
=> articles

A: I found the answer.  You need to define the foreign_key for the table so you can map it back.
  belongs_to :addresses, foreign_key: 'state_abreviation'


text:
Q: Render Widget as HTML in Code Behind I have come across a situation where I'm needing to retrieve the rich text content of a page type column, and return that data/HTML as it would appear on a rendered page. A custom web part then serves aggregated data as nodes of XML or JSON.
For the most part this was easy enough in the code behind using DocumentQuery, however the problem is with widgets that have been inserted into the content.
My question is: How do I "render" a widget purely in code? Or even, what process is Kentico doing to render a widget that I might be able to reproduce?
I am somewhat familiar with the widget/web part/user control relationship, so I'm thinking a web part would need to be instantiated (somewhere, somehow) using the properties on the widget, and then accessing the RenderedHTML property of the web part.
Due to the format that widgets are stored in the data, I was hoping that they could just be Resolved with the MacroResolver, but that doesn't seem to be the case.
For reference, here is an example of how the out-of-the-box DateTime widget shows up:
{^widget|(jsuseservertime)False|(name)DateTime|(widget_displayname)Date+%26+time|(width)|(height)^}
Any input is greatly appreciated!

A: Have you checked this article http://devnet.kentico.com/articles/how-to-resolving-the-inline-controls? It is pretty old. But CMS.ExtendedControls.ControlsHelper.ResolveDynamicControls is available in newer Kentico versions. I think it might resolve you issue.


text:
Q: How to read values from XML document  in php Here is my problem :
I receive a xml string response from an api call an I need to read data. I use the function simplexml_load_string() to convert my string into a simpleXMLElement but some data don't appear to be correctly convert during the process.
Here is the exemple :
<JobList xmlns="http://webservice.blabla.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <jobCount>1</jobCount>
    <JobSet>
        <Job>
            ...
            <JobDataSet>
                <JobData>
                    ...
            </JobDataSet>
            ...
            <departmentKeys xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                <a:int>1608</a:int>
            </departmentKeys>
        </Job>
    </JobSet>
</JobList>

I want to access to 1608 in departmentKeys but when I parse it using simplexml_load_string() I have all data except the one in departmentKeys
result of my xmlelementand I don't understand why ?
Can someone help me ?
Sorry for my poor english.

A: You need to deal with namespaces:
$xmlDoc = simplexml_load_string($xmlString);#this assumes your xml string is well formed, of course
$xmlDoc->registerXPathNamespace("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
$target = $xmlDoc->xpath('//a:int/text()');
echo ($target[0]);

Output should be
1608


text:
Q: SyntaxError: Unexpected token '??=' Error al actualizar discord.js 12v a 13v
Supuestamente en la libreria. Soy yo o no existe esa syntaxis en JavaScript?
D:\Proyectos\Discord\NombreDelProyecto\node_modules\discord.js\src\rest\APIRequest.js:33
    agent ??= new https.Agent({ ...this.client.options.http.agent, keepAlive: true });
          ^^^

SyntaxError: Unexpected token '??='

A: Ese operador si existe y su nombre es Logical nullish assignment (??=).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
Es compatible con nodeJS desde la versión 15.0, sugiero revises si tu versión es inferior a esa.
Saludos