text:
Q: PHP money_format function use for multiple currency I want to use php money_format function from below currency.
(INR,USD,EUR,GBP,AUD,CNY,HKD,JPY)

In my system I have allow to select currency from above list, As per selection I have display amount.
I have tried this code for USD & INR
money_format('$%i',$amount); //USD

money_format('%!i',$amount); //INR

I want money format function code for all the currencies that I have listed above.

A: I have found this function on web and its really helpful for me.
Format currency
    function formatcurrency($floatcurr, $curr = "USD"){
        $currencies['ARS'] = array(2,',','.');          //  Argentine Peso
        $currencies['AMD'] = array(2,'.',',');          //  Armenian Dram
        $currencies['AWG'] = array(2,'.',',');          //  Aruban Guilder
        $currencies['AUD'] = array(2,'.',' ');          //  Australian Dollar
        $currencies['BSD'] = array(2,'.',',');          //  Bahamian Dollar
        $currencies['BHD'] = array(3,'.',',');          //  Bahraini Dinar
        $currencies['BDT'] = array(2,'.',',');          //  Bangladesh, Taka
        $currencies['BZD'] = array(2,'.',',');          //  Belize Dollar
        $currencies['BMD'] = array(2,'.',',');          //  Bermudian Dollar
        $currencies['BOB'] = array(2,'.',',');          //  Bolivia, Boliviano
        $currencies['BAM'] = array(2,'.',',');          //  Bosnia and Herzegovina, Convertible Marks
        $currencies['BWP'] = array(2,'.',',');          //  Botswana, Pula
        $currencies['BRL'] = array(2,',','.');          //  Brazilian Real
        $currencies['BND'] = array(2,'.',',');          //  Brunei Dollar
        $currencies['CAD'] = array(2,'.',',');          //  Canadian Dollar
        $currencies['KYD'] = array(2,'.',',');          //  Cayman Islands Dollar
        $currencies['CLP'] = array(0,'','.');           //  Chilean Peso
        $currencies['CNY'] = array(2,'.',',');          //  China Yuan Renminbi
        $currencies['COP'] = array(2,',','.');          //  Colombian Peso
        $currencies['CRC'] = array(2,',','.');          //  Costa Rican Colon
        $currencies['HRK'] = array(2,',','.');          //  Croatian Kuna
        $currencies['CUC'] = array(2,'.',',');          //  Cuban Convertible Peso
        $currencies['CUP'] = array(2,'.',',');          //  Cuban Peso
        $currencies['CYP'] = array(2,'.',',');          //  Cyprus Pound
        $currencies['CZK'] = array(2,'.',',');          //  Czech Koruna
        $currencies['DKK'] = array(2,',','.');          //  Danish Krone
        $currencies['DOP'] = array(2,'.',',');          //  Dominican Peso
        $currencies['XCD'] = array(2,'.',',');          //  East Caribbean Dollar
        $currencies['EGP'] = array(2,'.',',');          //  Egyptian Pound
        $currencies['SVC'] = array(2,'.',',');          //  El Salvador Colon
        $currencies['ATS'] = array(2,',','.');          //  Euro
        $currencies['BEF'] = array(2,',','.');          //  Euro
        $currencies['DEM'] = array(2,',','.');          //  Euro
        $currencies['EEK'] = array(2,',','.');          //  Euro
        $currencies['ESP'] = array(2,',','.');          //  Euro
        $currencies['EUR'] = array(2,',','.');          //  Euro
        $currencies['FIM'] = array(2,',','.');          //  Euro
        $currencies['FRF'] = array(2,',','.');          //  Euro
        $currencies['GRD'] = array(2,',','.');          //  Euro
        $currencies['IEP'] = array(2,',','.');          //  Euro
        $currencies['ITL'] = array(2,',','.');          //  Euro
        $currencies['LUF'] = array(2,',','.');          //  Euro
        $currencies['NLG'] = array(2,',','.');          //  Euro
        $currencies['PTE'] = array(2,',','.');          //  Euro
        $currencies['GHC'] = array(2,'.',',');          //  Ghana, Cedi
        $currencies['GIP'] = array(2,'.',',');          //  Gibraltar Pound
        $currencies['GTQ'] = array(2,'.',',');          //  Guatemala, Quetzal
        $currencies['HNL'] = array(2,'.',',');          //  Honduras, Lempira
        $currencies['HKD'] = array(2,'.',',');          //  Hong Kong Dollar
        $currencies['HUF'] = array(0,'','.');           //  Hungary, Forint
        $currencies['ISK'] = array(0,'','.');           //  Iceland Krona
        $currencies['INR'] = array(2,'.',',');          //  Indian Rupee
        $currencies['IDR'] = array(2,',','.');          //  Indonesia, Rupiah
        $currencies['IRR'] = array(2,'.',',');          //  Iranian Rial
        $currencies['JMD'] = array(2,'.',',');          //  Jamaican Dollar
        $currencies['JPY'] = array(0,'',',');           //  Japan, Yen
        $currencies['JOD'] = array(3,'.',',');          //  Jordanian Dinar
        $currencies['KES'] = array(2,'.',',');          //  Kenyan Shilling
        $currencies['KWD'] = array(3,'.',',');          //  Kuwaiti Dinar
        $currencies['LVL'] = array(2,'.',',');          //  Latvian Lats
        $currencies['LBP'] = array(0,'',' ');           //  Lebanese Pound
        $currencies['LTL'] = array(2,',',' ');          //  Lithuanian Litas
        $currencies['MKD'] = array(2,'.',',');          //  Macedonia, Denar
        $currencies['MYR'] = array(2,'.',',');          //  Malaysian Ringgit
        $currencies['MTL'] = array(2,'.',',');          //  Maltese Lira
        $currencies['MUR'] = array(0,'',',');           //  Mauritius Rupee
        $currencies['MXN'] = array(2,'.',',');          //  Mexican Peso
        $currencies['MZM'] = array(2,',','.');          //  Mozambique Metical
        $currencies['NPR'] = array(2,'.',',');          //  Nepalese Rupee
        $currencies['ANG'] = array(2,'.',',');          //  Netherlands Antillian Guilder
        $currencies['ILS'] = array(2,'.',',');          //  New Israeli Shekel
        $currencies['TRY'] = array(2,'.',',');          //  New Turkish Lira
        $currencies['NZD'] = array(2,'.',',');          //  New Zealand Dollar
        $currencies['NOK'] = array(2,',','.');          //  Norwegian Krone
        $currencies['PKR'] = array(2,'.',',');          //  Pakistan Rupee
        $currencies['PEN'] = array(2,'.',',');          //  Peru, Nuevo Sol
        $currencies['UYU'] = array(2,',','.');          //  Peso Uruguayo
        $currencies['PHP'] = array(2,'.',',');          //  Philippine Peso
        $currencies['PLN'] = array(2,'.',' ');          //  Poland, Zloty
        $currencies['GBP'] = array(2,'.',',');          //  Pound Sterling
        $currencies['OMR'] = array(3,'.',',');          //  Rial Omani
        $currencies['RON'] = array(2,',','.');          //  Romania, New Leu
        $currencies['ROL'] = array(2,',','.');          //  Romania, Old Leu
        $currencies['RUB'] = array(2,',','.');          //  Russian Ruble
        $currencies['SAR'] = array(2,'.',',');          //  Saudi Riyal
        $currencies['SGD'] = array(2,'.',',');          //  Singapore Dollar
        $currencies['SKK'] = array(2,',',' ');          //  Slovak Koruna
        $currencies['SIT'] = array(2,',','.');          //  Slovenia, Tolar
        $currencies['ZAR'] = array(2,'.',' ');          //  South Africa, Rand
        $currencies['KRW'] = array(0,'',',');           //  South Korea, Won
        $currencies['SZL'] = array(2,'.',', ');         //  Swaziland, Lilangeni
        $currencies['SEK'] = array(2,',','.');          //  Swedish Krona
        $currencies['CHF'] = array(2,'.','\'');         //  Swiss Franc
        $currencies['TZS'] = array(2,'.',',');          //  Tanzanian Shilling
        $currencies['THB'] = array(2,'.',',');          //  Thailand, Baht
        $currencies['TOP'] = array(2,'.',',');          //  Tonga, Paanga
        $currencies['AED'] = array(2,'.',',');          //  UAE Dirham
        $currencies['UAH'] = array(2,',',' ');          //  Ukraine, Hryvnia
        $currencies['USD'] = array(2,'.',',');          //  US Dollar
        $currencies['VUV'] = array(0,'',',');           //  Vanuatu, Vatu
        $currencies['VEF'] = array(2,',','.');          //  Venezuela Bolivares Fuertes
        $currencies['VEB'] = array(2,',','.');          //  Venezuela, Bolivar
        $currencies['VND'] = array(0,'','.');           //  Viet Nam, Dong
        $currencies['ZWD'] = array(2,'.',' ');          //  Zimbabwe Dollar

        function formatinr($input){
            //CUSTOM FUNCTION TO GENERATE ##,##,###.##
            $dec = "";
            $pos = strpos($input, ".");
            if ($pos === false){
                //no decimals
            } else {
                //decimals
                $dec = substr(round(substr($input,$pos),2),1);
                $input = substr($input,0,$pos);
            }
            $num = substr($input,-3); //get the last 3 digits
            $input = substr($input,0, -3); //omit the last 3 digits already stored in $num
            while(strlen($input) > 0) //loop the process - further get digits 2 by 2
            {
                $num = substr($input,-2).",".$num;
                $input = substr($input,0,-2);
            }
            return $num . $dec;
        }

        if ($curr == "INR"){
            return formatinr($floatcurr);
        } else {
            return number_format($floatcurr,$currencies[$curr][0],$currencies[$curr][1],$currencies[$curr][2]);
        }
    }

    echo formatcurrency(39174.00000000001);             //1,000,045.25 (USD)

    /*formatcurrency(1000045.25, "CHF");        //1'000'045.25
    formatcurrency(1000045.25, "EUR");      //1.000.045,25
    formatcurrency(1000045, "JPY");         //1,000,045
    formatcurrency(1000045, "LBP");         //1 000 045
    formatcurrency(1000045.25, "INR");      //10,00,045.25
    */
    ?>


text:
Q: WordPress Multisite Login Access I have a multisite installation and use an .htaccess directive to close access to wp-login.php.
<files wp-login.php>
errordocument 403 http://example.com/restricted/
order deny,allow
deny from all
</files>

Is there a way that I can allow access to a specific individual site using another directive?
I don't know how multisite generates those URLs, as I don't see an obvious rewrite rule.

A: If you want to provide restricted access, you should add an additional string with the /wp-login.php URL. For example:
http://example.com/wp-login.php?restricted_site_access=key_string

If the URL does not have such a string parameter, then you can redirect them to a 404 page; you don't need to rewrite the .htaccess file for it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache will not start on CentOS in Local Network I installed httpd on a CentOS 7 server, but systemctl start httpd.service is failing.
What specific sequence of commands need to be typed in order to get httpd to start correctly on CentOS 7?
Error Message
The precise error message extracted from the full results at bottom is as follows:
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain.
Set the 'ServerName' directive globally to suppress this message

