text:
Q: Intrusion Detection System for WordPress sites With the current issues with Network Solutions sites being hacked, I'm in need of a tool (preferably freeware) that I can install into my site and it will email me the second a file change/update occurs.
Any recommendations welcome :)
This site is on a shared server hosting package.

A: You can't install a true IDS on shared hosting, this is the host's responsibility.
An hack-ish solution:
You could create a script that ran periodically (using cron or some other mechanism), that would checksum all files, and compare the checksums with a previously stored record, then notify you if there are differences.
To find out if your script itself was deleted by the attack (1), you must also create a script sitting on a remote server (something like Google App Engine, perhaps), that pings your shared-server-script, and checks if it gets an expected result (a hash based on given time, perhaps) – if not, it emails you.
(1) This is actually quite unlikely, most attacks don't delete files

A: http://www.la-samhna.de/samhain/
However this won't work on shared hosting, so you'll need either a vps or a dedicated server

A: I've used Tripwire before.  It worked really well.  ...its not freeware.
You could find some good options by searching the term "IDS" or "Intrusion Detection System"

A: I second the suggestion of Joel L above - usually any cron job output is emailed to the address you pick when you set up the cron job.
If you rarely change themes or plugins, then this is a good way to go.
When you do make a change, you can just update the "baseline" checksum values.
I need to check out the mute screamer plugin, though, that may be best.

A: The best free and open source Intrusion Prevention System (IPS) for web application (as in a Web Application Firewall WAF)  is Mod_Security.  But no system will stop it all.  Espically with Wordpress because it won a pwnie award for being so insecure.  I would think seriously about ditching Wodrpess for any other blog engine.
Another option which is best suited if you are in a shared hosting enviroment is to use PHP-IDS.  The name is a bit deceptive,  its actually a regular expression based IPS.  All of the regular expressions used by PHP-IDS have been ported to Mod_Security.  Mod_Security provides a much better level of protection(ips) and logging(ids).

A: i originally wrote this in a comment on the rook's answer, but it might get lost in all that noise;

phpids indeed looks interesting as it can
  be used in a shared server hosting
  environment, which in general will
  not be the case for tripwire or mod_security.
interestingly, there is a wordpress
  plugin which nicely integrates (an
  older version of) phpids in
  wordpress, so that might be worth
  looking into.

A: Rook: I think it is probably because WordPress security flaws get patched quickly once discovered. This do mean that anyone running an install must watch for new releases and install them as quickly as they can.

A: You could version the site with subversion/git/etc - doing a simple 'svn status' or 'git status' would allow you to tell if the source files had changed - however it obviously won't catch any modifications someone may have made to the database content, and it'll get a little messy when someone updates plugins (or wordpress itself) - as so much will have changed.

A: take a look at http://www.guardio.net uptime and file integrity monitoring


text:
Q: Wait till next page fully loads I have page 1 and page 2, A button in page 1 takes a user to page 2. I want a javascript to wait till page 2 has fully loaded before displaying it when the user clicked the button in page one, In between I need to put loading gif, so that visitor will know that something is loading.
How can I achieve that using pure javascript?
No jQuery please.
EDIT:
The javascript has to be pasted in page one, so that the button would be the trigger, do note that we can't load page 2 in div as some might suggest to load page two in div, then read if page two is fully loaded then display div.

A: window.onload
might be what you're looking for

A: document.addEventListener("DOMContentLoaded", function(event) {
    //Your code
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: mouseevent in java is not being triggered I am designing a virtual piano using Java7. I am having an issue with event calls however on mouse clicks. the JFrame (Piano) contains the JPanel (PianoKeyboard) which in turn contains several piano keys  as JComponent(PianoKey). i would like the Piano class (jframe) to know which key was pressed when the respective icon is pressed.
Hence i have done the following
the PianoKey has a MouseListener, who's methods are implemented within PianoKeyboard. PianoKeyboard has a KeyListener who's methods are implemented within Piano. The Key listener events are fired when an event is received from piano key.
The issue however is that when the icons are clicked on, none of the mouse event listener methods within piano keyboard are being triggered.
The Piano Class:
public class Piano extends JFrame implements KeyListener {

    public Piano() {
        super();
        this.setTitle("Piano");
        this.setName("Piano");
        this.setSize(850,200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        PianoKeyboard s = new PianoKeyboard(0);
        s.addListener(this);
        this.getContentPane().add(s);
        this.setVisible(true);
    }
}

the Piano Keyboard Class:
public class PianoKeyboard extends JPanel implements MouseListener{
    ArrayList<KeyListener> listeners = new ArrayList<KeyListener>();
    public PianoKeyboard(int tempo){
        super();
        this.tempo = tempo;
        this.setBackground(Color.WHITE);
        this.setEnabled(true);
        this.setSize(Piano.FRAME_SIZE);
        this.setVisible(true);
        this.setLayout(new OverlayLayout(this));
        createKeyboard();
    }
    public void addListener(KeyListener listener){
        listeners.add(listener);
    }

    private void createKeyboard() {
    ........ code ......
    for (int i = 0; i < 25; i++) {
            PianoKey k = new PianoKey(i+1, tempo);
            k.addMouseListener(this);
            ..... code .....
            keys.add(k);
        }
    }

   /** the followign methods are also available:
         mouseClicked, mouseExited, mousePressed, mouseReleased
         which contain the following code when neeed:
         for(KeyListener k : listeners){
        k.keyPressed();
    }
   */

   public void paint(Graphics g){
        for(int i = 0; i < keys.size(); i++){
            g.drawImage(keys.get(i).getImage(),positions.get(i),0,54,150,null);
        }
    }
}

The Piano Key Class:
public class PianoKey extends JComponent {
    public PianoKey(int pitch,int tempo) {
        super();
    ....code....
    this.setImage(ImageIO.read(cl.getResource(IMAGE_DIRECTORY + "/key/white.png")));
}

The Key Listener:
public interface KeyListener {
    public void keyPressed();
}

A: implement this on your piano class :
public void keyTyped(KeyEvent e) {
    System.out.println("am i working?");
}

what happens now?

A: I think what is going on is you haven't actually added the keys to any GUI to register mouse clicks. I see you adding them to what appears to be some kind of List but that's all. They 'appear' because the panel is painting images from them but that's not the same thing as actually being a visible part of the interface.
class PianoKey
extends JComponent {

    PianoKey(/* args */) {

        BufferedImage key = ImageIO.read(
            cl.getResource(IMAGE_DIRECTORY + "/key/white.png")
        );

        final Dimension sz = new Dimension(key.getWidth(), key.getHeight());
        setPreferredSize(sz);
        setMinimumSize(sz);
        setMaximumSize(sz);

        setImage(key);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        BufferedImage key = getImage();

        g.drawImage(key, 0, 0, key.getWidth(), key.getHeight(), null);
    }
}

class PianoKeyBoard
extends JPanel
implements MouseListener {

    PianoKeyBoard(/* args */) {

        setLayout(new GridLayout(25, 0));

        for( int i = 1; i <= 25; i++ ) {
            PianoKey key = new PianoKey(/* args */);

            key.addMouseListener(this);

            add(key);
        }
    }

    @Override
    public void mousePressed(MouseEvent me) {
        System.out.println("pressed");
    }
    @Override
    public void mouseClicked(MouseEvent me) {
        System.out.println("clicked");
    }
    @Override
    public void mouseReleased(MouseEvent me) {
        System.out.println("released");
    }
    @Override
    public void mouseEntered(MouseEvent me) {
        System.out.println("entered");
    }
    @Override
    public void mouseExited(MouseEvent me) {
        System.out.println("exited");
    }
}

class Piano
extends JFrame {

    Piano() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setContentPane(new PianoKeyBoard(/* args */));

        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Piano().setVisible(true);
            }
        });
    }
}

Something like that will work. Here, PianoKey paints the image and PianoKeyBoard just adds them to itself. Also, as a side note, make sure you are overriding paintComponent in Swing, not paint.


text:
Q: Is is possible to use array_map in this case instead of foreach? I have the following foreach statement:
$classes = '';

foreach($uriSet as $uri) {
   if (request()->is($uri)) {
      $classes .= 'active';
   }
}

Instead, I tried to use array map like so:
if (array_map([$this, 'checkUri'], $uriSet)) {
    $classes .= 'active';
}

// Somewhere down the class I have
public function checkUri($uri)
{
    return request()->is($uri);
}

but that if statement seems to be true all the time. I want to extract that into a separate method, as I will be using the checkUri method somewhere else in the same manner, but doing a different operation afterwards (not setting a classname like I have here).

A: I managed to do this with array_filter instead, like so:
if (array_filter($uriSet, [$this, 'checkUri'])) {
    $classes .= 'active';
}

A: array_map() returns an array, so your if statement will be false only if it will return an empty array.
http://php.net/manual/en/function.array-map.php

array array_map ( callable $callback , array $array1 [, array $... ] )
  array_map() returns an array containing all the elements of array1
  after applying the callback function to each one. The number of
  parameters that the callback function accepts should match the number
  of arrays passed to the array_map()

var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)

A: Since you're using Laravel, you can utilize the contains method on the Collection class:
if (collect($uriSet)->contains([$this, 'checkUri'])) {
    $classes .= 'active';
}


text:
Q: which site template is best for public site in Share Point 2010 I have to create a public facing site, surely it will have a admin panel.
which site template is best for public site in Share Point 2010.

A: Publishing Site - This is intended for public facing site.
See:
A preview of the SharePoint Server 2010 site templates


text:
Q: Weka Creating Instance Object error I was looking a programmatic exampple of Weka from http://weka.wikispaces.com/Programmatic+Use . However, I think because of the version of my Weka jar (3.7.7), it gives error on this line:
 Instance iExample = new Instance(4);

 Error: Cannot instantiate the type Instance

What kind of change should I do on the code?

A: Okay, according to this documentation Instance is an interface. Which is why your getting this error. You will need create one of the implementing classes eg,
Instance iExample = new DenseInstance(4);

Perhaps that example is out of date.


text:
Q: What's wrong with my implementation of the Dutch National flag algorithm? Here's the original question

Give you an array which has n integers,it has both positive and
  negative integers.Now you need sort this array in a special way.After
  that,the negative integers should in the front,and the positive
  integers should in the back.Also the relative position should not be
  changed.
  eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.