Also, per @DopeGhoti's suggestion, the contents of the logs are:
[root@localhost ~]# vi /var/log/httpd/error_log
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.

How httpd was installed:
1.) Install Apache:
sudo yum -y install httpd

2.) Enable Apache as a CentOS service so that it will automatically restart on reboot:
sudo systemctl enable httpd.service

3.) Configure Firewalld
sudo firewall-cmd --zone=public --add-service=http
sudo firewall-cmd --list-all
sudo firewall-cmd --zone=public --permanent --add-service=http

4.) Give the server a name:
vi /etc/httpd/conf/httpd.conf
//Uncomment the ServerName line and give it the IP of the machine:
ServerName 192.168.1.5:80

The error message:
After installing httpd using the above commands, httpd is failing to start as follows:
[root@localhost ~]# systemctl start httpd.service
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.

[root@localhost ~]# systemctl status httpd.service -l
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2017-06-06 11:31:32 PDT; 15min ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 32268 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 32267 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 32267 (code=exited, status=1/FAILURE)

Jun 06 11:31:32 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
Jun 06 11:31:32 localhost.localdomain httpd[32267]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain. Set the 'ServerName' directive globally to suppress this message
Jun 06 11:31:32 localhost.localdomain systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jun 06 11:31:32 localhost.localdomain kill[32268]: kill: cannot find process ""
Jun 06 11:31:32 localhost.localdomain systemd[1]: httpd.service: control process exited, code=exited status=1
Jun 06 11:31:32 localhost.localdomain systemd[1]: Failed to start The Apache HTTP Server.
Jun 06 11:31:32 localhost.localdomain systemd[1]: Unit httpd.service entered failed state.
Jun 06 11:31:32 localhost.localdomain systemd[1]: httpd.service failed.
[root@localhost ~]# systemctl status httpd.service -l

[root@localhost ~]# vi /var/log/httpd/error_log
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs
~
"/var/log/httpd/error_log" 10L, 675C

@JeffSchaller's suggestion
After @JeffSchaller suggested to consider SELinux, I found that typing setenforce 0 as root resulted in the following:
[root@localhost ~]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   enforcing
Mode from config file:          enforcing
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      28

[root@localhost ~]# setenforce 0

[root@localhost ~]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   permissive
Mode from config file:          enforcing
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      28

[root@localhost ~]# systemctl start httpd.service -l
[root@localhost ~]# systemctl status httpd.service -l
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2017-06-06 12:28:38 PDT; 22s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 32577 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
 Main PID: 32690 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─32690 /usr/sbin/httpd -DFOREGROUND
           ├─32691 /usr/sbin/httpd -DFOREGROUND
           ├─32692 /usr/sbin/httpd -DFOREGROUND
           ├─32693 /usr/sbin/httpd -DFOREGROUND
           ├─32694 /usr/sbin/httpd -DFOREGROUND
           └─32695 /usr/sbin/httpd -DFOREGROUND

Jun 06 12:28:38 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
Jun 06 12:28:38 localhost.localdomain systemd[1]: Started The Apache HTTP Server.
[root@localhost ~]#

A: Apache failed to start, with an error saying

(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs

Since SELinux was in enforcing mode, it prevented Apache from writing to the non-standard log directory. In order to keep Dan Walsh from weeping and CodeMed productive, we can apply the httpd_log_t policy to that directory:
semanage fcontext -a -t httpd_log_t "/var/www/mytestdeployment(/.*)?"
restorecon -Rv /var/www/mytestdeployment

and confirm with:
ls -lZ /var/www/mytestdeployment

If you don't have the semanage utility, you can install it with:
yum install policycoreutils-python

A: From your error log, we see this:
(13)Permission denied: AH00091: httpd: could not open error log file /var/www/mytestdeployment/error.log.
AH00015: Unable to open logs

This implies to me that the directory into which you are trying to write logs, /var/www/mytestdeployment, does not exist.
Run sudo mkdir -p /var/www/mytestdeployment and try starting the service again.
If the directory already exists, its permission set precludes being written to; check the permissions of that directory to ensure apache can write its logs therein.
I would suggest, though changing your configuration to write the logs into /var/log/httpd/.

A: as i can see from your previous screenshots when you disable selinux everything is going well. So make sure that every new file that you created have the right selinux context.


text:
Q: Не выполняются sh скрипты в контейнере docker. psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed Подскажите пожалуйста, после запуска контейнера с PostgreSQL хочу выполнить скрипт sh который бы подконнектился к бд и выполнил запрос из SQL файла моего, но появляется ошибка коннекта к моей БД.
/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh
pg_14_1 | psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
pg_14_1 |       Is the server running on that host and accepting TCP/IP connections?
pg_14_1 | connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address
pg_14_1 |       Is the server running on that host and accepting TCP/IP connections?

Хотя если зайти в контейнер и там выполнить psql -h localhost -p5432 -U postgres -f /var/init.sql он успешно выполняется.
dockser-compose:
   version: '3'

services:
  db:
    build: /Users/db
    container_name: pg_14_1
    ports:
    - "5432:5432"
    environment:
    - POSTGRES_PASSWORD=root
    - POSTGRES_USER=postgres
    restart: always
    volumes:
    - type: bind
      source: /Users/db/init.sh
      target: /docker-entrypoint-initdb.d/init.sh

dockerfile:
FROM postgres:14

COPY init.sql ./var/

RUN mkdir /var/pgdata
RUN mkdir /var/pgdata/ts

ну и сам init.sh содержит у меня лишь
#!/bin/bash

psql -h localhost -p5432 -U postgres -f /var/init.sql


text:
Q: Using a Euclidean norm to bound a $k$-tuple This does not look too complicated, but I've been stuck here for several hours. My question is to prove that $||(h, \cdots, h)||\leq ||h||^{k}$, where $||\cdot||$ is the euclidean norm, and $(h,\cdots, h)$ is a $k$-tuple with $h\in R^n$.
My attempt: by definition, $||(h, \cdots, h)||=|\sum\limits_{i_1, \cdots, i_k}^{n} (h_{i_1})\times \cdots \times (h_{i_k})|.$ Also, $||h||^{k}=((\sum\limits_{j=1}^{n} h_j^2)^k)^{\frac{1}{2}}.$ Then, I think I should use Cauchy-Swartz Inequality somewhere. Could someone give me a hint? Thanks in advance!

A: This is false; if $n=1$ and $k=2$ and $h=\frac{1}{2}$ then $||h||=\frac{1}{2}$ whereas
$$\left|\left|\left(\frac{1}{2},\frac{1}{2}\right)\right|\right|=\sqrt{\left(\frac{1}{2}\right)^2+\left(\frac{1}{2}\right)^2}=\frac{1}{\sqrt{2}}>\frac{1}{4}=||h||^2.$$
Of course this example scales to any $n$ and $k$ with $nk>1$.


text:
Q: Kernel update for Ubuntu 12.04 with Linux 3.11.0-15-generic is failing How to update to Linux 3.11.0-15-generic on Ubuntu 12.04.

A: Ubuntu 12.04 has passed end of life (unless you have (paid for) extended security maintenance, that you are an Ubuntu Advantage customer). As a regular user you cannot expect to update and upgrade Ubuntu within the version 12.04 LTS.
Please make a fresh installation of a current version! I would suggest that you try the version 16.04 LTS,

*

*standard Ubuntu

*or one of the community flavours with a light desktop environment, if the computer is getting old (Lubuntu, Ubuntu Budgie, Ubuntu MATE or Xubuntu).

Try first (booted from DVD or USB), and install, when you find a version/flavour, that works well. See this link
Try Ubuntu (Kubuntu, Lubuntu, Xubuntu, ...) before installing it


text:
Q: data:Url php with random numbers I need to write a function that returns a date:url picture with a random number, I'm absolutely confused, here are my attempts, tell me where to go next
$function = new \Twig\TwigFunction('picture', function () {

    header("Content-Type: image/png");
    $im = @imagecreate(50, 50)
    or die("Невозможно создать поток изображения");
    $background_color = imagecolorallocate($im, 0, 0, 0);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    $string = rand();
    imagestring($im, 1, 5, 5,  $string, $text_color);
    imagepng($im);
    imagedestroy($im);
    $img64 = base64_encode($im);
    return $img64;

});

$twig->addFunction($function);

A: Issues:

*

*header("Content-Type: image/png"); doesn't make any sense. Your function returns plain text that isn't even meant to be returned to browser as-is but injected inside HTML. Get rid of this line.

*The @ in @imagecreate(50, 50) is the error control operator. By default it'll just hide useful error messages from you. You don't possibly want it either.

*You define $background_color but never use it. You can feed it to imagefill() or, if you want it black, omit it altogether.

*imagepng($im) immediately prints the image. That's bad when you want to process and return it. You can capture with e.g. output control functions.

*base64_encode($im) triggers:

Warning: base64_encode() expects parameter 1 to be string, resource

You're incorrectly assuming that imagecreate() returns the final image bytes; it doesn't. It returns a resource to be passed as argument to other image functions. You don't need it for anything else. Additionally, if you didn't see the message it can mean that you haven't configured PHP to display error messages.

*There's no need to imagedestroy(). The image is local to the function, builtin garbage collector will take care.

*Don't store the image bytes in temporary variables for no reason, that will only increase memory consumption.
So you basically need to understand that your code is not a black box and ensure that every line you write has a purpose known to you and is used as the corresponding manual page explains.
$im = imagecreate(50, 50)
    or die("Невозможно создать поток изображения");
$text_color = imagecolorallocate($im, 233, 14, 91);
$string = rand();
imagestring($im, 1, 5, 5,  $string, $text_color);
ob_start();
imagepng($im);
return base64_encode(ob_get_clean());


text:
Q: How do you make a better seo friendly URL when there is UTF-8 characters and many space in between? When someone by mistake enters many spaces between characters what I do is to replace all spaces with - but what if there are many spaces in between? for e.g:
User entered post title:
فارسی   * Allposts---

When I convert the above example to user-friendly url (slug) I get this:
----فارسی---*-Allposts---

How to put one - for spaces and remove special characters and preserve utf-8 characters as well? The output I'm seeking for is as below:
فارسی-Allposts

Is there a way to handle it with regex? if positive, how?

EDIT:
Now I can manage multiple spaces as below:
 $string = preg_replace('/\s+/', '-', $string);

but for special chars problem still remains.

A: *

*Remove special characters:  replace [\-\?\*] or whatever your blacklist characters are with empty string.

*Convert strings of whitespace to a single - character: replace \s+ with -

Looks like you already figured out step 2.  Make sure you do it second so you don't accidentally remove your own hyphens that you just inserted.


text:
Q: Store result of a for loop in Perl as a single variable I'm currently printing a result in the for loop itself:
for (@data1, @data2, @data3) {
    print "$_" . " ";
}

Instead I want to process the loop quietly and store the entire result of the for loop as a variable, then print it separately like so:
print "$forloopresult";

How do I do that? Thanks!

A: For this case, I'd just use a join:
my $foo = join(' ', @data1, @data2, @data3);
print "$foo "; # space at the end to emulate your for loop

A: Just declare the variable and append the data at each step:
my $result = "";
for (@data) {
    $result = $result."$_ ";
}

print $result;

A: If your intention is to keep the print statement but have the text go to a variable instead of to a console then that is also possible. You can print to a scalar variable if you pass a reference to that variable instead of a file name
It looks like this. I have declared $forloopresult and passed \$forloopresult as the third parameter of open. The output of Data::Dump shows the result
use strict;
use warnings;

use Data::Dump;

my @data1 = qw/ a b c /;
my @data2 = qw/ aa bb cc /;
my @data3 = qw/ aaa bbb ccc /;

my $forloopresult;
open my $fh, '>', \$forloopresult or die $!;

for ( @data1, @data2, @data3 ) {
    print $fh "$_ ";
}

dd $forloopresult;

output
"a b c aa bb cc aaa bbb ccc "


text:
Q: Placing a value at the bottom of a channel? In Clojure(Script), is there anyway to jam a value at the bottom (as opposed to the top) of a channel so that the next time it is taken from (for example by using <! inside a go block), it is guaranteed that that the value you jammed into it will be the one that is received?

A: I'm not sure there is any easy way to do this. You may be able to implement your own type of buffer, as in buffers.clj, and then instantiate your channel using that buffer:
(chan (lifo-buffer 10))

For example you could create a buffer that works like a LIFO queue:
(deftype LIFOBuffer [^LinkedList buf ^long n]
  impl/UnblockingBuffer
  impl/Buffer
  (full? [this]
    false)
  (remove! [this]
    (.removeFirst buf))
  (add!* [this itm]
    (when-not (>= (.size buf) n)
      (.addFirst buf itm))
    this)
  (close-buf! [this])
  clojure.lang.Counted
  (count [this]
    (.size buf)))

(defn lifo-buffer [n]
  (LIFOBuffer. (LinkedList.) n))

Beware, though, that this solution relies on implementation details of core.async and may break in the future.

A: You can have two channels, imagine one is called first-class and the other is called economy. You write a go-loop that just recurs and calls alts! (or alts!!) on the two channels, but with the :priority option for first-class. Then you put values into economy as your "normal" input channel, and when you want a value to jump the line, you put it into first-class.


text:
Q: Excel functions for whole columns I was wondering how you would make a function for a whole columns by using other columns in the function. So for example column C = A + B. and this would work for the whole column not matter what the row is. Note: I do know how to select a whole column. :)
EDIT: what i am meaning is that for c3 c4 c5 c6 ect all have the function that the a3+b3 = c3 then a4+b4=c4 and so on and so forth
Thanks in advance

A: Edit:
Sorry about that, I misunderstood.
All you need is to have the function in the first cell, then you "drag" it down and it will fill for you.
In the screenshot, you can see the function bar, me dragging it and the arrow is to the little box to drag with.


text:
Q: Import in C# bundle written in c++ (Unity3D project) I try to use the functions from a .bundle file inside Unity3D but every time when I call the functions I get the error:
DllNotFoundException: libant
connectANT.Start () (at Assets/connectANT.cs:13)

This is the script that I use to call the library antlib.bundle which is in the Assets/Plugin folder:
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class connectANT : MonoBehaviour {
[DllImport("libant")] static extern bool ANT_Init(int ucUSBDeviceNum_, int ulBaudrate_);
void Start () {
    ANT_Init (1, 50000);
}
}

in the bundle this function is declared like this:
#ifdef __cplusplus
extern "C" {
#endif
EXPORT BOOL ANT_Init(UCHAR ucUSBDeviceNum_, ULONG ulBaudrate_);  //Initializes and opens USB connection to the module
#ifdef __cplusplus
}
#endif

This is just  an example with only one function from the bundle. If I just import the functions in my script I don't get any error in Unity.
Can someone help me to figure it out?

A: try this:
[DllImport("antlib.bundle")]
static extern int ANT_Init(byte ucUSBDeviceNum_, uint ulBaudrate_);

there're two problems in your code:

*

*wrong file name

*wrong argument type and return type

if you want to use bool as return type, another attribute is required:
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
[DllImport("antlib.bundle")]
static extern bool ANT_Init(byte ucUSBDeviceNum_, uint ulBaudrate_);

A: Sam is right, your return value and arguments have to match.
Also, make sure you bundle includes info.plist with following:
<key>CFBundleExecutable</key>
<string>antlib.dylib</string>

your bundle name and your library name do not have to match, but your plist needs to fix this by pointing to the right lib.


text:
Q: Let $T$ be a normal random variable that describes the temperature... Let $T$ be a normal random variable that describes the temperature in Rome
on the 2nd of June. It is known that on this date the average temperature is equal to $µ_T = 20$ centigrade degrees and that $P (T ≤ 25) = 0.8212$.
How can I calculate the variance of $T$?

A: From $P(T \leq 25)=0.8212$, you can find the $z$-score of $25$ (reverse-lookup in a $z$-score table).
The $z$-score of $25$ is also given by $z=\frac{25-\mu_T}{\sigma}$.
Set these two expressions for the $z$-score equal to each other and solve for $\sigma$. Finally, square it to get $\sigma^2$.

A: Consider the standard version of $T$,
$$\Pr(Z \leq \alpha) = 0.8212$$
where we subtract by the mean and divide by standard deviation $\sigma$, as
$$\Pr(T \leq 25) = \Pr(\underbrace{\frac{T - \mu_T}{\sigma}}_Z \leq \underbrace{\frac{25 - 20}{\sigma}}_\alpha) = 0.8212$$
Using the z table, you can easily find $\alpha$, which gives you $\sigma$.


text:
Q: In Javascript how to make arrays with custom behavior that can be instantiated? I need an kind of "circular array". I have everything working but for single instance. I don't know how to make it "instantiable". I mean I want it to work the following way:
var arr = ['a', 'b', 'c', 'd']; // it's kind of pseudo-code
arr.getNext(); // gives a
arr.getNext(); // gives b
arr.getNext(); // gives c
arr.getNext(); // gives d
arr.getNext(); // gives a
arr.getNext(); // gives b
// and so on

I know I can create object with array inside and iterate over it, but I'm pretty sure I can do this the other way.
The problem is I need several instances of that object. If it was only one instance I could do:
var arr = ['a', 'b', 'c', 'd'];
arr.getNext = function() {
  // ... I got this stuff working
}

How to allow createion of several instances of such custom arrays?

A: Even if you can extend Array.prototype with Object.defineProperty (to create a non-enumerable property), an alternative solution might be interesting as well, depending on your actual needs.
You could define a function that returns an iterator over an array:
function iter(arr) {
    var index = -1;

    return {
        next: function() {
            index = (index + 1) % arr.length;
            return arr[index];
        }
    };
}

Usage:
var it = iter(arr);
it.next();

A: You can extend the prototype to be able to use it in all instances of Array:
Array.prototype.getNext = function(){
  var next = this.shift();
  this.push(next);
  return next;
};

Note that this modifies the array.

A: You can add you getNext method to the Array prototype, like this:
Array.prototype.getNext = function ()
{
....
}

You can then call this method on any array that you create.