My Java code (translated from Wikipedia's pseudocode)
package ThreewayPartition;

import java.util.Arrays;

public class ThreewayPartition {
    public void sort(int[] input, int mid) {
        int i=0;
        int j=0;
        int n = input.length - 1;

        while (j <= n) {
            if (input[j] < mid) {
                swap(input, i, j);
                i++;
                j++;
            } else if (input[j] > mid) {
                swap(input, j, n);
                n--;
            } else {
                j++;
            }
        }
    }

    private void swap(int[] arr, int j, int k) {
        int tmp = arr[j];
        arr[j] = arr[k];
        arr[k] = tmp;
    }

    public static void main(String[] args) {
        int[] input = {-1, 1, 3, -2, 2};
        ThreewayPartition twp = new ThreewayPartition();
        twp.sort(input, 0);
        System.out.println(Arrays.toString(input));
    }
}

I get this output: [-1, -2, 3, 2, 1] instead of [-1, -2, 1, 3, 2]

A: Your swap() method is swapping elements, not shifting.

You can modify the sort method as shown below -
public void sort(int[] input, int mid) {
    int n = input.length - 1;
    int i=0;
    int tmpvar;
    while (n >= i) {
        if(input[n] < mid) {
            tmpvar = input[n];
            System.arraycopy(input, 0, input, 1, n);
            input[0] = tmpvar;
            i++;
        } else {
            n--;
        }
    }
}

A: Probably there is nothing wrong with implementation - just Dutch national flag inplace partition is not stable.

A: I had a look at Wikipedia's pseudocode and I noticed that mid is used incorrectly in sort(). It should be used as a value, i.e, input[mid].
That being said Dutch National Flag algorithm is not stable and will not satisfy the constraint in the question:

the relative position should not be changed

However, it's important to mention that the problem is a variant of the DNF algorithm.
So you are looking for something along the following lines:
import java.util.Arrays;

public class ThreewayPartition{

    public static void sort(int[] A, int mid) {
        int startIndex = 0;

        for (int i = 0; i < A.length; i++) {
            if (A[i] <= mid) {
                int temp = A[i];
                for (int j = i; j > startIndex; j--) {
                    A[j] = A[j-1];
                }
                A[startIndex] = temp;

                if (temp < mid) startIndex++;
            }
        }
    }

    public static void main(String[] args) {
        int[] input = {-1, 1, 3, -2, 2};
        ThreewayPartition twp = new ThreewayPartition();
        twp.sort(input, 0);
        System.out.println(Arrays.toString(input));  // [-1, -2, 1, 3, 2]
    }
}

Please note that the code's time complexity is O(n*n).
A more efficient, time complexity O(n), and simpler to understand:
import java.util.Arrays;

public class ThreewayPartition{

    public static void sort(int[] A, int mid) {

        for (int i = A.length - 1; i > 0; i--) {
            if (A[i] <= mid && A[i - 1] > mid) {
                swap(A, i, i-1);
            }
        }
    }

    private static void swap(int[] arr, int j, int k) {
        int tmp = arr[j];
        arr[j] = arr[k];
        arr[k] = tmp;
    }

    public static void main(String[] args) {
        int[] input = {-1, 1, 3, -2, 2};
        ThreewayPartition twp = new ThreewayPartition();
        twp.sort(input, 0);
        System.out.println(Arrays.toString(input));  // [-1, -2, 1, 3, 2]
    }
}


text:
Q: Jssor slider responsiveness not working when placed inside a table When you make Jssor slider responsive and it's elements placed inside a Table, responsiveness not working anymore.

and html:

If i place "slider1_container" inside a table, the responsiveness won't work anymore.
Im creating a slider webpart for SharePoint and i don't control over the parent of "slider1_container" and any html element could be there.
And because of that table, this line of code never returns a value smaller than the initial width of slider:
var jssor_slider1 = new $JssorSlider$('slider1_container', options);

And that's why the responsiveness will fail, because if width not get any smaller then $ScaleWidth method will not scale the slider.

A: Since i'm creating a slider web part for SharePoint, i solved this problem by finding another Div element that is parent of the table which causing the issue.
And in this line i set element id of my savior div element like:
var parentWidth = $('#savior_parent').width();


text:
Q: Direct link to write an app review in Google Play Store I have the following link: https://play.google.com/store/apps/details?id=com.android.chrome
If I open this link on an Android device, the Google Play Store app gets opened and shows the details of the Google Chrome app.
At iOS, it's possible to ad ?action=write-review to the link, this will not only open the app in the App Store, this will also present the Write a review window of the app, so that you can write a review without the need to click on the Write review button before.
Is there something similar for Android?

A: As far as I know, Android doesn't have a similar option.
However, Android supports reviewing within your application with in-app reviews.


text:
Q: Xamarin VS Windows - IPhone does not show up I'm using Visual Studio for Windows and I have a Xamarin Forms app for Android and iOS. I mostly test physically on Android (since that is much easier) and I have tested on an IPhone as well about a year ago, which worked fine (without a mac). Now I plugged it in again and it doesn't work anymore: the IPhone does not show up in the debugging list.
I have:

*

*Apple Developer account and I'm connected with this account from Visual Studio

*Identifier for Bundle

*Profile (created by VS itself, with Type 'Development')

What am I missing here? I haven't added the provisioning profile in my solution, is that something that needs to be done? Am I missing another step?
I hope someone can help.

A: For the exact breakdown on how to setup and get started with your iOS solution, follow Microsoft's Xamarin iOS on Windows guide.
The tl;dr though is: you absolutely need a Mac to run a Xamarin iOS project, even on windows. I do not know how you had your project setup last time, however this has been the case since Xamarin's debut. Although, you could also just have access to a Mac through network connection instead of having a physical Mac. Without a physical device, you can use the Mac's ios simulator. If you are planning on using a physical iphone though, said device needs to be plugged into the Mac and not the windows machine. Later MacOS do support wireless connections of trusted devices, but it is still a wireless connection from the iphone to the mac (needing to be on the same network).


text:
Q: Во время выполнения программного клика по кнопке (doClick), не отображаются остальные кнопки Совсем новичок в Swing, возможно не до конца понимаю потоки или еще что-то
В общем, такая проблема -- класс Field представляет собой окно, содержащее панель из кнопок 4 на 4 (field).

Класс AI -- его наследник, но также в конструкторе программно вызываются нажатия по кнопкам на главной диагонали. Дело в том, что когда это нажатие осуществляется, само поле из кнопок не отображается. Примерно так:

Исходник программы:
класс Field
import java.awt.*;

import javax.swing.*;

public class Field extends JFrame {

    JPanel field;   //панель будет содержать кнопки 4x4
    JButton[][] buttons;    //собственно, кнопки

    public Field() {
        // TODO Auto-generated constructor stub
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);

        field = new JPanel(new GridLayout(4, 4));   //инициализируем панель
        field.setPreferredSize(new Dimension(300,300));

        buttons = new JButton[4][4];
        for(int i=0; i<4; i++)
            for(int j=0; j<4; j++) {
                buttons[i][j] = new JButton();
                field.add(buttons[i][j]);
            }

        add(field);
        setVisible(true);
    }
}

Класс AI:
public class AI extends Field {
    public AI() {
        // TODO Auto-generated constructor stub
        super();
        for(int i=0; i<4; i++) {
            buttons[i][i].doClick();
        }
    }
}

Вызываю AI асинхронно (SwingUtilities.invokeLater)

A: Если хотите нажать программно(не пользователем) можете использовать такой вариант:
public AI() {
    // TODO Auto-generated constructor stub
    super();
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 4; i++) {
                buttons[i][i].doClick();
            }
        }
    }).start();
}

т.е. выполнять нажатие в параллельном потоке


text:
Q: How to extract a vector by 100+ unique character strings without having to type all of them by hand in R I have a data set of more than 86,000 different rows and 27 variables. It is a list of different individuals, their company, percentage attendance, among other things. Each company has data from 2010-2011 starting in September all the way to 2015-2016.
A portion of the data set is below with omissions and ellipses to indicate transitions.
yr      Company month MO    % Attendance    %Change
2010-11 "015JK" 1    SEP    88.21
2010-11 "015JK" 2    OCT    92.51             4.31
2010-11 "015JK" 3    NOV    90.97            -1.54
2010-11 "015JK" 4    DEC    89.19            -1.78
2010-11 "015JK" 5    JAN    86.88            -2.31
2010-11 "015JK" 6    FEB    89.28             2.4

...
yr        Company  month MO % Attendance     %Change
2015-2016  015JK    1   JAN   82
2015-2016  015JK    2   FEB   64               -18
2015-2016  015JK    3   MAR   94                30
2015-2016  015JK    4   APRIL 98                4
2015-2016  015JK    5   MAY   50                -48
2015-2016  015JK    6   JUNE  68                18

This is a typical set of data whereupon we start again but this time we start with a new company as such:
yr           Company    month   MO    %Attendance          %Change
2010-2011    0184JK     1       JAN     49
2010-2011    0184JK     2       FEB     52                   3
2010-2011    0184JK     3       MAR     82                   30
2010-2011    0184JK     4       APRIL   55                  -27
2010-2011    0184JK     5       MAY     53                   -2
2010-2011    0184JK     6       JUNE    80                   27

...
yr           Company    month   MO     %Attendance      %Change
2015-2016    0184JK      1      JAN        87
2015-2016    0184JK      2      FEB        47              -40
2015-2016    0184JK      3      MAR        61               14
2015-2016    0184JK      4      APRIL      78               17
2015-2016    0184JK      5      MAY        43              -35
2015-2016    0184JK      6     JUNE        85               42

I can capture these sets of data relatively easily from the massive 86,000 row datasheet with the following R codes
015JK <- df[ which( df$Company== "015J"), ]
0184JK <- df[ which( df$Company== "0184JK"), ]