text:
Q: xsl scenario when a node is not present in every for each loop I have an xml represented by this http://feeds.contenthub.aol.com/syndication/2.0/feed/53dfbe8362619. I am also postin a patch of an xml
<item>
<title>
<![CDATA[ Jon Lester Uses Full-Page Ad To Thank Red Sox Fans ]]>
</title>
<description type="html">
<![CDATA[

Jon Lester made a classy move by taking a full-age ad in the Sunday edition of the Boston Globe...

]]>
</description>
<link>
http://www.huffingtonpost.com/2014/08/03/jon-lester-full-page-ad-red-sox-fans_n_5645882.html
</link>
<source_id>qkjDte</source_id>
<guid isPermalink="false">0d85d061e4436ffaeeeafa9a86c3a253</guid>
<dc:creator>Michael Klopman</dc:creator>
<dc:publisher>Huff. Post: United States - Sports</dc:publisher>
<dc:rightsHolder>Huff. Post: United States - Sports</dc:rightsHolder>
<pubDate>Sun, 03 Aug 2014 19:58:04 +0000</pubDate>
<ingested>1407096147696297537</ingested>
<modified>2014-08-05 14:58:17</modified>
<category>
<![CDATA[ Jon Lester full page ad ]]>
</category>
<category>
<![CDATA[ brew-pub ]]>
</category>
<category>
<![CDATA[ Red Sox Jon Lester ]]>
</category>
<category>
<![CDATA[ mlb ]]>
</category>
<category>
<![CDATA[ major league baseball ]]>
</category>
<category>
<![CDATA[ Jon LEster full-page ad ]]>
</category>
<category>
<![CDATA[ Jon Lester Boston Globe ]]>
</category>
<category>
<![CDATA[ Oakland A's ]]>
</category>
<category>
<![CDATA[ Red Sox ]]>
</category>
<category>
<![CDATA[ oakland Athletics ]]>
</category>
<category>
<![CDATA[ Boston Red Sox ]]>
</category>
<media:content url="http://i.huffpost.com/gen/1945400/original.jpg" width="" height="" medium="image">
<media:keywords>headline</media:keywords>
<media:media_html>
<![CDATA[ <HH--PHOTO--JON-LESTER--1945400--HH> ]]>
</media:media_html>
<dc:identifier>
<![CDATA[ ]]>
</dc:identifier>
<media:credit>
<![CDATA[ ASSOCIATED PRESS ]]>
</media:credit>
<media:description>
<![CDATA[
Boston Red Sox starting pitcher Jon Lester heads to the bull pen before a baseball game against the Kansas City Royals in Boston, Sunday, July 20, 2014. (AP Photo/Michael Dwyer)
]]>
</media:description>
<media:title>
<![CDATA[ ]]>
</media:title>
</media:content>
</item>
<item>
<title>
<![CDATA[ 10 Home Runs of the Century ]]>
</title>
<description type="html">
<![CDATA[ %Slideshow-209585% ]]>
</description>
<link>
http://www.mandatory.com/2014/07/24/10-home-runs-of-the-century/
</link>
<source_id>blEPZi</source_id>
<guid isPermalink="false">20936381</guid>
<dc:creator>Joshua Crouthamel</dc:creator>
<dc:publisher>Mandatory</dc:publisher>
<dc:rightsHolder>Mandatory</dc:rightsHolder>
<pubDate>Thu, 24 Jul 2014 15:52:00 +0000</pubDate>
<ingested>1406220498372620179</ingested>
<modified>2014-07-24 16:45:40</modified>
<category>
<![CDATA[ co-gallery ]]>
</category>
<category>
<![CDATA[ Sports ]]>
</category>
<ss:slideshow>
<ss:media_html>
<![CDATA[ %slideshow-209585% ]]>
</ss:media_html>
<media:title>
<![CDATA[ 10 Home Runs of the Century ]]>
</media:title>
<dc:identifier>
<![CDATA[ 209585 ]]>
</dc:identifier>
<dc:created>2014-07-24 15:52:00</dc:created>
<media:content url="http://www.blogcdn.com/slideshows/images/slides/279/483/8/S2794838/slug/l/1-2.jpg" width="" height="" medium="image">
<dc:identifier>
<![CDATA[ 2794838 ]]>
</dc:identifier>
<media:credit>
<![CDATA[ New York Giants ]]>
</media:credit>
<media:description>
<![CDATA[

The home run is the best part of baseball. But not all home runs are created equal. Here are the 10 most amazing home runs of the century. (Prepare to argue in the comments.)

Bobby Thomson’s “Shot Heard ‘Round the World”
 October 3, 1951: Things weren’t looking good for the New York Giants coming into the ninth inning of the National League pennant game — they were down 4-1 to the Brooklyn Dodgers, and the game’s winner would take home the title. Enter Bobby Thomson, who hit a game-ending three-run homer … and the New York Polo Grounds went wild.

]]>
</media:description>
<media:title>
<![CDATA[ Bobby Thomson's "Shot Heard 'Round the World" ]]>
</media:title>
</media:content>
<media:content url="http://www.blogcdn.com/slideshows/images/slides/279/484/0/S2794840/slug/l/2-2.jpg" width="" height="" medium="image">
<dc:identifier>
<![CDATA[ 2794840 ]]>
</dc:identifier>
<media:credit>
<![CDATA[ Los Angeles Dodgers ]]>
</media:credit>
<media:description>
<![CDATA[

Kirk Gibson’s World Series Home Run
 October 15, 1988: Talk about an incredible underdog story. Gibson was nursing two knee injuries as well as a virus when he was called in to pinch hit for the Los Angeles Dodgers at the bottom of the ninth, Dodgers down by one with two outs on the board. His two-run, walk-off homer, followed by subsequent fist-pumping round of the bases, was one of the greatest moments in LA sporting history (and won the game).

]]>

So my xsl is iterating over every item node to get <title>, <description>, <media:content/@url> and <link> node. However there are 2 corner cases which I want to address in my xslt. If you look at the feed Link http://feeds.contenthub.aol.com/syndication/2.0/feed/53dfbe8362619 within the  node which I am for:eaching through there are scenarion when the  node is not present and hence I cannot access it @url attribute. So when /@url attribute is not present there are  nodes those are also not there for every  node but they are for those where  node is not present. I want to write an xsl which does this
if(!media:content node)
{
get ss:slideshow/media:content[1]/@url//first media:content node and its url attribute
}
second cornercase is some  node have %slideshow.
I want to get ss:slideshow/media:description if the normal  node contains '%slideshow' as content. I have written xsl for that but it does not give me the media:description within ss:slideshow.
so what I want is something like this
if(description node containe '%Slideshow)
{
use ss;slideshow/media:description
}
 It breaks with a failed XSL transformation when I try to access the ss:slideshow node.
My XSL is as follows
 <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
        xmlns:media="http://search.yahoo.com/mrss/">
        <xsl:output method="xml" indent="yes"/>
        <xsl:template match="/">
            <rss xmlns:georss="http://www.georss.org/georss" xmlns:twitter="http://api.twitter.com" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
                <channel>
                    <author>
                        <xsl:text>Content-Feed-Pics</xsl:text>
                    </author>
                    <xsl:for-each select="rss/channel/item[position() < 30]">
                        <item>
                            <title><xsl:value-of select="title"/></title>
                            <xsl:call-template name="deleteEllipses">
                                <xsl:with-param name="nodeData" select="description"></xsl:with-param>
                            </xsl:call-template>

                            <link><xsl:value-of select="link"/></link>

                            <enclosure>
                     <xsl:attribute name="url">

                       <xsl:value-of select="media:content/@url"/>
                   </xsl:attribute>
                             <xsl:attribute name="type">
                              <xsl:text>image/jpg</xsl:text>
                              </xsl:attribute>
                          </enclosure>

                        </item>
                    </xsl:for-each>
                </channel>
            </rss>
        </xsl:template>
         <xsl:template name="deleteEllipses">
            <xsl:param name="nodeData"/>
            <xsl:choose>
                <xsl:when test="contains($nodeData, '%Slideshow')">

                    <description><xsl:value-of select="//media:content[1]/media:description"/></description>
                </xsl:when>
                <xsl:otherwise>
                    <description><xsl:value-of select="$nodeData"/></description>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:template>

    </xsl:stylesheet>

Please help me with this.
Regards
Swaraj

A: First, what you need to do is declare the relevant namespace in your XSLT, to allow to easily access nodes in the XML belonging to that namespace
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:media="http://search.yahoo.com/mrss/"
    xmlns:ss="http://contenthub.aol.com/slideshow/">

Then, one solution is to just use an xsl:choose to determine whether a media:content element is present.
<xsl:attribute name="url">
  <xsl:choose>
   <xsl:when test="media:content">
       <xsl:value-of select="media:content/@url"/>
   </xsl:when>
   <xsl:otherwise>
       <xsl:value-of select="ss:slideshow/media:content[1]/@url"/>
   </xsl:otherwise>
  </xsl:choose>
</xsl:attribute>

In fact, as it looks like you are still looking for a media:content element, but just at a different level, you can getaway with not having an xsl:choose at all, and just do this...
<xsl:attribute name="url">
   <xsl:value-of select=".//media:content/@url"/>
</xsl:attribute>

Better still, use "Attribute Value Templates" to create the attributes on the enclosure item directly
<enclosure url="{.//media:content/@url}" type="image/jpg" />


text:
Q: Bash and variables substitution I use this to generate svn logs for a specific user:
svn log | sed -n '/bob/,/-----$/ p'

which works fine. Now I would like to use a parameter/variable for the user:
USER="bob"
svn log | sed -n '/$USER/,/-----$/ p'

but it just give an empty log. How do I pass a parameter to the above command?

A: The correct way to do this is to use double quotes so that the bash variable can be expanded:
USER="bob"
svn log | sed -n "/$USER/,/-----$/p"

Adding more single quotes to "insert" a bash variable (as per the accepted answer) is not best practice. HTH.

A: Use single quotes:
USER="bob"
svn log | sed -n '/'$USER'/,/-----$/ p'

A: try:
svn log | sed -n '/"$USER"/,/-----$/ p'


text:
Q: Best way to invert a n x n Matrix I was wondering what's the correct and best way on Java to invert a (double) 2D matrix. My input(MatrixToBeInverted) is a double[][] ,filled and over 20x20. Using code like this will throw me errors.
invMatrix = LinearAlgebra.inverse(MatrixToBeInverted);

I read that the .inverse() function is deprecated.
When using Apache Commons 2.4 with such code:
System.out.println(new org.apache.commons.math3.linear.LUDecomposition(
        MatrixUtils.createRealMatrix(MatrixToBeInverted)
        ).getSolver().getInverse());

I get such error:
Exception in thread "main" org.apache.commons.math3.linear.SingularMatrixException:     matrix is singular

at org.apache.commons.math3.linear.LUDecomposition$Solver.solve(LUDecomposition.java:335)

at org.apache.commons.math3.linear.LUDecomposition$Solver.getInverse(LUDecomposition.java:383)

at MatrixCalc.calculateMatrix(MatrixCalc.java:405)

at MatrixCalc.main(MatrixCalc.java:932)

But as a matter of fact I know that the Input matrix can be inverted.


text:
Q: Unable to send email with Mac Mail via Mailgun Beginning in July of 2015, I've been unable to send mail using the Mailgun SMTP server using Mac Mail. To add a Mailgun account, I go to Mail > Preferences and under Account Information > Outgoing Mail Server (SMTP)

I choose the Edit SMTP Server List option. I select the options shown in the images.

When I hit OK, the account description in the Outgoing Mail Server (SMTP) briefly changes so that the "(Offline)" suffix is removed, but then it is quickly added back and I can't send with that account.
As suggested by Mailgun at https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp,

I tried sending with swaks and was successful, though I had to change the password provided by Mailgun's example.

A: Go to: Connection Doctor in the Windows menu item...

Then enable the log, or select show details to see if anything in the log helps you to see what the issue is...


text:
Q: Process.StandardOutput.ReadToEnd() and extraneous newline chars I am trying to understand why, when I call the above function, I am getting hex 0D0A every 80th column on the output I am reading.
I have a powershell script, for testing that has two lines in it for brevity's sake:
$xmlSpew = "<IISAppPoolConfig><DefaultWebSite><ApplicationPoolName>DefaultAppPool</ApplicationPoolName></DefaultWebSite><AuthN>Basic</AuthN></IISAppPoolConfig>"
Write-Output $xmlSpew

I am calling the script using the Process object with ProcessStartInfo as follows:
var psi = new ProcessStartInfo
{
    WorkingDirectory = Path.GetDirectoryName(FileToRun),
    FileName = FileToRun,
    Arguments = Arguments,
    UseShellExecute = false,
    CreateNoWindow = true,
    RedirectStandardError = true,
    RedirectStandardOutput = true,
};

var process = new Process
{
    StartInfo = psi,
    EnableRaisingEvents = true,
};

FileToRun value is:
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe

Arguments value is:
-File "C:\Program Files\MyTest\MyProgInputs\read.d\IISAppPoolConfig.ps1"

The script runs fine and I get back exit code 0, but I have this mysterious (to me) 0D0A newline every 80th char in standard out that I capture using:
var Stdout = new List<string>;

...

Stdout.Add(process.StandardOutput.ReadToEnd());

This is wreaking havoc on my XML efforts once I have standard out stored in a string var. I expected to get exactly what I write to the stdout in the ps1 script, not the extra newline.
What am I missing? I've looked for others with this issue, but I have not found an answer. Hopefully it is not me being search-challenged.

A: Follow this P/Invoke method and set dwXCountChars to a very large value.  Don't forget to include STARTF_USECOUNTCHARS in the flags as well.

A: Final and tested resolution for now (because I need to ship something), is to have output from powershell come from the Write-Host cmdlet instead of Write-Output. The process for obtaining stdout remained the same as in my original post. Hope this helps others. Thanks for all the inputs.


text:
Q: R unnest with Sentence start and end positions New to R.
I am using tidytext::unnest_tokens to break down a long text into individual sentences using below
tidy_drugs <- drugstext.raw %>%
  unnest_tokens(sentence, Section, token="sentences")
So I get a data.frame with all the sentences converted into rows.
I would like to get the start and end positions for each sentence that is unnested from the long text.
Here is a sample of the long text file. It is from a drug label.
<< *6.1 Clinical Trial Experience
  Because clinical trials are conducted under widely varying conditions, adverse reaction rates observed in clinical trials of a drug cannot be directly compared to rates in the clinical trials of another drug and may not reflect the rates observed in practice.
 The data below reflect exposure to ARDECRETRIS as monotherapy in 327 patients with classical Hodgkin lymphoma (HL) and systemic anaplastic large cell lymphoma (sALCL), including 160 patients in two uncontrolled single-arm trials (Studies 1 and 2) and 167 patients in one placebo-controlled randomized trial (Study 3).
 In Studies 1 and 2, the most common adverse reactions were neutropenia, fatigue, nausea, anemia, cough, and vomiting.*

The desired result is a dataframe with three columns

A: You can do this with str_locate from stringr. This is mostly annoying because newlines and special characters can mess up regular expressions that you search with. Here we first remove newlines from the input text with str_replace_all, then unnest the tokens making sure to keep the original text and to prevent case change. Then, we make a new regex column, replacing special characters (here (, ), and .) with properly escaped versions, and use str_locate to add the start and end of each string.
I don't get the same numbers as you, but I copied the text from your code which doesn't always keep all characters, and your final end number is smaller than the start in any case.
library(tidyverse)
library(tidytext)

raw_text <- tibble(section = "6.1 Clinical Trial Experience
  Because clinical trials are conducted under widely varying conditions, adverse reaction rates observed in clinical trials of a drug cannot be directly compared to rates in the clinical trials of another drug and may not reflect the rates observed in practice.
                   The data below reflect exposure to ARDECRETRIS as monotherapy in 327 patients with classical Hodgkin lymphoma (HL) and systemic anaplastic large cell lymphoma (sALCL), including 160 patients in two uncontrolled single-arm trials (Studies 1 and 2) and 167 patients in one placebo-controlled randomized trial (Study 3).
                   In Studies 1 and 2, the most common adverse reactions were neutropenia, fatigue, nausea, anemia, cough, and vomiting."
)

tidy_text <- raw_text %>%
  mutate(section = str_replace_all(section, "\\n", "")) %>%
  unnest_tokens(
    output = sentence,
    input = section,
    token = "sentences",
    drop = FALSE,
    to_lower = FALSE
    ) %>%
  mutate(
    regex = str_replace_all(sentence, "\\(", "\\\\("),
    regex = str_replace_all(regex, "\\)", "\\\\)"),
    regex = str_replace_all(regex, "\\.", "\\\\.")
  ) %>%
  mutate(
    start = str_locate(section, regex)[, 1],
    end = str_locate(section, regex)[, 2]
  ) %>%
  select(sentence, start, end) %>%
  print()
#> # A tibble: 3 x 3
#>   sentence                                                     start   end
#>   <chr>                                                        <int> <int>
#> 1 6.1 Clinical Trial Experience  Because clinical trials are ~     1   290
#> 2 The data below reflect exposure to ARDECRETRIS as monothera~   310   626
#> 3 In Studies 1 and 2, the most common adverse reactions were ~   646   762

Created on 2018-02-23 by the reprex package (v0.2.0).


text:
Q: Unusual behaviour in UIAnimation of IOS I am moving a view upward to some offset multiple times. My code is here:
for i in 0..<10 {
    UIView.animate(withDuration: TimeInterval(duration), animations: {
        view.frame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y - offset, width: view.frame.size.width, height: view.frame.size.height)
    }) { (boolValue) in
        DispatchQueue.main.async {
                print("loop completed -- \(i)")
            }
    }
}

The problem is that "animation completed" is printing after outer loop completes (after 10 times), not just after that particular animation gets completed.
Means , when below code get executed after 10 times
UIView.animate(withDuration: TimeInterval(duration), animations: {
    view.frame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y - offset, width: view.frame.size.width, height: view.frame.size.height)
}) { (boolValue) in
    DispatchQueue.main.async {
        print("loop completed -- \(i)")
    }
}

then all completion block executes


text:
Q: Making windows form with CLR and C++ program So I have this project called "Detection" written in c++, the project is all set, it has class, function and of course a main function to call all the function and class written in Main.cpp . The problem is, when I want to make GUI using windows form with CLR for this project (that I already made earlier), the MyForm.cpp (default name for windows form) also has main function. So I have some question :

*

*How can I overload these main functions?

*If I can overload them, how can I called the main function in Main.cpp through a button? (after the button clicked, the program run)

I'am very sorry if my questions doesn't make sense because I'am new to CLR and C++. Thank you

A: The approach you take isn't the correct one. Look up how to write functions in c++.
There should be one main function in your programme. Other code should be written in an appropriately named function and called as per required; for eg :
public static void main(char[]args){
//initialisation codes only
}

public void onButtonClicked()
{
   //your button clicked code
   onPlaySound();
}

public void onPlaySound()
{
   //your play sound code
}


text:
Q: RegEx: Validating Alternate text for image I'm trying to set validation for an image alternate text, and here's what I think should be validated so far. It's a pretty simple RegEx, but I'm yet to start learning that topic..

*

*Double quotes

*< and > characters to prevent HTML input

Is there anything else you would add to this?
Would text length ever be an issue?
I appreciate your help and if someone could provide this simple RegEx I'd be really grateful :)

A: That sounds like a good place to start for me. Max size: pick something sane, unless you want it to be valid to post a dissertation as an alt text - though it is probably possible. As for the regex to validate it's okay:
/^[^"<>&\\]{0,XXX}$/

where XXX is the maximum size you want. Or get rid of the {0,XXX} altogether and replace it with * to mean "zero or more". Syntax depends on language, of course.
Also found this, looked interesting:
http://www.cs.tut.fi/~jkorpela/html/alt.html
Update:
Yeah, you two make a good point. As long as the quotes used around the alt-text aren't themselves single-quotes, then they should be fine.
And as per other answers below, possibly also & and . Though you may need to be careful with how many slashes, whether they are before things that matter. And also, whether   and such things are allowed in the text itself.


text:
Q: Python Echo Function I am currently learning about python functions.  In the book I'm reading "Introducing Python" it lists the below code as an example.  The purpose of the function is to simply output word twice.  I'm drawing a blank as to what I'm doing incorrectly.  This is not the only example in the book where I receive a syntax error.  I'm assuming it has something to do with my indentation?  Any help would be greatly appreciated.  Thank you in advance!
 >>> def echo(anything):
 ...     return anything '' anything
 ...
  File "<input>", line 2
    return anything '' anything
                 ^
 SyntaxError: invalid syntax

A: To get a list returned, do:
return any, '', any

If it is returning a list, you can stick it in separate variables with:
a,b,c = echo(anything)


text:
Q: Multiple arrays tensordot I've got list of np.arrays like:
l = [array([0.2,0.3,0.5]),array([0.7,0.3])]

What I need to get outer product:
array([[0.14, 0.06],
       [0.21, 0.09],
       [0.35, 0.15]])

in general way:
array([[l[0][0] * l[1][0], l[0][0] * l[1][1]],
       [l[0][1] * l[1][0], l[0][1] * l[1][1]],
       [l[0][2] * l[1][0], l[0][2] * l[1][1]]])

But for any length of l (>= 2), so when len(l) == 4, I'll got 4-dimensional array.
My current approach is to use tensordot in for loop:
product = np.tensordot(l[0], l[1], 0)
for i in range(2, len(l)):
    product = np.tensordot(product, l[i], 0)

But I'm used that in Python code looks nicer. Have anybody some idea how to do nicer and faster solution?
The motive is that I need to get sum of element-wise multiplied two arrays:
result = np.sum(arr * product)

where arr.shape == product.shape. Maybe you, clever guys, can improve it also.

A: Perhaps more concise is:
reduce(lambda x, y: tensordot(x, y, 0), l)

A: numpy has a great thing called broadcasting, where it iterates through the arrays. so if you have an array that is x by 1 and multiply it by an array that is 1 by y, you'll get an x by y array. works just like matrices. So I am going to do everything you want in just 2 lines:
result = np.array((l[0])).reshape((1,len(l[0])))# resizing the first column to make it a 3 by 1 so that numpy broadcasting will work.
print result * l[1] # broadcasting the 3 by 1 by a 1 by 2 to result in your 3 by 2

And there you have it! quick and easy! I am going to put the entire code below for your convenience:
import numpy as np
l = [([0.2,0.3,0.5]),([0.7,0.3])]
result = np.array((l[0])).reshape((len(l[0]),1))
print result * l[1]
>>>>aray([[ 0.14  0.06]
 [ 0.21  0.09]
 [ 0.35  0.15]])


text:
Q: PHP MySQL query What is wrong in this code?

$sql = "SELECT * FROM blogs WHERE blog_id = $'blog_id'";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$content = $rows['blog_content'];

echo $content;

The error is : Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Program Files\xampp\htdocs\jordan_pagaduan\blog_delete_edit.php on line 3.

A: You should be using:
$sql = "SELECT * FROM blogs WHERE blog_id = '$blog_id'";

Since it is never too early to start reading about best practices, note that for public websites it is really dangerous to include any un-sanitized input into an SQL query, as you appear to be doing. You may want to read further on this topic from the following Stack Overflow posts:

*

*XKCD sql injection - please explain (with pictures!)

*What is SQL injection?

*Is SQL injection a risk today?

*SQL Injection Topics on Stack Overflow

A: The first line should read:
$sql = "SELECT * FROM blogs WHERE blog_id = '$blog_id'";
(move the $ to inside the single quotes)

A: $sql = "SELECT * FROM blogs WHERE blog_id = '$blog_id'";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$content = $rows['blog_content'];

A: You need to put the $ symbol in your quotes.
Instead of this:
$sql = "SELECT * FROM blogs WHERE blog_id = $'blog_id'";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$content = $rows['blog_content'];

echo $content;

Write this:
$sql = "SELECT * FROM blogs WHERE blog_id = '$blog_id'";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$content = $rows['blog_content'];

echo $content;


text:
Q: Cannot mock the RedisClient class - method pipeline overrides nothing I have a CacheService class that uses an instance of the scala-redis library
class CacheService(redisClient: RedisClient) extend HealthCheck {
  private val client = redisClient

  override def health: Future[ServiceHealth] = {
    client.info
    ...
  }

In my unit test, I'm mocking the client instance and testing the service
class CacheServiceSpec extends AsyncFlatSpec with AsyncMockFactory {
  val clientMock = mock[RedisClient]
  val service = new CacheService(clientMock)

  "A cache service" must "return a successful future when healthy" in {
    (clientMock.info _).expects().returns(Option("blah"))

    service.health map {
      health => assert(health.status == ServiceStatus.Running)
    }
  }
}

yet I'm getting this compilation error
Error:(10, 24) method pipeline overrides nothing.
Note: the super classes of <$anon: com.redis.RedisClient> contain the following, non final members named pipeline:
def pipeline(f: PipelineClient => Any): Option[List[Any]]
  val clientMock = mock[RedisClient]

My research so far indicates ScalaMock 4 is NOT capable of mocking companion objects. The author suggests refactoring the code with Dependency Injection.

*

*Am I doing DI correctly (I chose constructor args injection since our codebase is still relatively small and straightforward)? Seems like the author is suggesting putting a wrapper over the client instance. If so, I'm looking for an idiomatic approach.

*Should I bother with swapping out for another redis library? The libraries being actively maintained, per redis.io's suggestion, use companion objects as well. I personally think this is is not a problem of these libraries.

I'd appreciate any further recommendations. My goal here is to create a health check for our external services (redis, postgres database, emailing and more) that is at least testable. Criticism is welcomed since I'm still new to the Scala ecosystem.

A:
Am I doing DI correctly (I chose constructor args injection since our
  codebase is still relatively small and straightforward)? Seems like
  the author is suggesting putting a wrapper over the client instance.
  If so, I'm looking for an idiomatic approach.

Yes, you are right and this seems to be a known issue(link1). Ideally, there needs to a wrapper around the client instance. One approach could be to create a trait that has a method say connect and extend it to RedisCacheDao and implement the connect method to give you the client instance whenever you require. Then, all you have to do is to mock this connection interface and you will be able to test.
Another approach could be to use embedded redis for unit testing though usually, it is used for integration testing.You can start a simple redis server where the tests are running via code and close it once the testing is done.

Should I bother with swapping out for another redis library? The
  libraries being actively maintained, per redis.io's suggestion, use
  companion objects as well. I personally think this is is not a problem
  of these libraries.

You can certainly do that. I would prefer Jedis as it is easy and it's performance is better than scala-redis(while performing mget).
Let me know if it helps!!


text:
Q: How does react-router persist location state over page refreshes? I am just so very confused.
I have a workflow where someone can start to fill out a form for a product. It is a long form and I want to save progress to the server as they type (but not until they fill it out for a bit). So we start at a url for creating the form, after they've typed for a bit, we POST to create a resource on the server, and after the request finishes, we update the url to the edit route with the new id.
In other words, you start filling out the form at url /product then after you've filled it out for a bit the url shifts to /product/123. After that, loading that URL gives you your form.
So basically I have
<Route path={`/product`} exact component={CreateProduct} />

and
<Route exact={true} path="/product/:productId" render={({
      match: {params: {productId}},
      location: {state: {data}={}}
  }) => (
    <EditProduct productId={productId} initialData={data}
  )} />

See that state? That's because the way I do the switch over from create to edit mode is something like this
const id = await apiFetch(`/api/product`, data, {method: `POST`})
this.props.history.push({pathname: `/product/${id}`, state: {data} })

in the constructor of my <EditProduct> component I have
constructor({productId, initialData}) {
   this.super()
   this.state = {}
   if(initialData)
     this.setState({data: initialData})
   else
     getProduct(productId).then(({data}) => this.setState({data}))
}

By doing that, the initial data into the <EditProduct> is seeded from the <CreateProduct> component and I don't need to reload it from the server or anything.
This works, the transition is smooth, the url updates, and everything is hunky dory.
I can now continue editing the <EditProduct> component and it saves properly. I can open a new tab to the same url and it loads everything up and I can continue. This happens because in that situation initialData is undefined so it's loaded from the server. yay!
BUT
If I instead refresh the original tab things get weird. Any changes that have accumulated since the save are lost. Drilling down in the debugger I see the issue is that initialData passed from the location.state.data object is not empty - it is the initial object from when the product was first created.
So where on earth does it come from? I just did a full page refresh (even a "hard" refresh with no cache and devtools open). That data isn't in the URL (and in fact copy pasting the url into another tab in the same window doesn't have this issue).
The only mechanism I'm aware of that can persist data across refreshes but not to new tabs like this is sessionStorage, yet when I check it in the console, I am told
> sessionStorage
< Storage {length: 0}

I've even thought that maybe react-router is manipulating session storage just before the page unloads and just after it loads, but breaking on the first line of my javascript bundle shows the exact same thing.
So how on earth is this persistence happening!?

A: I believe the asker already resolve this problem, the answer is buried in the comment though.
The question is actually down to this:
Where the state come from when the user reloads the page? And state  refers to props.location.state provided by react-router
TLDR; the state is not a plain javascript implementation, it is bound to the browser environment.
The BroswerRouter of react-router use the underlying native broswer history API directly so the history API is bound to the platform, you can not predict its behavior based on the normal rule.
Here is the special part:

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser

Most of the users treat the state as a plain javascript, so there is a problem

A: I had a very similar problem, and the same confusion.
Solved it with window.history.replaceState()
I had a simple search form which redirected to a second page, and used the location state from the router to repopulate the search input on the second page.
In myse case, this happened:

*

*Search for "foo" on the first page -> Get redirected to the second page, and see search+results for "foo".

*Search for "bar" on the second page. -> See results for "bar".

*Hit refresh. Expectation? Either an empty search bar, or search+results for "bar". -> Instead, see search+results for "foo" (??)

I solved this by making it so that every time the user does a search on the second page, I replace the state using window.history.replaceState with the correct search term. This way a refresh gives the user the expected search. Replacing the state with an empty object on each search from the second page worked fine as well, giving the user an empty search on each refresh.


text:
Q: Finding the number of automorphisms in $G_{\Bbb{Q}(\sqrt[4]{2},i),\Bbb{Q}}$? I am trying to solve the following problem:

Given $K$, the splitting field of $x^4-2$ over $\Bbb{Q}$, consider $\sigma,\tau\in G_{K / \Bbb{Q}}$ such that
$$\sigma(\sqrt[4]{2})=\sqrt[4]{2}i\hspace{2cm} \sigma(i)=i\hspace{2cm}\tau(\sqrt[4]{2})=\sqrt[4]{2} \hspace{2cm}\tau(i)=-i$$
Show that $|\sigma|=4$ and $|\tau|=2$.

I think we must count all the $\Bbb{Q}$-automorphisms $\sigma, \tau$ with the given conditions, is that correct? I tried to write the expression for the elements in $K$:
$$a+b\sqrt[4]{2}+c\sqrt[4]{2}^2+d\sqrt[4]{2}^3+ei+fi\sqrt[4]{2}+gi\sqrt[4]{2}^2+hi\sqrt[4]{2}^3$$
And check for  the automorphisms but this looks a bit unwieldy. Is there a more practical way to do it? I suspect there is because the $\sigma$ and $\tau$ looks a bit specific and I have found before that $K=\Bbb{Q}(\sqrt[4]{2},i)$ and $2,4$ are the degrees of the extensions. I have also seen other similar questions to mine but they don't seem to address exactly what I am looking for.

A: The question gives you two specific automorphisms $\sigma, \tau\in\textrm{Gal} (K/\mathbb{Q}) $ and asks you to verify their order (as members of the Galois group).
Since you already know that $K=\mathbb {Q} (\sqrt[4]{2},i)$, observe that any automorphism in $\textrm{Gal} (K /\mathbb {Q}) $ is determined / specified by its action on just these two members $i, \sqrt [4]{2}$. Whenever the field is specified like $K=F(a_1,a_2,\dots,a_n)$ you don't need to check all members of $K$ (as you have tried in question by expressing in terms of a basis) for guessing any automorphism. It is just sufficient to check for the members $a_i$.
You are trying to interpret the question as if we need to find (and count) automorphisms which have properties like $\sigma, \tau$. No! Those properties determine $\sigma, \tau $ uniquely as explained in previous paragraph.
Finding order of $\sigma, \tau$ is rather straightforward. Just keep on applying $\sigma$ (similarly for $\tau $) to both $i, \sqrt[4]{2}$ and see when you get the identity map.
Thus $$\sigma^2(\sqrt[4]{2})=\sigma(\sigma(\sqrt[4]{2}))=\sigma(i\sqrt [4]{2})=\sigma(i)\sigma(\sqrt[4]{2})=i^2\sqrt[4]{2}$$ and in general $\sigma^n(\sqrt [4]{2})=i^n\sqrt[4]{2}$. Further $\sigma^n(i) =i$. Thus we see that $\sigma^4$ is the identity map so that $|\sigma|=4$ and in a like manner you can show that $|\tau|=2$.

A: Letting $K=\mathbf Q(i,\sqrt [4] 2)=$ your splitting field and $k=\mathbf Q (i)$, it's easier to determine the whole Galois group $G=G(K/\mathbf Q)$ without using brute force. Noting that $i$ is a primitive 4th root of unity, Kummer theory tells you that $G(K/k)$ is cyclic of order 4, generated by your $\sigma$ (even if you don't know about Kummer, it's easy here to keep track of the action of $\sigma$ and use the bound $[K:k]\le 4$ to conclude). In the same vein, introduce the subextension $k'=\mathbf Q (\sqrt [4] 2)$. Because $k'$ is totally real and $i$ is imaginary, it's immediate that $G(K/k')$ is cyclic of order 2, generated by $\tau$. By the same token, you get the bonus that $G$ is generated by $\sigma$ and $\tau$. Subsidiary question: is $G$ isomorphic to $D_8$ or $H_8$ ?


text:
Q: django-tables2 sorting non-queryset data Hi I have a table thus:
class MyTable(tables.Table):

    brand = tables.Column(verbose_name='Brand')
    market = tables.Column(verbose_name='Market')
    date = tables.DateColumn(format='d/m/Y')
    value = tables.Column(verbose_name='Value')

I'm populating the table with a list of dicts and then I'm configuring it and rendering it in my view in the usual django-tables2 way:
data = [
    {'brand': 'Nike', 'market': 'UK', 'date': <datetime obj>, 'value': 100},
    {'brand': 'Django', 'market': 'FR', 'date': <datetime obj>, 'value': 100},
]

table = MyTable(data)

RequestConfig(request, paginate=False).configure(table)

context = {'table': table}

return render(request, 'my_tmp.html', context)

This all renders the table nicely with the correct data in it. However, I can sort by the date column and the value column on the webpage, but not by the brand and market. So it seems non-string values can be sorted but strings can't. I've been trying to figure out how to do this sorting, is it possible with non-queryset data?
I can't populate the table with a queryset, as I'm using custom methods to generate the value column data. Any help appreciated! I guess I need to specify the order_by parameter in my tables.Column but haven't found the correct setting yet.

A: data.sort(key = lambda item: item["brand"].lower()) will sort the list in place (so it will return None; the original 'data' list is edited) based on brand (alphabetically). The same can be done for any key.
Alternatively, sorted(data, key = lambda item: item["brand"].lower()) returns a sorted copy of the list.


text:
Q: Shell Script won't fail in Jenkins I have a simple shell script which I want to set up as a periodic Jenkins job rather than a cronjob for visibility and usability for less experienced users.
Here is the script:
#!/bin/bash
outputfile=/opt/jhc/streaming/check_error_output.txt

if [ "grep -sq 'Unable' $outputfile" == "0" ]; then
    echo -e "ERROR MESSAGE FOUND\n"
    exit 1
else
    echo -e "NO ERROR MESSAGES HAVE BEEN FOUND\n"
    exit 0
fi

My script will always return "NO ERROR MESSAGES HAVE BEEN FOUND" regardless of whether or not 'Unable' is in $outputfile, what am I doing wrong?
I also need my Jenkins job to class this as a success if 'Unable' isn't found (e.g. If script returns "0" then pass, everything else is fail)

A: Execute the grep command and check the exit status instead:
#!/bin/bash
outputfile=/opt/jhc/streaming/check_error_output.txt
grep -sq 'Unable' $outputfile
if [ "$?" == "0" ]; then
    echo -e "ERROR MESSAGE FOUND\n"
    exit 1
else
    echo -e "NO ERROR MESSAGES HAVE BEEN FOUND\n"
    exit 0
fi

A: You are comparing two different strings. The outcome will always be false, i.e. the else part is taken.
Also, no need to explicitly query the status code. Do it like this:
if grep -sq 'Unable' $outputfile
then
  ....
else
  ....
fi


text:
Q: Can't save() the same doc multiple times in parallel and Operation `users.insertOne()` buffering timed out after 10000ms This is my router code :
router.post('/users/register',async (req,res) => {
       console.log(req.body);
       const user = new User(req.body);
       try{
          await user.save(function(err){
             if (err) {
               console.log(err);
             }
          });
          const token = await user.generateAuthToken();
          res.redirect('/');
       }catch(e){
          console.log(e);
          res.status(400).send(e);
       }

});

Generate Token Code :
userSchema.methods.generateAuthToken = async function() {
   const user = this;
   const token = jwt.sign({ _id : user._id.toString() },process.env.JWT_SECRET_CODE);
   user.tokens = user.tokens.concat({token});
   await user.save();
   return token;
}

user saving code:
userSchema.pre('save', async function (next){
   const user = this;
   if(user.isModified('password')){
      user.password = await bcrypt.hash(user.password,8);
   }
   next();
});

Error :
ParallelSaveError: Can't save() the same doc multiple times in parallel. Document: 61109ecdc48220245c0ecaf7
    at model.Model.save
    at model.userSchema.methods.generateAuthToken

MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous>

This is the data I'm sending to mongo database :
{
  name: 'sdhfie',
  username: 'eifh_2397',
  email: 'example@gmail.com',
  phone: '+918329389241',
  password: 'sdfieu@92734',
  'repeat-password': 'sdfieu@92734'
}

I consoled the data and Data is sent but user is not saved.
I had tried most of the solutions available on stackoverflow but nothing worked in case of mine. Please try helping me out.

A: You are currently mixing async and callback. Try updating POST handler to remove the callback function from save():
router.post('/users/register', async (req,res) => {
       console.log(req.body);
       const user = new User(req.body);
       try {
          await user.save();
          const token = await user.generateAuthToken();
          res.redirect('/');
       } catch(e){
          console.log(e);
          res.status(400).send(e);
       }

});

Hopefully that helps!


text:
Q: How to ignore type while Deserialization using Newtonsoft.Json I am trying to Deserialize json data which i have to with respect to model class i have
Json :
"{'test':'1339886'}"

Classes :
public class NewtonTest
    {
        public Element test { get; set; }
    }
public class Element
    {
        public string sample { get; set; }
    }

In Main class :
//under Main
string jsonData =  "{'test':'1339886'}";
var  = JsonConvert.DeserializeObject<NewtonTest>(jsonData);

Error Info : //innner exception
Could not cast or convert from System.String to Test.Element."
I am completely aware of what the error states as i am passing string in my json where as in class i have a class as type(mismatch happening) .
In such cases i need to handle the error and maybe place a null if there is mismatch in output but it should not throw exception .
I tried my best reading the docs and setting options via settings but none seem to work .
I am using version 4.5 of Newtonsoft.Json

A: You can tell JSON.NET to ignore errors for specific members and types:
var settings = new JsonSerializerSettings
{
    Error = (sender, args) =>
    {
        if (object.Equals(args.ErrorContext.Member, "test") &&
            args.ErrorContext.OriginalObject.GetType() == typeof(NewtonTest))
        {
            args.ErrorContext.Handled = true;
        }
    }
};

NewtonTest test = JsonConvert.DeserializeObject<NewtonTest>(json, settings);

This code won't throw an exception. The Error handler in the settings object will get called and if the member throwing the exception is named "test" and belongs to NewtonTest, the error gets skipped over and JSON.NET keeps going.
The ErrorContext property also has other properties that you might want to leverage to only handle errors that you're absolutely sure you want to ignore.

A: If you want a work around while using the badly formed json data.
Here is a simple solution that works.
 public static class NewtonHelpers
{
    internal class NewtonHelper
    {
        public string test { get; set; }
    }

    public static NewtonTest BuildNewton(string jsonData)
    {
        var newtonHelper = JsonConvert.DeserializeObject<NewtonHelper>(jsonData);

        var newtonTest = new NewtonTest { test = { sample = newtonHelper.test } };

        return newtonTest;
    }
}

Which can be used like
var testdata = "{'test':'1339886'}";
var newNewton = NewtonHelpers.BuildNewton(testdata);


text:
Q: Ask a question about the definition of trace norm. Suppose $X\in \mathbb{R}^{M\times N}$
$\|X\|_*=\mathrm{trace}(\sqrt{X^*X})=\sum_i^{\min{M,N}}\sigma_i$
where $\sigma_i$ is the singular values of $X$.
I know that $\mathrm{trace}({X^*X})=\sum_i^{\min{M,N}}\sigma_i^2$. Thus, the following equation holds.
$\sqrt{\mathrm{trace}({X^*X})}=\sqrt{\sum_i^{\min{M,N}}\sigma_i^2}$.
But I wonder how to prove $\mathrm{trace}(\sqrt{X^*X})=\sum_i^{\min{M,N}}\sigma_i$

A: Let $X = U \Sigma V^*$, where $U$ and $V$ are unitary and $\Sigma$ is nonnegative real diagonal, be an SVD of $X$. Then
$$X^*X = V \Sigma^2 V^*,$$
so
$$\sqrt{X^*X} = V \sqrt{\Sigma^2} V^* = V \Sigma V^*,$$
Notice that this is a similarity relation, so
$$\operatorname{tr} \sqrt{X^*X} = \operatorname{tr} (V \Sigma V^*) = \operatorname{tr} \Sigma.$$


text:
Q: How do I access a table that has a composite key I can't model using Code First? I have an existing database that I cannot change, but want to access using EF. For 90% of the database, I have been able to get Code First EF to work, and I am very impressed.
I've run into a case that I am wondering how to model or access the data through a navigation property.
In one case, the tables are like this (this example is totally made up, but represents the problem):
CREATE TABLE Dog (
    id            INTEGER      PRIMARY KEY,
    name          VARCHAR(50)  NULL,
    breed_id      INTEGER      NOT NULL
);

CREATE TABLE Breed (
    id               INTEGER      NOT NULL,
    organization_id  INTEGER      NOT NULL,
    description      VARCHAR(100) NOT NULL,
    Primary key (id, organization)
);

CREATE TABLE Organization (
    id            INTEGER      PRIMARY KEY,
    description   VARCHAR(100) NOT NULL
);

In Table breed, the organization represents an organization that has defined a breed. A dog can have several breeds, but the program only displays one, the results being 'filtered' by the organization id - which is a value that is configured when the program is set up.
An example of the data that might be present is this:
id    organizationID    Description
 1                 1    Basset Hound
 2                 1    Great Dane
 2                 2    Grande Dane

Where organization 2 has chosen to call the breed something different than organization 1.  The unique primary key is a combination of id and organizationID.  A dog has a breed, but  does not have a property to define one or more associated organizations.  It takes additional information from another table, or a configured value (perhaps an enumerated value) to find the breed of a dog.
In my case, to find a particular dog breed, you have to have a dog id and another piece of information (organization_id) which is related to program configuration.
The dog, breed and organization classes look like this:
public class Dog {
  public int id  { get; set; };
  public string name  { get; set; };
  public int breedID  { get; set; };

  public virtual Breed { get; set; }
}

public class Breed {
  public int id  { get; set; };
  public int organizationID  { get; set; };
  public string description  { get; set; };

  public virtual Organization { get; set; }
}

public class Organization {
  public int id  { get; set; };
  public string description  { get; set; };
}

As seen in the code, I'd like to use a "Navigation" Property on Dog that returns a breed, but don't think I can configure this in code first.
I've tried a few different things (in fluent API, and leaving organization out - since that's easy) and will also document things I don't think work:
1)
   modelBuilder.Entity<Dog>().HasKey(t => t.id);
   modelBuilder.Entity<Breed>().HasKey(t => t.id);
   modelBuilder.Entity<Dog>().HasRequired(d => d.Breed).WithMany().HasForeignKey(d => d.breedID);

Of course, the problem with this is that more than one breed will be returned and entity framework will throw an exception because the breedID itself is insufficient to yield a single value - which the model is calling for.
2)
   Change class dog:
      Remove:
          public virtual Breed { get; set; }
      Add:
          public virtual ICollection<Breed> Breeds { get; set; }

          public Breed Breed {
            get {
              // Assume 1 is configured organization value
              return Breeds.Single(t => t.OrganizationId == 1);
            };
            set {
              Breeds.Add(value);
            }
          }

     Change model:
        I don't know how to do this for the given classes.  Since it's a Collection, it must look something like

        modelBuilder.Entity<Dog>().HasMany(d => d.Breeds)...

        but I don't see how to specify that breedID is a foriegn key into the breed table.

If I could get the model to work, the rest will work, but it does seem wierd and inefficient.
 3)
    Change model to account for composite key (using first set of classes):
       modelBuilder.Entity<Breed>().HasKey(b => new { b.id, b.organizationId });

       modelBuilder.Entity<Dog>().HasRequired(t => t.Breed).WithMany().HasForeignKey(t => new { t.breedID, configuredValue });

I don't know how to "inject" configuredValue as in the last line, so this doesn't work either.
If none of the above methods work, or if I can't find another way to configure code first properly, then I'd like to specify that when the Breed navigation property getter is called, it should use a query that can get the appropriate breed and return it appropriately.
However, I don't want to dirty my POCO with the Context calls to return the result of the query. In other words, I'd like to have a property on Dog that does NOT look something like this:
public Breed Breed {
   get {
      return context.Breed.Where(b => b.id == this.id && b.organizationID == 1).Single();
   }
}

Ideally, it would work like the Navigation collections do, where EF does it's magic and returns the appropriate results.
Intuitively, it seems like I should be able to either configure this using POCO-like code or use/extend a proxy to extend the configuration to use the particular query I want when the accessor is called. Or - it seems like I ought to be able to populate the property on any read and dirty the POCO on write. I'm just not familiar enough with EF to know how to do this.
Is this possible?
As an addition to the first post, because I desire to keep my POCO classes clean, I think I will probably implement the Repository pattern to encapsulate the complex queries like the ones I've described, as well as support other operations also.
Looking at the EDMX that I've generated from my Code First model, it's not apparent how to implement the model from a database first perspective, either.
Any thoughts are greatly appreciated.

A: In short, you can't do that. You have illogical database structure (foreign key referencing non-unique column), you'll have to map it somewhere. You can't do that in EF configuration, because it's dynamic, so you'll have to do that inside you entity classes. And I see no ways to do that without direct call to context inside your entity class (or helper class).


text:
Q: is_dir returns false when remote debugging from PHPStorm Im running some remote debugging using PHPStorm on PHPUnit tests and I've run into a bit of a problem.
Everything runs fine, but when I try to run is_dir it returns false on a relative path, where when it is run from the command line it returns true.
is_dir("/path/to/files");

I assume that for some reason, although PHPStorm understands the file structure, for some reason PHP is not understanding it.
When runniing from PHPStorm, the following values are printing:
getcwd()
/var/www/html/MinuteByMinuteBundle/Tests/Services/Crunch

$path
src/MinuteByMinuteBundleTest

When running from the command line, the following values are different:
getcwd()
/Users/user/dev/

A: It turns out that PHPStorm has an option to set a custom working directory when specifying a test to run.
Go to Run -> edit configurations -> [your test]
Changed the custom working directory to match that being output by the terminal run:
/Users/user/dev


text:
Q: Getting "this class is not key value coding-compliant" when trying to perform NSPredicate in Swift 4 Whenever I try and use an NSPredicate it errors out saying:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Project.Object 0x7fc805c23770> valueForUndefinedKey:]: this class is not key value coding-compliant for the key happyfacevalue.'

Now I can't figure out why it refuses to work. I even tried initializing the array I want with @objc and it still crashes.
I understand that the filter feature works incredibly easy, but I need to be able to use NSCompoundPredicate. I don't think I can achieve the level of detailed searching with the Filter feature, that I can with an NSCompoundPredicate.
    let tempPredStr = model.selectionQueryArray[count + 1] + "==" + model.inputQueryArray[count + 1]

    let predicate = NSPredicate(format: tempPredStr, NSNumber(value: false))
    arrayOfPredicates.append(predicate)

    /*
    let predicateIsNumber = NSPredicate(format: "isStringOrNumber == %@", NSNumber(value: false))
    let predicateIsEnabled = NSPredicate(format: "isEnabled == %@", NSNumber(value: true))
     */
    count = count + 1
}

let andPredicate = NSCompoundPredicate(type: .and, subpredicates: arrayOfPredicates)

let filteredArray = (predicateArray as NSArray).filtered(using: andPredicate)

I want it to just predicate using the pre-built predicates and to produce an array of objects.


text:
Q: NSString or UILabel with a backslash through a letter Is it possible to make certain letters in a word have a slash through it? I have a tableview with a list of words, and I want to draw a slash through "silent letters"
What would be the best way to approach creating UILabel's to look like this?