The problem is that that I have more than 100 plus companies and it would be onerous to type in 90+ iterations of
some company name such as 015JK <-df[ which(df$company== "some company
name"), ]

Is there way to extract the unique values of Company and then input it into a multiple iterations of the following aforementioned variety:
some company code name such as 015JK <-df[ which(df$company== "some company
code"), ]


text:
Q: PHP Validation and Javascript Validation won't work together When I combine my php form validation code with my javascript validation code, the javascript code fails to work when I hit the submit button. It will only validate the first form field and not the 3 others and then php will validate all fields. I don't want the php form validation to do anything until javascript has completed the form validation.
When I use only php or only javascript to validate, then the code works correctly. What am I missing here? Is it something to do with the beginning of the form?
"form name="contactform" id="contactform" method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
onsubmit="return validateentry();">"

Am I supposed to do the php form validation while "action" goes to a different web page?
The javascript code:
function validateemail()
{
var emailentry=document.forms.contactform.email.value;
at=emailentry.indexOf("@");
period=emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
   alert("Please enter correct email in the format of 'yourmail@yourwebsite.com'")
   document.forms.contactform.email.focus();
   return false;
}
return(true);
}

function validatephonenumber()
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
    var numbers = document.forms.contactform.phone.value;
    var verified = re.exec(numbers);
    if (!verified)
    {
alert("Please enter a phone number in the format of 999-999-9999");
return false;
}
    return(true);
}

function validateentry()
{
if(document.forms.contactform.name.value=="")
{
 alert("Please provide your name.");
 document.forms.contactform.name.focus();
 return false;
}

if(document.forms.contactform.company.value=="")
{
 alert("Please provide your company name. If you don't have one, simply state
 that you don't.");
 document.forms.contactform.company.focus();
 return false;
}

 if(document.forms.contactform.email.value == "")
 {
 alert("Please provide an Email address.");
 document.forms.contactform.email.focus();
 return false;
 }else{
 var validformat=validateemail();
 if(validformat==false)
 {
 return false;
 }}

if(document.forms.contactform.phone.value=="")
{
 alert("Please provide a phone number in the format 999-999-9999.");
 document.forms.contactform.phone.focus();
 return false;
}
else if(document.forms.contactform.phone.value.length < 12)
{
    alert("Please provide the phone number in the format of 999-999-9999.");
    document.forms.contactform.phone.focus();
        return false;
}
    else
    {
    var validnumber=validatephonenumber();
    if(validnumber==false)
    {
    return false;
    }}

if(document.forms.contactform.msg.value=="")
{
 alert("Please provide a message.");
 document.forms.contactform.msg.focus();
 return false;
}
 return(true);
}

A: It's unclear without more code but based on your comment I am going to guess that you have incorrectly written your php and it's breaking your javascript/html code. Perhaps one of your quotes?  Look at the source code of the page and run it through one of the online validation services such as http://validator.w3.org and http://www.jslint.com

A: Try this:
PHP HTML:
<?php
echo "<form name='contactform' id='contactform' method='post'
action='' onsubmit='return validateentry(this);'>"
...

Validation JavaScript:
function validateemail(e)
{
    var emailentry = e.value
        , at = emailentry.indexOf("@")
        , period = emailentry.lastIndexOf(".");

    if(at < 1 || ( period - at < 2 ))
    {
       alert("Please enter correct email in the format of 'yourmail@yourwebsite.com'")
       e.focus();
       return false;
    }
    return true;
}

function validatephonenumber(e)
{
    var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/
        , numbers = e.value;

    if (!re.exec(numbers))
    {
        alert("Please enter a phone number in the format of 999-999-9999");
        e.focus();
        return false;
    }
    return true;
}

function validateentry(f)
{
    if(f.name.value == "")
    {
        alert("Please provide your name.");
        f.name.focus();
        return false;
    }

    if(f.company.value == "")
    {
        alert("Please provide your company name. If you don't have one, simply state
        that you don't.");
        f.company.focus();
        return false;
    }

    if(f.email.value == "")
    {
        alert("Please provide an Email address.");
        f.email.focus();
        return false;
    }
    else
    {
        var validformat = validateemail(f.email);
        if(validformat == false)
        {
            return false;
        }
    }

    if(f.phone.value == "" || f.phone.value.length < 12 || (validnumber = validatephonenumber(f.phone)) == false)
    {
        alert("Please provide the phone number in the format of 999-999-9999.");
        f.phone.focus();
        return false;
    }

    if(f.msg.value == "")
    {
        alert("Please provide a message.");
        f.msg.focus();
        return false;
    }
    return true;
}


text:
Q: Ubuntu stuck on login page - can't login with keyboard I don't know why but my Ubuntu session got stuck at the login page suddenly and I can't get through any further. When starting the VM, I get the following screen :

I've tried CTRL+ALT+F1 and CTRL+ALT+F7 but no luck... My keyboard and mouse aren't working.
I've also tried CTRL+ALT+F3 and ran
sudo apt install --reinstall ubuntu-desktop
sudo apt install --reinstall ubuntu-session

but still the same.
[
I'm wondering what's wrong and what I can do. If ever it is not possible to recover my session, is there a way to create another VM with the disk of this one... I'd hate to lose everything.


text:
Q: Typescript type casting when destructuring Let's assume this
{foo, bar} = groupBy(arg);

I want to cast foo to type Foo and bar to type Bar. How can I do this?
I'm a complete beginner with Typescript. groupBy is the one from lodash package.

A: If Typescript can not deduce the type of the result of groupBy you could try asserting it yourself.
function groupBy(o: any) {
    return o; // return any
}

let x = { a: 1, b: "1" }

// we know better than tsc and assert the type
let {a, b} = <{ a: number, b: string }>groupBy(x);


text:
Q: Excel formula- Two or more different cells repeat same text I need help with a formula.
In Column A I have a list of numbers or text.
In column B, I have another list of numbers or text, but for example in cell B 10 is the same  a number or text as in cell A55. I need a formula in column C10 that will show that the cells B10 and A55 same.
Columns A and B contain different data (text or numbers) but there is a possibility that in column B may be repeated as the data in column A.
In A column I have about 250 different data in column B  maximum of 15, so I need a formula for Column C that will indicate if a value in column B repeats.
I need a formula for excel 2003

A: This will give you the row number of the first object found in Column A which is repeated in a cell of column B.
=IFERROR(MATCH(B1,A:A,0),"")

With your figures:


text:
Q: Netstat listening programs on ports alternative on Debian 9 What is the alternative to command netstat -ntpl on Debian 9?
I am using this command to check what program is listening on port.
Alternatively with parameters -ntupl (with u) including UDP.

A: netstat (with both options) works fine on Debian 9. If it is not installed, it is in the package net-tools.
There is also the ss command (dumps socket statistics) from the package iproute2. The option you have given, seem all to be the same: ss -nptl, etc.. The output format is a bit different, though.
https://linux.die.net/man/8/ss
https://scottlinux.com/2012/08/16/ss-the-alternative-to-netstat/

A: Simply use ss -a4n for listening all ipv4 port (listening or not) and not resolve the port number (show the number, not the service)


text:
Q: Save image path name from sdcard to Sqlite database am having a little trouble here. i am trying to store and retrieve images from an sqlitedatabase by storing their image path name. the images are stored in the sdcard. I tried this code, but its not working.
saving image path:
 String filename = "/sdcard/barn.jpg"

ContentValues vals2 = new ContentValues(); //create content values and store it.
   vals.put(ImageDB.SHOW, filename);
   imagedb.tagImage(vals2);

public long tagImage(ContentValues val){
        Log.d(TAG,"tagged Images");
        return db.insert(DATABASE_TABLE, null, val);
    }

retrieving :
Cursor cursor = imagedb.retrieveTag(tag);

    /*method for retrieving*/

    public Cursor retrieveTag(String tag){
    String[] condition = {tag)};
    Cursor cursor = db.query(DATABASE_TABLE, condition, null, null, null, null, null);
        cursor.moveToNext();
        return cursor;
    }

The cursor is not returning anything and i sometimes get a CursorIndexOutofBoundsException.
Is this a correct way to save and retrieve from an sqlitedatabase or does the filename pose a problem for the sqlite database?.. How can i store it correctly?.. Thank you.

A: Try getting the root directory with Environment.getExternalStorageDirectory(), harcoding "/sdcard/" may not work.


text:
Q: How to write a function that returns indexes of input vector according to some rules, using repeat, while loop, or other iteration technique I'm trying to write a function that takes a numeric vector as input, and returns the indexes of a shorter version of the input vector, according to some rules:

*

*(a) if all elements are identical, return just the index of the first element; i.e., return 1; else:
if NOT all elements identical, then test for whether special_treatment_value is among them:

*

*(b) if special_treatment_value is there, return the input vector's indexes  except for the indexes of elements where special_treatment_value appeared; else:

*(c) if special_treatment_value is not there, return the indexes of the input vector as-is, i.e., 1:length(x).

The problem: if we ended up in route (b), we might encounter a situation in which all vector elements are now the same. In such case, we would like to iterate through (a) again to minimize to just the first element.
Example
Let's say that I want to pass the following vectors through my function:
my_vec_1 <- c(1, 2, 1, 2, 3)
my_vec_2 <- c(4, 4, 4)
my_vec_3 <- c(1, 2, 1, 4, 1)
my_vec_4 <- c(3, 3, 3, 4)

and that:
special_treatment_value <- 4

According to my rules, the function should return the outputs:

*

*for my_vec_1: it fits route (c) and thus the output should be 1:5 (indexes of all)

*for my_vec_2: it fits route (a) and thus the output should be 1 (index of first)

*for my_vec_3: it fits route (b). output should be 1 2 3 5 (indexes of all except for special value's)

*my_vec_4 demonstrates the problem. My desired output is 1 because first we go through route (b) then I want to pass through (a). But right now it doesn't happen and my function (see below) returns 1 2 3 (indexes of all except for special value's).

 my current attempt
get_indexes <- function(x, special_val) {
  if (var(x) == 0) { # route (a)
    output_idx <- 1
    return(output_idx)
  }

  idx_entire_length <- 1:length(x)

  if (any(x == special_val)) { # route (b)
    idx_to_remove <- which(x == special_val)
    output_idx    <- idx_entire_length[-idx_to_remove]
    return(output_idx)
  }

  # else
  output_idx <- idx_entire_length # route (c)
  return(output_idx)
}

get_indexes(my_vec_1, 4)
#> [1] 1 2 3 4 5
get_indexes(my_vec_2, 4)
#> [1] 1
get_indexes(my_vec_3, 4)
#> [1] 1 2 3 5
get_indexes(my_vec_4, 4)
#> [1] 1 2 3

I guess there should be some repeat block or while loop, but I can't figure out how to implement it correctly (and efficiently).

A: You can try
foo <- function(x, y){

  tmp <- which(x != y)

 if(dplyr::n_distinct(x[x!=y])<=1){
   tmp <- 1
 }

 return(tmp)
}

Instead n_distinct() you can use length(unique())
Result:
lapply(list(my_vec_1, my_vec_2, my_vec_3, my_vec_4), foo, 4)
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 1

[[3]]
[1] 1 2 3 5

[[4]]
[1] 1

A: You could repeat the condition for going through (a) inside condition (b), for example:
f <- function(x, treatment){
  if(var(x) == 0) 1 else {
    if(treatment %in% x) {
      x[-which(x == treatment)] |>
        (\(.) if(var(.) == 0) 1 else (1:length(x))[-which(x == treatment)])()
    } else {
      1:length(x)
    }
  }
}

lapply(list(v1, v2, v3, v4), f, 4)

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 1

[[3]]
[1] 1 2 3 5

[[4]]
[1] 1


text:
Q: postgres14 trims digits in timestamp Postgres 14. I have following table:
CREATE TABLE IF NOT EXISTS F_WALLET
(
    id                      serial PRIMARY KEY,
    // columns
    // more columns
    inserttime              timestamp
);

I have python code that does insert, example:
INSERT INTO F_WALLET
    (
    // some more columns
    inserttime
    )
    VALUES (
          11.05,      137.66,        2.20,
         137.66,        0.00,       21.81,
           0.00,       21.81,      115.85,
         137.66,        0.00,      115.85,
           true, '2022-09-15 2022-09-15 20:21:57.768330+02:00'
    )

But if microseconds in inserttime (last column) end with zeros it gets trimmed..
Now (using pgadmin/console/any other tool) when I do SELECT id, inserttime FROM F_WALLET I have:
 897  | 2022-09-15 20:22:05.400541
 896  | 2022-09-15 20:22:03.477851
 895  | 2022-09-15 20:22:01.9936
 894  | 2022-09-15 20:22:00.591512
 893  | 2022-09-15 20:21:57.76833
 892  | 2022-09-15 20:21:54.860594

How do I force my table to put zeros to get exactly n-digits ?
If not possible then how do I force my select to add zeroes to have exactly n-digits in microseconds ?

A: Timestamps have no format. Queries present them as needed. You may use  to_char to explicitly format the timestamp like this:
SELECT id,
    to_char(inserttime, 'yyyy-mm-dd hh24:mi:ss.us') as inserttime
FROM F_WALLET;

or format and extract in more complex cases.


text:
Q: Using INSERT INTO with two values, WHERE clause for only one I need to insert two values from two separate tables and filter one of the values with a WHERE clause.
Currently I'm using:
INSERT INTO Combined_List (Email, Product)
SELECT meta_value, item_name FROM user_list, order_items
WHERE meta_key LIKE '%user_email%'

The meta_value contains various information so I'm trying to filter just the entries that have anything like user_email as their meta_key.
The problem is that when I run this the entries are repeated hundreds of extra times.
Am I using the correct syntax to filter just the meta-key and not the item_name?

A: You need to join the user_list and order_items on their common field!
Right now you are combining every entry from user_list with every entry from order_items.

A: Try this:
INSERT INTO Combined_List (Email, Product)
SELECT DISTINCT meta_value, item_name FROM user_list, order_items
WHERE meta_key LIKE '%user_email%'

Or:
INSERT INTO Combined_List (Email, Product)
SELECT DISTINCT meta_value, item_name FROM user_list
WHERE meta_key LIKE '%user_email%'
UNION
SELECT DISTINCT meta_value, item_name FROM order_items
WHERE meta_key LIKE '%user_email%'

EDIT:
Not knowing your structure, this is the best I can do
INSERT INTO Combined_List (Email, Product)
SELECT a.meta_value, b.item_name
FROM user_list a
JOIN order_items b ON a.meta_key = b.meta_key
where a.meta_key LIKE '%user_email%'

Use a PK - FK relationship instead of a.meta_key = b.meta_key


text:
Q: Problems with updating & upgrading I'm trying to update my system and install SQL, but I'm having problems with llibgsapi-krb5-2 seemingly.
I have tried to update, upgrade, clean, purge etc... that I have found from forums.
This is the problem that occurs when I try to --fix-broken install.
I have a Raspberry PI with noobs.
$ sudo apt --fix-broken install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following package was automatically installed and is no longer required:
  point-rpi
Use 'sudo apt autoremove' to remove it.
The following additional packages will be installed:
  libgssapi-krb5-2
Suggested packages:
  krb5-doc krb5-user
The following packages will be upgraded:
  libgssapi-krb5-2
1 upgraded, 0 newly installed, 0 to remove and 364 not upgraded.
Need to get 0 B/135 kB of archives.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Reading changelogs... Done
(Reading database ... 156037 files and directories currently installed.)
Preparing to unpack .../libgssapi-krb5-2_1.17-3+deb10u1_armhf.deb ...
dpkg: error processing archive /var/cache/apt/archives/libgssapi-krb5-2_1.17-3+deb10u1_armhf.deb (--unpack):
 too-long line or missing newline in '/var/lib/dpkg/info/libgssapi-krb5-2:armhf.triggers'
Errors were encountered while processing:
 /var/cache/apt/archives/libgssapi-krb5-2_1.17-3+deb10u1_armhf.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Result of
cat /var/lib/dpkg/info/libgssapi-krb5-2:armhf.triggers
# Triggevs added bi dh]makeshlibs/12.1.!
actkvate-noaWaitldconfig


text:
Q: How do you define an enumeration in 68000 assembly language? I'm using the assembler that came with the Manx Aztec C compiler (version 5.0) on a Commodore Amiga 500.
I want to code the equivalent of the following C code:
enum STATUS {
    STATUS_OKAY,
    STATUS_WAITING,
    STATUS_ERROR
};

I tried the following—which works—but it seems kind of hokey:
s_id            set 0
STATUS_OKAY     equ s_id
s_id            set s_id+1
STATUS_WAITING  equ s_id
s_id            equ s_id+1
STATUS_ERROR    equ s_id

I know I could do:
STATUS_OKAY    equ 0
STATUS_WAITING equ 1
STATUS_ERROR   equ 2

But I would like to be able to insert and rearrange values without having to manually renumber.
I was thinking I might be able to do something with macros, but I don't have much experience with them.

A: I'd guess you'd want to write a macro that you can use like AUTONUMBER s_id STATUS_OKAY that takes two args: 2nd is the symbol name to define, 1st is the counter to increment.
You'd want it to expand to something like:
STATUS_OKAY     equ s_id
s_id            set s_id+1    # post-incr so it uses the initial value of s_id

(I don't know that assembler or its syntax for defining macros; I assume that's possible though.)
Some assemblers have a special macro directive for redefining a preprocessor constant, allowing you to increment.  e.g. NASM wouldn't work with foo equ foo+1, you'd need %define.  You used s_id set s_id+1 in most of your lines, but equ in the last one, so that's probably just a typo.

So full usage would look like:
s_id  set 0       # starting value
AUTONUMBER s_id  STATUS_OKAY
AUTONUMBER s_id  STATUS_WAITING
AUTONUMBER s_id  STATUS_ERROR

I put the counter name first because it's the same length every time (and short).  Putting it 2nd required more indenting to avoid ragged columns.  And it puts the unique part of the line at one end, where it's visually more obvious.

A: After Peter Cordes' suggestion, I came up with the following macro, which works great:
        macro   ENUM
\2      set     \1
\1      set     \1+1
        endm

s_id    set     0
        ENUM    s_id,STATUS_OKAY
        ENUM    s_id,STATUS_WAITING
        ENUM    s_id,STATUS_ERROR


text:
Q: The relationship between state url of UI-Router and REST API url Is there any relationship between the state url of UI-Router and REST API url in angularjs?

A: NO.
The UI-Router state's url represents current state, optionally with some settings (called params). That even could be working without any API in place. It is just a client (browser) side handling.
REST API url, is a way how to get or set data - via server-client communication


text:
Q: RPM 4.8.0 and 'Prereq' I am trying to install a large set of very old packages with rpm 4.8.0, and the transaction order is resulting in an installation failure.
Specifically,

*

*I have a package (tzdata) that says: Prereq: /bin/cp

*'/bin/cp' is in 'coreutils'

Yet 'coreutils' is still after tzdata in the installation order.
Looking at the source (rpm 4.8.0) I can see that the design in this area has changed a lot but it seems like the intent is that the old 'Prereq' flag is still supported.
/* map legacy prereq to pre/preun as needed */
if (isLegacyPreReq(dsflags)) {
    flags |= (teType == TR_ADDED) ?
             RPMSENSE_SCRIPT_PRE : RPMSENSE_SCRIPT_PREUN;
}

Does that sound right?
Based on the code comments, I also get a strong sense that provide/require relationships will sometimes be ignored in order to eliminate dependency loops.  I would like to know if/when this is happening, but it doesn't seem like there are any messages emitted, even at debug level, for such an event ('dropping' a relationship).
Can anyone suggest how to generate and/or interpret debug information in the transaction output to understand why this particular ordering clue is not observed?

A: The code in rpm-4.8.0 has chosen to remap Prereq: (which tries
to force a package installation before current package) as if
it were a Requires(pre): (which marks a require dependency needed
by a %pre scriptlet)contrary to what was originally implemented in rpm.
Yes: dependency loops will be dealt with "best effort" so that an
installation doesn't halt with dependency loops. One crude way to handle loops is to
discard all dependencies in a loop. Another, better, way yo handle loops is to attempt to
install all packages in the loop as a single entity. In both cases
the order determined by the dependencies in a loop is indeterminate and issues
like you are reporting can/will happen.
Installing with rpm -Uvv displays LOOP messages for all dependencies
that are ignored. Verify whether you have a LOOP that includes packages
involved with installing tzdata.
Meanwhile, using 2 transactions to guarantee the installation of a known prerequisite,
or using a hand crafted/ordered package manifest with --nodeps/--noorder during the installation, is
likely going to be your best work around to packaging flaw(s) and a change
in the semantics/implementation of Prereq: in rpm.


text:
Q: Recortar uma string sql server Como posso recortar parte de uma string, por exemplo : "2017/12/teste.jpg",
preciso unicamente pegar "teste.jpg".

A: Esse comando pegará tudo que está depois do último /
select right(minhaString, charIndex('/', reverse(minhaString) + '_') - 1)

Este pegará tudo que está antes do último /
select left(minhaString, len(minhaString) - charindex('/', reverse(minhaString) + '/'))

EDIT
E para pegar sempre à partir do 9º caractere:
substring(@string, 9, len(@string))


text:
Q: MySQL Active record query ignoring case I have the following active record query:
$this->db->select('id, firstname, surname');
$this->db->from('users');
$this->db->where('site_id',$siteid);
$this->db->like('firstname', $name);
$this->db->or_like('surname', $name);
$query = $this->db->get();

This works fine with the exception that my names within the DB can contain upper and lowercase names. If the case does not match, the query fails.
Is there any way I can ignore the case with my query?

A: Try this, it works fine for me:
(you can use lower or upper mode in both sides to insensitive query )
$this->db->select('id, firstname, surname');
$this->db->from('users');
$this->db->where('site_id',$siteid);
$this->db->like('lower(firstname)', strtolower($name));
$this->db->or_like('lower(surname)', strtolower($name));
$query = $this->db->get();

A: One of the way to manipulate case sensitivity in mysql to have your firstname field in either upper or lower case in db and convert given string in that format and match it.
edit: like is an operator and it depends on the database you use that it will be case sensitive or not . In postgres , it is case insenstive where as in mysql it is case sensitive. So it depends on the database you are using.
edit: Another working but not that useful way will be to use ucase() or lcase() function on given field and then match with lowercase or uppercase of match. Though it will have performance issues.


text:
Q: Targeted Push Notification I'm currently doing a location-based project.
I use sql management studio to create and maintain the database.
I use Visual studio 2015 to create the website.
I use Bing Maps for retrieving coordinates based on the dropped pin and store the coordinates in my local DB.
Windows phone is used for the mobile app(receiving notification&location).
And Finally I use Azure Mobile Service to push notification to the phone.
Here's the scenario of my project:

*

*Website will drop a pin on bing maps, and users fill the additional textboxes.

*I have a sql query to sort the users that is within the location of the dropped pin on bing maps. The idea is to push these additional info and pinpoint the location on the mobile app(bing map is used in the app). The submit button will then store the coordinates(Longitude&Latitude) with the additional info into the DB.

Here's what is already done:
1. Website with bingmaps, a panel that displays users within the dropped pin, text boxes for additional info, and finally the submit button.
2. WP app that has bing map inside.
3. Azure mobile service (I can send notifications through the azure portal).
The Problem:
I only want to send the coordinates and additional info based on the user_id that is within radius of the dropped pin on the website.
As far as I know from reading on various web, that Azure push notifications can only be sent to ALL that is on the mobile service. And I would only like to send the push notification ONLY to those within the area based on the user_id from the website.
Is there any reference I can use to send TARGETED notifications based on the user id that I want?

A: You can check out Azure Mobile engagement to send notifications to targeted subset of clients
https://azure.microsoft.com/en-in/documentation/articles/mobile-engagement-user-interface-reach-criterion/


text:
Q: Vlookup in Visual Basic: Trying to Set for the reference column that has a variable range I had a question regarding the code below.  If anyone could provide some insight, I would be greatly appreciative.  Essentially this is part of a report I'm building to be run on a weekly basis.  The issue I'm having is that the reference column K is variable in size of inputs and I hate putting in a constant that results in a bunch of N/A#s (K rows should never exceed 300).  I'm sure it's something simple I'm overlooking, but I tried to write something to count K2:Kn and then input it in the Ranges (q2:r2:s2:t2:qrstn).  Please share your wisdom =)
Sub Vlookup()
    Sheets(2).Select
    Range("q2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-6],table,15,FALSE)"
    Range("q2").Select
    Selection.AutoFill Destination:=Range("q2:q300"), Type:=xlFillDefault
    Range("r2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-7],table,16,FALSE)"
    Range("r2").Select
    Selection.AutoFill Destination:=Range("r2:r300"), Type:=xlFillDefault
    Range("s2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-8],table,17,FALSE)"
    Range("s2").Select
    Selection.AutoFill Destination:=Range("s2:s300"), Type:=xlFillDefault
    Range("t2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-9],table,18,FALSE)"
    Range("t2").Select
    Selection.AutoFill Destination:=Range("t2:t300"), Type:=xlFillDefault

A: Hope I've understood your question properly
The following will autofill range Q2:QN where N is the last used cell in column Q
Selection.AutoFill Destination:=Range(Range("K2"),Range("K2").End(xlDown)).Offset(ColumnOffset:=6), Type:=xlFillDefault

You could also do it the other way round as you have a fixed maximum.
Selection.AutoFill Destination:=Range(Range("K2"),Range("K301").End(xlUp)).Offset(ColumnOffset:=6), Type:=xlFillDefault

The first looks down the sheet for the last row, and the 2nd looks up the sheet from the maximum to the last row.
You can replace Q with whatever column you need, as you appear do do the same for lots of columns!
Update
I've updated the example, it now finds the used range in the K column and offsets it to your desired column. The value of ColumnOffset will be the same (although positive) as the value used in your R1C1 formulas.
Also, as the K Range should remain constant, and your formulas are fairly predictable you could shorten it a little. like the following (i've not testing it, just playing around)
Sub Vlookup() ' might want to re-name, to avoid confusion with the worksheet function
Dim R As Range
Dim A As Range
Dim I As Integer

  Set R = Range(Range("K2"), Range("K301").End(xlUp))
  Set A = Range("K2")

  For I = 6 To 9
    A.Offset(ColumnOffset:=I).FormulaR1C1 = "=VLOOKUP(RC[-" & CStr(I) & "], table, " & CStr(I+9) & ", FALSE)"
    A.Offset(ColumnOffset:=I).AutoFill Destination:=R.Offset(I), Type:=xlFillDefault
  Next I

End Sub

A: You don't need to fill down when you use FormulaR1C1.  You can apply the formula to the whole range.  Here's an example.
Sub MakeVlookup()

    Dim lRows As Long, lCols As Long
    Dim rCell As Range
    Dim rRef As Range

    'Set the first cell of the reference column
    Set rRef = Sheet1.Range("K2")

    'Count the rows of the reference column
    lRows = Sheet1.Range(rRef, rRef.End(xlDown)).Rows.Count

    'Loop through the row 2 cells where you want the formula
    For Each rCell In Sheet1.Range("Q2:T2").Cells
        'Compute the offset back to the reference column
        lCols = rCell.Column - rRef.Column
        'Write the formula to the whole range
        rCell.Resize(lRows, 1).FormulaR1C1 = _
            "=VLOOKUP(RC[-" & lCols & "],Table1," & rCell.Column - 2 & ",FALSE)"
    Next rCell

End Sub

A: No need to loop or address each column with a different formula!
Instead of these formulas:

Column Q: =VLOOKUP(K2,table,15,FALSE)
Column R: =VLOOKUP(K2,table,16,FALSE)
...

you can simply use =VLOOKUP($K2,table,COLUMN()-2,0) as one formula across all columns! $K2 (in R1C1: RC11) instead of K2 (in R1C1 RC[-6], RC[-7], ...) will keep column K. And COLUMN() will return you the column number of the actual cell, i.e. column Q = 17, R = 18, etc.. (I also replaced FALSE with 0 as this reduces typing for lazy blokes like me but results in the same. :-) ).

Therefore, you can reduce your macro to
Sub MakeVLOOKUP
    Sheets(2).Range("Q2:T300").FormulaR1C1 = "=VLOOKUP(RC11,table,COLUMN()-2,0)"
End Sub

and achieve the same result.
If you want to flexibilize the range as in Dick's solution, you can do it like this:
Sub MakeVLOOKUP
    Sheets(2).Range("Q2").Resize(Sheet1.Range("K2").End(xlDown)).Rows.Count-1,4).FormulaR1C1 = _
        "=VLOOKUP(RC11,table,COLUMN()-2,0)"
End Sub


text:
Q: Simplemodal: four times on a page leads to extra "next" or "previous" button NOTE: This has been edited from the original question with a solution. The original question was too long and had many errors in its thinking. For this I apologize.
We experienced a problem when each instance of the call to the simplemodal div class .basic-modal-content added an extra next or previous button in the modal windows at the end of a chain. We had two separate areas of modal content and they were joined at the modal window.
This was solved by having two div classes: .basic-modal-content-foo and .basic-modal-content-bar and having two instances of the script below on the page. All that is required is some CSS...
.basic-modal-content-foo {
    display: none;
}

.basic-modal-content-bar {
    display: none;
}

Here is the "foo" version of the script. Modify the 4 instances of the div class for the bar version.

and some CSS to create an image for each window that shows the progress bar through the ul/li list.
The code to produce the above looks like this:

Our HEADLINE

TEXT 1

TEXT 2

TEXT 3

TEXT 4

TEXT 5

TEXT 6

headline text

body text

headline text

body text

 ... other divs 3 4 and 5

headline text

body text

And staying within the div class the additional text for the "bar" modal.

headline text

BIOGRAPHY

headline text

BIOGRAPHY

headline text

BIOGRAPHY

The ul/li structure works on the main page for the links. The modal windows allow one to browse through all of the six TEXTs. There is a common CSS style to the windows and a custom image in each of the modal windows derived from the "#modal_[number] img" CSS in the form of a progress bar.
Here is the relevant code from one of the three biographic links. You will note that the biographic links each have to have all three in this current configuration.

Our HEADLINE

Read about person NUMBER 1 by clicking on the following link:
Expand

Similarly the "biographies" open up from a different area of the page. The modal windows allow one to browse through all three of the BIOs. The bios use the SAME CSS style windows and a custom image in each of the modal windows derived from the "#modal_[number] img" CSS in the form of a portrait.
Everything is working well.
One question left: I have two instances of the JS on the page. Can this be combined into one script?
Thanks in advance.
DDF

A:
One question left: I have two instances of the JS on the page. Can this be combined into one script?

I don't see why not. Have you tried it?


text:
Q: ViewModel that automagically has same properties than generic model I'm trying to create code for the use-case in the code below, where a generic ViewModel class "captures" all the properties from its model, and presents properties with the same name and type, and also triggers PropertyChanged event for data-binding.
Is there a way to do it? I'm using .NET 4.6.
public class Rectangle
{
    public double Width {get; set;}
    public double Height {get; set;}
}

public class RectangleViewModel : MagicViewModel<Rectangle>
{
    public RectangleViewModel(Rectangle model)
        : base(model){ }
}

public class MagicViewModel<TModel> : INotifyPropertyChanged
{
    protected readonly TModel _model;

    public MagicViewModel(TModel model)
    {
        _model = model;
    }

    // inpc implementation

    // what else?
}

public class Program
{
    public static void Main(string[] args)
    {
        var vm = new RectangleViewModel(new Rectangle());
        var calls = 0;
        vm.PropertyChanged += (sender, args) => calls++;
        vm.Height = 10;  // magic happened here
        Debug.Assert(calls > 0);
    }
}

A: You could use Fody to automatically inject code that raises the PropertyChanged event for all properties of the model classes at compile time.
Then you could bind directly to Rectangle without modify it and explicitly implement the INotifyPropertyChanged interface.
Othwerwise I am afraid that you will have to define each property, one-by-one, in each view model or come up with a way to auto-generate the view model classes before you build.

A: Is something like this what you're looking for?
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;

public class Rectangle : INotifyPropertyChanged
{
    private double height;

    public double Width { get; set; }
    public double Height { get => height; set => SetField(ref height, value); }

    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
            return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
    #endregion
}

public class RectangleViewModel : MagicViewModel<Rectangle>
{
    public RectangleViewModel(Rectangle model)
        : base(model)
    {
        this.model = model;
        model.PropertyChanged += (s, e) => OnPropertyChanged(e.PropertyName);
    }

    private Rectangle model;

    public Rectangle Model { get => model; set => SetField(ref model, value); }
}

public class MagicViewModel<TModel> : INotifyPropertyChanged
{
    protected readonly TModel _model;

    public MagicViewModel(TModel model)
    {
        _model = model;
    }

    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
            return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
    #endregion
}

public class Program
{
    public static void Main(string[] args)
    {
        var vm = new RectangleViewModel(new Rectangle());
        var calls = 0;
        vm.PropertyChanged += (sender, propChangedArgs) => calls++;
        vm.Model.Height = 10;  // magic happened here
        Debug.Assert(calls > 0);
    }
}


text:
Q: Form not validation failed on hitting the url twice I have one model form for entering product detail. After submitting it I am validating this form in a view and returning another HTML page. It is working fine.
Now on another page, where I am coming after submitting the form, I am doing 2 things:
1. Refreshing the page by clicking on the refresh icon: In this case, validation is happening as usual.
I am facing a problem when I am doing this 2nd thing:

*When I hit the same URL again then the form validation is failing.

Why? Can anyone please help me?
Url for getting the form:
 /createProduct

Url for submitting the form:
/saveProduct

This is my model form:
#Model form for Product model
class ProductForm(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-
control','placeholder':'Product Name','name':'product-name'}))
category = forms.ModelChoiceField(widget=forms.Select(attrs={'class':'form-control','selected':'Select Product Category','name':'product-category'}),queryset=Category.objects.all())
description = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Product Description','name':'product-description'}))

price =forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Product Price','name':'product-price'}))
contact =forms.IntegerField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Provide your contact no','name':'poster-contact'}))

class Meta:
    model = Product
    #fields = ('name','category', 'image','description','price')
    fields = ('name','category','description','price','contact')

This is the view for rendering product form:
def create_product_fn(request):
 form = ProductForm()
 return render(request, 'olx/product/create_product.html', {'form': form})

This is the view where I am coming after submitting the form:
def  save_new_product(request):
 if request.user.is_authenticated:

   formToSave = ProductForm(request.POST,request.FILES)

   if formToSave.is_valid():

     # Instead of saving it store it in session to save it later

     request.session['save_product_form_data_1'] = request.POST
     request.session['save_product_form_data_2'] = request.FILES

   else:
      # if form is not valid, returning to form to enter product detail again
      return create_product_fn(request,info)

   return render(request, 'olx/product/upload_product_photos.html')
 else:
   print('session expired')
   return render(request, 'olx/login.html')


text:
Q: inject required dependency to a bind directly in the register method This is my register method. I have two binds. The second CaptionOrderSubmission is the one that interest me.
public function register()
{
    $clientKey = env('REV_CLIENT_API_KEY');
    $userKey = env('REV_USER_API_KEY');
    $endPoint = env('REV_URL_END_POINT');

    App::bind('RevAPI\Rev', function($app) use($clientKey, $userKey, $endPoint)
    {
        return new Rev($clientKey, $userKey, $endPoint);
    });

    App::bind('RevAPI\CaptionOrderSubmission', function($app) use($clientKey, $userKey, $endPoint)
    {
        $rev = new Rev($clientKey, $userKey, $endPoint);
        return new CaptionOrderSubmission($rev);
    });

}

How can I do something like?
public function register()
{
    $clientKey = env('REV_CLIENT_API_KEY');
    $userKey = env('REV_USER_API_KEY');
    $endPoint = env('REV_URL_END_POINT');

    App::bind('RevAPI\Rev', function($app) use($clientKey, $userKey, $endPoint)
    {
        return new Rev($clientKey, $userKey, $endPoint);
    });

    App::bind('RevAPI\CaptionOrderSubmission', function($app) use(RevApi/Rev $rev)
    {
        return new CaptionOrderSubmission($rev);
    });

}
is that possible?

A: I found the solution
in the second bind you can do
App::bind('RevAPI\CaptionOrderSubmission', function($app)
{
    $rev = $app->make("RevApi\Rev");
    return new CaptionOrderSubmission($rev);
});


text:
Q: Prove the following automorphism exists Having a field $ℚ(x_1, ... , x_n)/ℚ$, where $x_1, ... , x_n$ are the roots of a polynomial (although I'm not sure if that is of any importance to my question), does there exists a bijection for every permutation $σ$ of $x_1, ... , x_n$ from $ℚ(x_1, ... , x_n)/ℚ$ into itself?
It is supposed to be that way, at least that is what I understand from a sentence of a text. It is supposed to be "obvious".
The issue is that I'm not entirely sure that it is impossible for a given permutation $σ$ to map two different elements of $ℚ(x_1, ... , x_n)/ℚ$ into the same place.
How could one prove that this is never the case?
Any help/thoughts would be rrally appreciated.

A: Yes and no: there is a basic result in Galois theory like that. It's mentioned at this link, at least, the formulation I think you want, which is that every permutation of roots of an irreducible polynomial gives rise to an automorphism of the splitting field of the polynomial.
See lemma 18.3 in Isaacs Graduate Algebra for example.


text:
Q: Tokenize an environment variable and save the resulting token in a char** I'm attempting to create an array of strings that represent the directories stored in the PATH variable. I'm writing this code in C, but I'm having trouble getting the memory allocation parts working.
char* shell_path = getenv ("PATH");
char* tok = strtok (shell_path, SHELL_PATH_SEPARATOR);
int number_of_tokens = 0, i = 0;

while (tok != NULL)
{
    number_of_tokens++;
}

Shell_Path_Directories = malloc (/* This is where I need some help */);
shell_path = getenv ("PATH");
tok = strtok (shell_path, SHELL_PATH_SEPARATOR);
while (tok != NULL)
{
    Shell_Path_Directories[i++] = tok;
    tok = strtok (NULL, SHELL_PATH_SEPARATOR);
}

The issue I'm having is that I can't think of how I can know exactly how much memory to allocate.
I know I'm tokenizing the strings twice, and that it's probably stupid for me to be doing that, but I'm open to improvements if someone can figure out a better way to do this.

A: You can do:
Shell_Path_Directories = malloc (sizeof(char*) * number_of_tokens);

Also the way you are counting the number_of_tokens is incorrect. You need to call the strtok again in the loop passing it NULL as the 1st argument:
while (tok != NULL) {
    number_of_tokens++;
    tok = strtok (NULL, SHELL_PATH_SEPARATOR);

}

A: Just to give you basically the same answer as user411313's in a different dialect:
char* shell_path = getenv ("PATH");

/* Copy the environment string */
size_t const len = strlen(shell_path)+1;
char *copyenv = memcpy(malloc(len), shell_path, len);

/* start the tokenization */
char *p=strtok(copyenv,SHELL_PATH_SEPARATOR);
/* the path should always contain at least one element */
assert(p);

char **result = malloc(sizeof result[0]);
int i = 0;

while (1)
{
  result[i] = strcpy(malloc(strlen(p)+1), p);
  p=strtok(0,SHELL_PATH_SEPARATOR);
  if (!p) break;
  ++i;
  result = realloc( result, (i+1)*sizeof*result );
}

A: Since you've counted the number of tokens already, you can use that as the number of pointers to char to allocate:
char **Shell_Path_Directories = malloc(number_of_tokens * sizeof(char *));

Then you have one more minor issue: you're using strtok directly on the string returned by getenv, which leads to undefined behavior (strtok modifies the string you pass to it, and you're not allowed to modify the string returned by getenv, so you get undefined behavior). You probably want to duplicate the string first, then tokenize your copy instead.

A: You should not change the getenv-return pointer, safer you make a copy. With strtok you can destroy the content of your environment table.
char* shell_path = getenv ("PATH");
char *p,*copyenv = strcpy( malloc(strlen(shell_path)+1), shell_path );
char **result = 0;
int i = 0;
for( p=strtok(copyenv,SHELL_PATH_SEPARATOR); p; p=strtok(0,SHELL_PATH_SEPARATOR) )
{
  result = realloc( result, ++i*sizeof*result );
  strcpy( result[i-1]=malloc(strlen(p)+1), p );
}


text:
Q: VSO Share Repository Browse Only? Not exactly like this - How to publicly share a Visual Studio Online Repository? - I am trying to share the source code repository (Git) from Visual Studio Online to registered stakeholders. They need to get at the latest stuff at the Master branch to eval it along with work items. How can I do that?
Thanks.

A: If you have people with a Stakeholder license they won't be able to see the code. The Stakeholder license only gives access to:

*

*View team dashboards and portfolio backlogs

*View, add, and modify items on the backlog

*View, create, and modify work items such as stories, features, and bugs

*View, create, and save queries

*Create and receive alerts when changes are made to work items

*Submit, view, and change your feedback responses.

For people to see the code, they will at least need a Basic license. If you then want to restrict their access, you can do so by creating a TFS Group and setting the correct permissions. In this case, you want to limit the Code permissions to only Read so they can't modify the code.
See Permission reference for Team Foundation Server for more information.
This means there is no free way to allow users to read your code. You do start with 5 free basic licenses however, so if that's enough you can assign those to your users.


text:
Q: How should I set up UITableViewCell subclasses with UIControls in them? I have a dynamically generated UITableView (so I have to use prototype cells, not static cells) with many cells on it.  Each cell will have a UILabel on it.  Additionally, each cell will also have at least one UIControl (as of right now, it could be a UITextfield or a UISegmentedControl, but I want to keep it flexible in case I add something else in the future).
The user is going to go through and set all the controls to the state they want, then press a "Calculate" button at the end.  On the click of that button, I'm going to need to be able to get information about what the user did with each control (what text the user has entered into each textfield, which segement they have selected in each control, etc.).
What would be the best way to set this up?

A: You should be getting these values from the model object that populates the table, not from the table itself. It's hard to know how you should do this without knowing more about your data source, and what values you need when the user clicks a button -- do you need values from all the rows? From just the row whose cell has the label cellLabel (if so, how do you know which cellLabel to pass to the method)?
How much it can be cleaned up depends to a great extent on the structure of your data.

A: Right now, I have several UICell subclasses, one for each combination I've needed so far (so I have a LabelTextboxCell, LabelSegmentCell, LabelSegmentTextboxCell, LabelTextTextCell, etc.).  When I do the call to get the information for that cell, the code in my call looks like:
-(NSString *) getValueFor:(NSString *)cellLabel fromControl:(NSInteger *)controlCount inTable:(UITableView *)table
{
    if ([cellLabel isEqualToString:@"Label1"] || [cellLabel isEqualToString:@"Label3"])
    {
        for (LabelTextboxSegmentCell *cell in table.visibleCells)
        {
             if ([cell.label.text isEqualToString:cellLabel])
             {
                 if (controlCount == 1)
                 {
                     return cell.textfield.text;
                 }
                 else if (controlCount == 2)
                 {
                     return [cell.segment titleForSegmentAtIndex:[cell.segment selectedSegmentIndex]];
                 }
             }
             //else {continue - this is not the cell I want)
         }
    }
    else if ([cellLabel isEqualToString:@"Label2"])
    {
        //...same for loop structure and such as before except specific to LabelTextTextCell
    }
    //.... couple more else ifs and their loops
}

This is terrible.  It works, but it is messy, prone to errors, very hard to add to in the future, and totally against best practice.  But it's the best I've come up with so far.  There has to be a better way.

A: The cells come and go dynamically in a tableView. It'll drive you crazy using them to store values. I suggest using a mutable array to store data and to supply the cells with what they need.
Here's a solution in 3 simple steps.
1, subclass one UITableCell and use it for all of your prototype cells. All you have to do in the cell subclass is set all the properties that ANY of the elements in your cells (and synthesize them in the .m file)
2, in the IB, set the class for all of your cells as that UITableCell subclass you just made, and here's the crucial part, in IB, control-drag from the cell to whatever elements (in that cell) you want to link to. This is imperative for step three to work.
3, in your UITableViewController, in the cellForRowAtIndexPath: method, use your cell subclass and tag anything you want in it with the index of the tableView (which you get in that method call for a cell).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellOneID = @"CellOne";
    MySubclassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...

    cell.textFieldOne.tag = indexPath.row;
    cell.textFieldOne.delegate = self;

    cell.labelTwo.text = [myMutableArray objectForIndex:indexPath.row];
    cell.labelTwo.tag = indexPath.row;

    return cell;
}

You can change the label text by changing the corresponding object in the array and then calling:
[self.tableView reloadData];

Then, when your textField calls to say stuff is happening to it, you can check it's tag and know which one it is. (of course by implementing the UITextField delegate methods in the VC)


text:
Q: Rails 3 accepts_nested_attributes_for form for new model (instead of full collection) I have a model Album which has a "has_many :trough" assocation named Track. Basically, an album can have a number of tracks on it, but a track can belong to more than one album at the same time (hence the through association "Tracklist").
I have a RESTful app with a form (with the help of formtastic) that puts out all the tracks's attributes like so
form.semantic_fields_for :tracks do | builder |
    builder.fields
end

The form puts out all the associated Tracks' fields and I can update them fine, everything works.
Now, what I want to do is have another view to add a new track to an existing album. In this view, I don't want to render all the input fields for the existing tracks, but only the fields for the single new association I am trying to create.
I have tried to find info on how to do this, and the best I've come up with is:
form.semantic_fields_for :tracks, Track.new do | builder |
    builder.fields
end

This outputs a single set of Track inputs, like needed, and I can submit the form and the track gets created and associated to the product - but only if there are no validation errors.
The problem comes with validations. If one fails, the app renders the same view again, but all the inputs are empty again (all data, valid or not, is lost, and the inline error messages for Formtastic are also gone):
 form.semantic_fields_for :tracks, Track.new do | builder |
        builder.fields
 end

I reckon this is because I do a Track.new even though there is already an object in the request params which has the data and error messages. This is no good of course. What I want to have is the form for the single track displayed with the already input data, as well as the Formtastic error messages.
What am I doing wrong?

A: Instead of
Track.new

you need to set up
@track = @album.tracks.build

in your controller and use that. That should preserve the fields through the validation errors.

A: I found a solution. It works, but I wonder if it is a good solution. Thanks Srdjan for putting me on the right track!
@track = @album.tracks.build

form.semantic_fields_for :tracks, @track do | builder |
   builder.fields if builder.object.new_record?
end

Apparently only renders the new record's form fields.


text:
Q: How can I sum up data in tree-like structure in SQL from children to parent? I have a query for selecting amounts per department in a tree-like structure. I want to display the sum amount of the children on their respective parent.
Is it possible to archive this in a query without using a cursor?
Below is a resultset of the data to sum up. A full sample can also be found on sqlfiddle.
Results:
| DEPARTMENT_ID | PARENT_DEP_ID |     DEPARTMENT |          AMOUNT |
|---------------|---------------|----------------|-----------------|
|             1 |             0 |              1 |               0 |
|             7 |             1 |             11 |               0 |
|            34 |             7 |            111 |               0 |
|           120 |            34 |           1111 |               0 |
|           402 |           120 |         111101 |               0 |
|           651 |           402 | 11110101/10000 | 227470.72339635 |
|           651 |           402 | 11110101/10000 |  52255.99610869 |
|           651 |           402 | 11110101/10000 |   4437.15281795 |
|           651 |           402 | 11110101/10000 |   4552.70289465 |
|           651 |           402 | 11110101/10000 |   8510.61790448 |
|           651 |           402 | 11110101/10000 |         8266.08 |
|           651 |           402 | 11110101/10000 |         9968.16 |
|           651 |           402 | 11110101/10000 |          242.58 |
|           403 |           120 |         111102 |               0 | <= this is where i
|           652 |           403 | 11110201/10005 |  120384.7842412 |    want to have my
|           652 |           403 | 11110201/10005 | 488733.59476206 |    sum from the
|           652 |           403 | 11110201/10005 |    2318.6573888 |    child items
|           652 |           403 | 11110201/10005 |  23690.22829273 |
|           652 |           403 | 11110201/10005 | 38321.261680815 |
|           652 |           403 | 11110201/10005 |         6199.56 |
|           652 |           403 | 11110201/10005 |         7476.12 |
|           652 |           403 | 11110201/10005 |          161.92 |

A: This will get the full report
SELECT t1.DEPARTMENT_ID
     , t1.PARENT_DEP_ID
     , t1.DEPARTMENT
     , Sum(t2.Amount) Amount
FROM   TREE_DATA t1
       INNER JOIN TREE_DATA t2
       ON t1.DEPARTMENT = SUBSTR(t2.DEPARTMENT, 1, LENGTH(t1.DEPARTMENT))
WHERE  t1.Amount = 0
GROUP BY t1.DEPARTMENT_ID, t1.PARENT_DEP_ID, t1.DEPARTMENT

UNION ALL

SELECT DEPARTMENT_ID
     , PARENT_DEP_ID
     , DEPARTMENT
     , Amount
FROM   TREE_DATA
WHERE  Amount > 0
ORDER BY DEPARTMENT

The first query get the rolling sum by hacking the structure of the Department name for the oens without the amounts, the second one get the leafs.
The first query cannot show the leafs, as they will get grouped.
I haven't found any column combination to get the same order, the leafs seems to be unordered.
SQLFiddle demo
I've tried to write a recursive CTE, but it's not possible to have aggregate function, such as SUM in it.

A: with rec(parent_dep_id, department_id, depth) as (
  select cast(null as int), 403, 0 from dual
  union all
  select rec.department_id, t.department_id, depth+1
  from rec
     , tree_data t
  where depth<100
    and rec.department_id = t.parent_dep_id
) select sum(t.amount)
  from rec
  join tree_data t
      on rec.department_id = t.department_id

One can avoid the final join on tree_data by including amount in rec.


text:
Q: `np.any` returns an object from an object array instead of boolean? Ok, in trying to answer this question I came across something very strange.
matrix = np.zeros(10000)
matrix[np.random.choice(10000, 100)] = np.random.rand(100)
matrix = matrix.reshape(10, 1000)

from scipy.sparse import lil_matrix
l = lil_matrix(matrix.T)
l.rows

Out: array([[], [], [], ..., [], [], []], dtype=object)

Ok, so I want to know which rows have data, so I tried:
np.any(l.rows)

Out: [8]

. . . what?
out = np.any(l.rows)
type(out)

Out: list

It's a list.  With an 8 in it.  Which seems . . . random.  What is going on?
After playing around it seems it returns the first object in the array that's not [].
np.random.seed(9)
matrix = np.zeros(10000)
matrix[np.random.choice(10000, 100)] = np.random.rand(100)
matrix = matrix.reshape(10, 1000)

from scipy.sparse import lil_matrix
l = lil_matrix(matrix.T)
l.rows

Out: array([[], [], [5], ..., [], [], []], dtype=object)

np.any(l.rows)
Out: [5]

But considering np.any is only supposed to output boolean or np.array of boolean, this is a very strange result.  Does anyone know why this happens?

A: I found it.  Apparently it's been on the Easy Fix list since 2014, but finally has someone working on it since last week.
Should have figured I'm not the first dummy to try something like that.
Also, the correct usage in this case would be:
l[l.rows.astype(bool)]
Out:
<97x10 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in LInked List format>


text:
Q: eBay API additem returns error when creating Buy It Now listing I am using the following code to list items in eBay through their API. However, the code below only creates auction type listings.
I was just wondering if anyone knows how I can create buy it now items/listings instead?
Thank You
This is my XML request.
<?xml version="1.0" encoding="utf-8" ?>
<AddItemRequest
    xmlns="urn:ebay:apis:eBLBaseComponents">
    <RequesterCredentials>
        <eBayAuthToken>AgAAAA</eBayAuthToken>
    </RequesterCredentials>
    <DetailLevel>ReturnAll</DetailLevel>
    <ErrorLanguage>en_US</ErrorLanguage>
    <Version>949</Version>
    <Item>
        <Site>US</Site>
        <PrimaryCategory>
            <CategoryID>45114</CategoryID>
        </PrimaryCategory>
        <ItemSpecifics>
            <NameValueList>
                <Name>Brand</Name>
                <Value>Unbranded</Value>
            </NameValueList>
            <NameValueList>
                <Name>MPN</Name>
                <Value>Does Not Apply</Value>
            </NameValueList>
            <NameValueList>
                <Name>Model</Name>
                <Value>mp02</Value>
            </NameValueList>
            <NameValueList>
                <Name>Country/Region of Manufacture</Name>
                <Value>United States</Value>
            </NameValueList>
        </ItemSpecifics>
        <ConditionID>1000</ConditionID>
        <BuyItNowPrice currencyID="USD">30.00</BuyItNowPrice>
        <Country>US</Country>
        <Currency>USD</Currency>
        <DispatchTimeMax>3</DispatchTimeMax>
        <ListingDuration>Days_7</ListingDuration>
        <ListingType>Auction</ListingType>
        <LiveAuction>TRUE</LiveAuction>
        <LotSize>11</LotSize>
        <Location>san jose, CA</Location>
        <PaymentMethods>PayPal</PaymentMethods>
        <PayPalEmailAddress>usasiva@gmail.com</PayPalEmailAddress>
        <PictureDetails>
            <PictureURL>http://www.qbforms.com/api/shopfunc/Penguins.jpg</PictureURL>
        </PictureDetails>
        <PostalCode>95125</PostalCode>
        <Quantity>1</Quantity>
        <RegionID>0</RegionID>
        <StartPrice>20.00</StartPrice>
        <ShippingTermsInDescription>True</ShippingTermsInDescription>
        <Title>tak_test2_31</Title>
        <Description>itemXYZzx</Description>
        <ReturnPolicy>
            <ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>
            <RefundOption>MoneyBack</RefundOption>
            <ReturnsWithinOption>Days_30</ReturnsWithinOption>
        </ReturnPolicy>
        <ShippingDetails>
            <ShippingType>Flat</ShippingType>
            <ShippingServiceOptions>
                <ShippingService>USPSMedia</ShippingService>
                <ShippingServiceCost>2.0</ShippingServiceCost>
            </ShippingServiceOptions>
        </ShippingDetails>
    </Item>
</AddItemRequest>

A: If I understand correctly, and you are trying to create a Buy it Now listing instead of an auction listing, then it's simple: you just need to use a different API call AddFixedPriceItem.
Here is the API reference with all the details.


text:
Q: Bootstrap multiple bars on horizontal progress bar Does anyone knows how to come up with a bar like this on Bootstrap?

A: here is a jsfiddle
div
{
    height:50px;
    width:100%;
    background: repeating-linear-gradient(90deg,
      transparent, transparent .25em /* black stripe */,
      #EA9949 0, #EA9949 .75em /* blue stripe */
    );
}

Update
here is how to make it works jsfiddle
function setProgressbarValue(currentValue,MaxValue)
{
    var percentage = ((currentValue/MaxValue) * 100) ;
    if (percentage <= 0)
        percentage = 0;
    else if (percentage >= 100)
        percentage = 100;
    return parseInt(percentage);
}


text:
Q: Discontinuity of the Laplacian I'm searching for a proof of the following fact:

For every $d$ there is a sequence $\{\phi_n\}_{n\in \mathbb{N}} \subseteq C_c^{\infty}(\mathbb{R}^d)$ that converges to $0$ in $L^2(\mathbb{R}^d)$, such that $\Delta \phi_n$ does not converge to $0$ in $L^2(\mathbb{R}^d)$.

As I couldn't find a proof anywhere, I'd appreciate it if anyone could sketch an example of such sequence.

A: Maybe an easy example in $ [0,1] $ first, something like $ \frac{1}{n} \sin(n \pi x) $. Now you can extend to $ \mathbb{R} $ smoothly with some bump function.
Note: Neal's example of gaussian is nicer, but I think he didn't mean $ \frac{1}{\sigma} $ as a prefactor? It is also not compactly supported.


text:
Q: How to Reach the Next Element in HTML I am having trouble with my code not printing all the strings that I want and I am unsure of how to edit my code to change that.
I am trying to scrape all the strings including things like 460 hp @ 7000 rpm which it is currently not scraping. Ideally the strings in the strong elements are kept separate. I have tried adding another .next_sibling, changing the br to p and strong they just return an error.
The HTML is as follows:

     Displacement:
     " 307 cu in, 5038 "

     Power:
     " 460 hp @ 7000 rpm "

     Torque:
     " 420 lb-ft @ 4600 rpm "

     TRANSMISSION:
     " 10-speed automatic with manual shifting mode "

     CHASSIS

     " Suspension (F/R): struts/multilink "

     " Brakes (F/R): 15.0-in vented disc/13.0-in vented disc "

     " Tires: Michelin Pilot Sport 4S, F: 255/40ZR-19 (100Y) R: 275/40ZR-19 (105Y) "

I have written the following code thus far:
import requests
from bs4 import BeautifulSoup

URL = requests.get('https://www.LinkeHere.com')

soup = BeautifulSoup(URL.text, 'html.parser')

FindClass = soup.find(class_='specs-content')
FindElement = FindClass.find_all('br')

for Specs in FindElement:
    Specs = Specs.next_sibling
    print(Specs.string)

This returns:

Power:
Torque:
Suspension (F/R): struts/multilink
Brakes (F/R): 13.9-in vented disc/13.0-in vented disc
Tires: Michelin Pilot Sport 4S, 255/40ZR-19 (100Y)

A: You can use the get_text() method with adding a newline \n as the separator argument:
from bs4 import BeautifulSoup

html = """THE ABOVE HTML SNIPPET"""

soup = BeautifulSoup(html, "html.parser")

for tag in soup.find_all(class_="specs-content"):
    print(tag.get_text(strip=True, separator="\n").replace('"', ""))

Output:
Displacement:
 307 cu in, 5038
Power:
 460 hp @ 7000 rpm
Torque:
 420 lb-ft @ 4600 rpm
TRANSMISSION:
 10-speed automatic with manual shifting mode
CHASSIS
 Suspension (F/R): struts/multilink
 Brakes (F/R): 15.0-in vented disc/13.0-in vented disc
 Tires: Michelin Pilot Sport 4S, F: 255/40ZR-19 (100Y) R: 275/40ZR-19 (105Y)


text:
Q: How to add tasks to azure dev ops starter? I am new to azure dev ops and yml files. I recently created an Azure dev ops starter resource for a .NET Core site I built. I connected it to a github repo and pushed some files.
I am getting the error:
Build FAILED.
/home/runner/.dotnet/sdk/3.1.302/Microsoft.Common.CurrentVersion.targets(1177,5): error MSB3644: The reference assemblies for .NETFramework,Version=v5.0 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application
I researched the issue and came up with this solution  https://stackoverflow.com/questions/65079876/error-msb3644-the-reference-assemblies-for-framework-netframework-version-v5#:~:text=assemblies%20for%20framework%20%22.-,NETFramework%2CVersion%3Dv5.,SDK%20or%20Targeting%20Pack%20installed.
However I have no idea how to actually implement this.
Do I create a separate yml file and it just fixes it when I push it to git?
I tried adding the following block to the devops-starter-workflow.yml file that was autogenerated by azure in the repo when it was auto created :
- task: UseDotNet@2
  displayName: 'Use .NET Core sdk 5.0.100'
  inputs:
    packageType: 'sdk'
    version: '5.0.100'
    includePreviewVersions: true

- task: DotNetCoreCLI@2
  displayName: 'dotnet restore'
  inputs:
    command: restore
    projects: '**/*.csproj'

but I got the error "every step must define a uses or run key"
How do I actually add this to my build? I dont see a pipeline anywhere in my azure portal.

A: Are you specifying the MS Agent vs2017-win2016
Here is an example of one I have made should help you to figure it out your error looks to me like you are using the wrong agent as it cant find Visual Studio Code to be able to build the .Net App.

trigger:
  branches:
    include:
    - master

pr: none

pool:
   vmImage: vs2017-win2016

variables:
  System.Debug: false
  azureSubscription: 'AzureSub'
  RG: 'myrg'
  Location: UK South
  appconnectionname: 'azuresub/serviceprinciplename'

jobs:

  - job: job1
    displayName: Create And Publish Artifact

    steps:

    - task: UseDotNet@2 ## Not Needed For MS Self Hosted Agent.
      displayName: Use .Net Core 5.0.301 SDK
      inputs:
        packageType: 'sdk'
        version: '5.0.301'

    - task: DotNetCoreCLI@2
      displayName: dotnet restore
      inputs:
        command: restore
        projects: 'Website.csproj'

    - task: DotNetCoreCLI@2
      displayName: dotnet build
      inputs:
        projects: 'Website.csproj'
        arguments: '--configuration Release'

    - task: DotNetCoreCLI@2
      displayName: dotnet restore unit tests
      inputs:
        command: restore
        projects: 'UnitTests/UnitTests.csproj'

    - task: DotNetCoreCLI@2
      displayName: dotnet Test
      inputs:
        command: test
        projects: 'UnitTests/UnitTests.csproj'
        arguments: '--configuration Release'

    - task: DotNetCoreCLI@2
      displayName: dotnet publish
      inputs:
        command: publish
        projects: 'Website.csproj'
        arguments: '--configuration Release --output $(Build.ArtifactStagingDirectory)'
        zipAfterPublish: true
        modifyOutputPath: false

    - task: PublishPipelineArtifact@1
      displayName: Publish Pipeline Artifact
      inputs:
        targetPath: '$(Build.ArtifactStagingDirectory)'
        artifact: 'Website'
        publishLocation: 'pipeline'

  - job: job2
    displayName: Create Web App
    dependsOn: job1
    steps:

    # Download Artifact File
    - download: none
    - task: DownloadPipelineArtifact@2
      displayName: 'Download Build Artifacts'
      inputs:
        patterns: '**/*.zip'
        path: '$(Build.ArtifactStagingDirectory)'

    # deploy to Azure Web App
    - task: AzureWebApp@1
      displayName: 'Azure Web App Deploy: nsclassroom'
      inputs:
        package: $(Build.ArtifactStagingDirectory)/**/*.zip
        azureSubscription: $(azureSubscription)
        ConnectedServiceName: $(appconnectionname)
        appName: 'nsclassroom'
        ResourceGroupName: $(RG)

Please put this in a YAML formatter in Azure DevOps to just check spaces or install YML Extension in VS Code.

A: In the portal I created a seperate Web App and set the service to .Net version 5 instead of Core v3 and was able to build it properly. A new yml file was created and I had to just update the build and publish processes to the path with my csproj.
I think all along I needed the webapp - not devops starter


text:
Q: Function "chaining" with && operator returns undefined I have these functions:
function A1()
{
    return B() && C();
}

function A2()
{
    return
        B() &&
        C();
}

function B()
{
    return true;
}

function C()
{
    return true;
}

Calling A1 returns true, but A2 returns undefined. The only difference between A1 and A2 is white space. What is going on? In my real code, I do not want to write my A1 function a as a single line because it will be very long and not very readable.

A: You are falling victim to automatic semicolon insertion. The interpreter will add a semicolon after your return statement, so this is effectively what's happening:
function A2()
{
    return;
    //    ^ Automatically inserted semicolon
        B() &&
        C();
}

Since you now have a return statement with no explicit return value, the function will return undefined.
If you look at the grammar for return statements in the spec:

ReturnStatement :
    return [no LineTerminator here] Expression;

You can see that it does not allow line terminators between the return keyword and the expression (this is known as a "restricted production"). If a line terminator is encountered, the third rule of automatic semicolon insertion applies:

When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no LineTerminator here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

I do not want to write my A1 function a as a single line because it will be very long...

You can still break your return statement over multiple lines, you just need to be careful about where you put the line breaks (just make sure they occur in the Expression rather than before it):
function A2()
{
    return B() &&
    //           ^ Invalid to put a semicolon here, so ASI doesn't apply
        C();
}

A: return (
    B() &&
    C()
);

will work as well


text:
Q: How do I retrieve image from Informix and Oracle database in Python? I am writing a python script to get image data (blob) from Informix/Oracle database and upload images to AWS S3. Part of my code is as below:
try:
    cur = conn.cursor()
    cur.execute(sql)

    for row in cur:
        client = trim(row[0])
        date = trim(row[1])
        filename = trim(row[2])
        imageblob = row[3].read()
        write_file(filename, imageblob)

I got the following error (Informix case):
Error: <class '_informixdb.InterfaceError'>
Traceback (most recent call last):
  File "UploadImagesToS3.py", line 57, in getImageFromDB
    imageblob = row[3].read()
InterfaceError: Sblob is not open

Could anyone give a help? The code needs to be compatible with both Informix and Oracle DB. Thanks