A: I guess the best would be to not use UILabel at all.
Create your own UIView subclass, override drawRect and draw the text. Then draw the lines over letters. If you have the font and the text, calculating the position for the line is pretty trivial.


text:
Q: Specflow :Could not load file or assembly TechTalk.SpecFlow, Version=2.2.0.0 I know this question is asked so many times but it is always difficult to updgrade Specflow from one version to another. Can anyone help in resolving below error while upgrading to 2.2.0.0 from 1.9.0 .
Could not load type 'TechTalk.SpecFlow.Infrastructure.RuntimePluginAttribute' from assembly 'TechTalk.SpecFlow, Version=2.2.0.0, Culture=neutral, PublicKeyToken=0778194805d6db41'. Automation

I'v tried to follow this thread Techtalk.Specflow error: Could not load assembly file or assembly by putting Old version as "1.9.0.77"   and "1.9.0.0" but still no luck. Also tried to delete all packages from solution then from Temp folder and tried to load all . Also tried to uninstall Specflow .
Using VS 2015
can anyone help with it ?

A: Finally able to resolve the issue .
Solution is : Once you upgrade the Specflow to any versions , make sure Specflow for Visual studio Extension is Enabled. As in my case it was not Enabled (Got disabled in the process of Upgrade) and all errors were Occurring .


text:
Q: Examples illustrating the difference between closed and bounded sets. Intuitively for me, it seems as if closed sets are bounded, especially considering closed sets contain all limit points. But I know this isn't the case, because $ℝ$ is closed (and open) and is not bounded.
Is this the only case of a closed set not being bounded? Can anyone provide an example that further illustrates the difference between closed and bounded?

A: $$\{x\in\mathbb R\mid x\geq 0\}$$
Also note that there are bounded sets which are not closed, for examples $\mathbb Q\cap[0,1]$.

A: In $\mathbb R^n$ every non-compact closed set is unbounded.

A: We cover each of the four possibilities below.
Closed and bounded: $[0,1]$
Closed and not bounded: $\cup_{n\in Z}[2n,2n+1]$
Bounded and not closed: $(0,1)$
Not closed and not bounded: $\cup_{n\in Z}(2n,2n+1)$

A: The integers as a subset of $\Bbb R$ are closed but not bounded.


text:
Q: Split a table in access I feel like this should be an easy question for someone to answer however despite my numerous searches I have not been able to find an answer  (probably due to lack of dB knowledge).
The problem:  I am building a research dB related to clinical examinations. I have created a main table and a couple of additional tables which have one to many relationships to the main (think, mulitple findings documented in one examination etc.  I have successfully been able to create a Main form with two embedded subforms. This functions as expected.
What I would like to do is break the Main table up into a three individual tables where there are logical differences between groups of fields. This will make the dB easier to revise later on and it will make it easier to find fields.
I would like a record to be created in the two related tables every time i create a record in the first table but I cannot work out how to acheive this.  When I go into the form I would like checkboxes from all three tables displayed and editable on the same page and kept in sync by the RecordID of the main table.
Any help or direction to an example dB would be greatly appreciated.
Regards,
James


text:
Q: Facing Issue while creating Custom User Store Manager [WSO2 API Manager 1.9.1] I am totally new to WSO2. I have to create custom user store manger using wso2 api manager. While some word around I am facing an exception as,
TID: [0] [AM] [2016-01-14 16:19:57,732]  INFO {org.wso2.carbon.databridge.agent.thrift.AgentHolder} -  Agent created !    {org.wso2.carbon.databridge.agent.thrift.AgentHolder}
TID: [0] [AM] [2016-01-14 16:19:57,736]  INFO {org.wso2.carbon.databridge.agent.thrift.internal.AgentDS} -  Successfully deployed Agent Client {org.wso2.carbon.databridge.agent.thrift.internal.AgentDS}
TID: [0] [AM] [2016-01-14 16:19:59,608] ERROR {org.wso2.carbon.user.core.common.DefaultRealmService} -  Cannot initialize the realm. {org.wso2.carbon.user.core.common.DefaultRealmService}
org.wso2.carbon.user.core.UserStoreException: org.wso2.sample.user.store.manager.CustomUserStoreManagerType class java.lang.ClassNotFoundException
I have updated user-mgt.xml as,
 <UserStoreManager class="org.wso2.sample.user.store.manager.CustomUserStoreManager">
        <Property name="TenantManager">org.wso2.carbon.user.core.tenant.JDBCTenantManager</Property>
    <Property name="ReadOnly">false</Property>
        <Property name="MaxUserNameListLength">100</Property>
        <Property name="IsEmailUserName">false</Property>
        <Property name="DomainCalculation">default</Property>
        <Property name="PasswordDigest">SHA-256</Property>
        <Property name="StoreSaltedPassword">true</Property>
        <Property name="ReadGroups">true</Property>
    <Property name="WriteGroups">true</Property>
        <Property name="UserNameUniqueAcrossTenants">false</Property>
        <Property name="PasswordJavaRegEx">^[\S]{5,30}$</Property>
        <Property name="PasswordJavaScriptRegEx">^[\S]{5,30}$</Property>
    <Property name="UsernameJavaRegEx">^[^~!#$;%^*+={}\\|\\\\<>,\'\"]{3,30}$</Property>
    <Property name="UsernameJavaScriptRegEx">^[\S]{3,30}$</Property>
    <Property name="RolenameJavaRegEx">^[^~!#$;%^*+={}\\|\\\\<>,\'\"]{3,30}$</Property>
    <Property name="RolenameJavaScriptRegEx">^[\S]{3,30}$</Property>
        <Property name="UserRolesCacheEnabled">true</Property>
        <Property name="MaxRoleNameListLength">100</Property>
        <Property name="MaxUserNameListLength">100</Property>
    <Property name="SharedGroupEnabled">false</Property>
        <Property name="SCIMEnabled">false</Property>
    </UserStoreManager>

I have also registered service as,
Public class CustomUserStoreMgtDSComponent{
 private static Log log = LogFactory.getLog(CustomUserStoreMgtDSComponent.class);
 private static RealmService realmService;

    protected void activate(ComponentContext ctxt) {
        log.info("Custome Component activated..");
        CustomUserStoreManager customUserStoreManager = new CustomUserStoreManager();
        ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), customUserStoreManager, null);
        log.info("CustomUserStoreManager bundle activated successfully..");
    }

    protected void deactivate(ComponentContext ctxt) {
        if (log.isDebugEnabled()) {
            log.debug("Custom User Store Manager is deactivated ");
        }
    }

    protected void setRealmService(RealmService rlmService) {
          realmService = rlmService;
    }

    protected void unsetRealmService(RealmService realmService) {
        realmService = null;
    }

}
I have also added sample-store.jar inside dropins folder.
Is there any reference guide/link to create custom user store manager through wso2 api manager?
Any help would be highly appreciable.


text:
Q: EC2 Instance will not stop or terminate after trying to create an AMI from the running instance After a routine reboot of a Linux ec2 instance with 1 small root volume and 1 small attached volume I was not able to ssh into the instance.  It is not clear why rebooting the instance caused it to be inaccessible from ssh.  The instance showed as running in the AWS console but ssh, http,etc was not responsive.  I tried to create an AMI from this running instance.  However, the AMI was never created.  Instead I just saw "pending" in the AMI section of the AWS console for hours.  Eventually I de-registered the AMI.  Next I tried to stop the ec2 instance.  However I am not able to stop the instance - it has been stuck in the stopping state for hours. I also tried force stopping the instance with no success.  I then tried to detach the volumes but they constantly report "detaching"  Does anyone have any suggestions about how to handle this?  It seems that Amazon does not offer any kind of email or phone support unless you are a premium member.  Thanks very much for your help.

A: I know this post is old, but you can also click stop again, and the dashboard will ask you if you want to do a forced stop. Sometimes, I know this from experience, you have to do two or three forced stops to get it to work.
Credit to Robin Scott.

A: If you don't have premium support, then "stuck" instances (where you can't stop/terminate them) and "stuck" volumes (where you can't detach/delete them) can be reported to Amazon on the EC2 forum:

Amazon AWS EC2 Forum
https://forums.aws.amazon.com/forum.jspa?forumID=30

Make sure you list the specific instance/volume ids involved.
Nobody but Amazon can really help in these situations.
Fortunately, you should not be charged for instance hours once it enters the "stopping" or "terminating" state.
Your original problem about not being able to connect to the instance through ssh could also be posted on the EC2 forum for help from the community, but it is a common problem and has many potential causes.  I've written an article to help start diagnose this and to point out pieces of information you should include in your forum post:

Solving: "I can't connect to my server on Amazon EC2"
http://alestic.com/2009/08/ec2-connectivity

I've also written an article describing a method that can be used to diagnose EBS boot instances by looking at the log files on the disk even if you can't connect to the instance:

Fixing Files on the Root EBS Volume of an EC2 Instance
http://alestic.com/2011/02/ec2-fix-ebs-root

However, you won't be able to use this approach until Amazon helps you detach your EBS volume.

A: I ran into a related situation after I created an Elastic Beanstalk environment within an ec2 instance. To terminate my ec2 instance, I had to terminate my eb environment first, which I did by visiting:
https://console.aws.amazon.com/elasticbeanstalk/?region=us-west-2
Where the value supplied to region= is the region that contains the environment to be shut down. On that page, one can easily deactivate multiple environments swiftly:

A: Force detach the system volume.  Then you will be able to stop instance.  Re-attach volume and start instance.  Viola!

A: I recently faced a similar same issue. While trying to start an instance, it got stuck in pending state. After reaching out to AWS support, they provided a workaround which worked well. This might also be applicable in other similar situations where an instance is stuck in a state which does not allow further actions through AWS Console.
You can use the AWS CLI to force stop the instance, instead of AWS console. Although an instance stack in Pending state cannot be managed through AWS console, using the AWS CLI allows you to stop it and start it again. The following command should allow you to stop the instance and force it move to the "Stopped" state:
aws ec2 stop-instances --instance-ids <You instance Id>

You can find more information about how to install and use AWS CLI here: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html

A: on reboot internal IPs and public DNS change, so if you dont have elastic IP associated with your system then this might be the reason why you cant SSH in to the system.