text:
Q: Detecting when right mouse button was clicked only My table has 4 columns, and I only want column 1 to be allowed to be clicked. Also, this code also allows the LEFT mouse button to be used, I only want the RIGHT button.
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    int iCol = jTable1.getSelectedColumn();

    if(iCol == 1 && evt.getModifiers() == InputEvent.BUTTON3_MASK)
    {
        if(evt.getClickCount() == 2)
        {
            int iRow = jTable1.getSelectedRow();

            File iFile = new File(jTable1.getValueAt(iRow, iCol).toString());

            String iPath = iFile.getAbsolutePath();
            File iDir = new File(iPath.substring(0, iPath.lastIndexOf(File.separator)));

            if(Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().open(iDir);
                } catch (IOException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

I'm sorry if this question turned out as 2.

A: Lets start with, left button is normally represented by MouseEvent.BUTTON1, then move onto MouseEvent#getModifiers is usually used to provide information about what keys are currently pressed and we begin to see the major problems.
The method you really want is MouseEvent#getButton
Try run the following example for some ideas ;)
public class TestMouseClicked {

    public static void main(String[] args) {
        new TestMouseClicked();
    }

    public TestMouseClicked() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new MousePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MousePane extends JPanel {

        private JToggleButton leftButton;
        private JToggleButton middleButton;
        private JToggleButton rightButton;

        public MousePane() {
            setLayout(new GridBagLayout());

            leftButton = new JToggleButton("Left");
            middleButton = new JToggleButton("Middle");
            rightButton = new JToggleButton("Right");

            add(leftButton);
            add(middleButton);
            add(rightButton);

            ButtonGroup bg = new ButtonGroup();
            bg.add(leftButton);
            bg.add(middleButton);
            bg.add(rightButton);

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println(e.getButton());
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        leftButton.setSelected(true);
                    } else if (e.getButton() == MouseEvent.BUTTON2) {
                        middleButton.setSelected(true);
                    } else if (e.getButton() == MouseEvent.BUTTON3) {
                        rightButton.setSelected(true);
                    }
                }
            });

        }

    }

}

A: Concerning the clicking only of a specific column:

1. create the table using you own model.
final JTable table = new JTable( new MyTableModel(data, columnNames));

2. create the new model overriding the function you need (i.e. isCellEditable)
public class MyTableModel extends DefaultTableModel {

    private static final long serialVersionUID = -8422360723278074044L;

    MyTableModel(Object[][] data, Object[] columnNames )
    {
      super(data,columnNames);
    }

    public boolean isCellEditable(int row,int cols)
     {
       if(cols==1 ){return true;}
          return false;
     }
}


text:
Q: Idle Oracle connections give error 'ORA-03114: not connected to ORACLE' We have a Node.js web application that connects to an Oracle DB instance, The problem is after some inactivity, connections of the database is turned to read-only mode. It means SELECT operations work but INSERT and UPDATE transactions encounter this error:

"Error: ORA-03114: not connected to ORACLE"

This problem solves after restarting the application. We use the last version of knex(0.20.1) and node-oracledb(4.1.0) library to connect to the database.

A: The error means that something (probably a firewall) has expired a connection.  You should track down the cause and eliminate it.  There may be work arounds such as configuring the Oracle Net layer to send occasional pings across the network to stop idle connections from being terminated, see https://oracle.github.io/node-oracledb/doc/api.html#connectionha
Both queries and DMLs will be equally affected on the connection that gives the error - all will fail.  I suspect you are using a different (new) connection for the query.
If you are using 19c client libraries (which, by the way, connect to Oracle DB 11.2 or later), then your connection string could use Easy Connect syntax like:
"mydbmachine.example.com/orclpdb1?expire_time=2"

This will perform a keep alive operation on idle connections, sending probes every two minutes.  The general recommendation is to set the period to just less than half the time that connections will be terminated (e.g. by a firewall).  See the tech article Oracle Database 19c Easy Connect Plus Configurable Database Connection
Syntax.
Other syntaxes can be used in older versions, or in tnsnames.ora files; check the doc.

A: I have faced same problem and found the solution.
Add environment variables (system variables)
ORACLE_HOME=installation path in my case F:\app\krushna\product\11.2.0\dbhome_1
and ORACLE_SID= orcl or xe .
Which ever you have.
It worked for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which languages are involved in the configuration of TYPO3? Which languages are involved in the configuration of TYPO3 with default extensions?

A: *

*TypoScript Used for frontend configuration

*

*TyposcriptReference

*Symfony ExpressionLanguage Used for conditions in TypoScript (TYPO3 9+)

*

*Symfony ExpressionLanguage

*Regular Expression Used in TypoScript

*

*Replacement

*config.linkVars

*...

*TSConfig Used for backend configuration

*

*TSconfigReference

*YAML Used for sites configuration (TYPO3 9+)

*

*Site Handling

*PHP Used for extensions, local configuration, TCA, ...

*

*Extension Configuration Files

*Local Configuration

*TCA

*...

*XML Used for FlexForms configuration

*

*FlexForms

*Environment Variables Used to define Application Context (TYPO3_CONTEXT)

*

*Application Context

*JSON For composer.json configuration (Only in case you use composer installation)

*

*Install TYPO3 via composer

*SQL Used in ext_tables.sql to change existing tables or create new tables in database

*

*ext_tables.sql

*Preparing the database
Translations

*

*XML (XLIFF) Used for translation

*

*XLIFF
Templating

*

*FLUID Used as template enging

*

*FLUID

*TypoScript Used for frontend templating

*

*TyposcriptReference
Webserver

*

*Apache Configuration (Apache Webserver only)

*

*mod_rewrite in .htaccess/.conf used for human readable urls

*php settings in .htaccess

*Nginx Configuration (Nginx Webserver only)

*

*Used for human readable urls

*INI

*

*php.ini to define php settings

Maybe i am missing some points, please report in comments :)


text:
Q: need help installing sick lms200 sensor software I have the LIDAR Sick lms200 http://sicktoolbox.sourceforge.net/
I would like to install the driver, but compiling the source ends in error.
I have tried modifying the compilation flags to be c++11 specific in the Makefile CXXFLAGS= -g -std=c++11 -Wall -pedantic
in either case, I havent been able to compile the source.
./configure runs no errors return
make
Makefile:340: recipe for target 'SickLD.lo' failed
make[4]: *** [SickLD.lo] Error 1
make[4]: Leaving directory '/home/ae/sicktoolbox-1.0.1/c++/drivers/ld/sickld-1.0'
Makefile:246: recipe for target 'all-recursive' failed
make[3]: *** [all-recursive] Error 1
make[3]: Leaving directory '/home/ae/sicktoolbox-1.0.1/c++/drivers/ld'
Makefile:251: recipe for target 'all-recursive' failed
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory '/home/ae/sicktoolbox-1.0.1/c++/drivers'
Makefile:246: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/ae/sicktoolbox-1.0.1/c++'
Makefile:362: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1

Make throws a bunch of warnings about c++11 depreciated code, I dont care about any of that, im just trying to make this LIDAR work.
My OS is Ubuntu Mate 18.04


text:
Q: CSS - setting icon as a background to input not working I have a search input field, which has a backround set up like this:
background: #ededed url(https://static.tumblr.com/ftv85bp/MIXmud4tx/search-icon.png) no-repeat 9px center;

But, I would like to replace the image for an icon. I am using and have tried to do it like this:
input[type=search]:before {
  font-family: 'Ionicons';
  content: '\f2f5';
  color: red;
}

This is the fiddle.
But, icon is not visible, what should I do?

A: :before and :after can be used on "container" elements only.  An input is not a container, because it cannot "contain" other elements.
Wrap the input in a span, and apply the :before styles to it:
<input type="search" placeholder="Search">

.container:before {
  font-family: 'Ionicons';
  content: '\f2f5';
  color: red;
  position: absolute;
}

Updated Fiddle

A: You can't use :before or :after on <input> on every browser!
But you can use a solution using a container for the <input>:

div span {
  margin-left:-20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.css" rel="stylesheet"/>

  <input type="text"/>

You can also use a  surrounding the <input> for more accessability:

label[for="search"]:after {
  font-family: 'Ionicons';
  content: '\f2f5';
  color: red;
  margin-left:-20px;
}
label[for="search1"] span {
  margin-left:-20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.css" rel="stylesheet"/>

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

  <input id="search1" name="search1" type="text"/>


text:
Q: How do I use a toString() method to replace a display method? I'm asked to modify the class Staff by replacing the displaySalary() method with the toString() method that returns all required information to be displayed and print S.O.P in the main method but I don't even know where to start because as I have declared, salary is a double, how are we going to use a String? I'm really lost with this. It will be a gratitude if I'm advised where to start.
This is the given code:
class Staff {

    private String name, staffID;
    private double salary;
    private double commission;
    private int workingHours;
    private double Sales;
    public void setStaffInfo(String nm, String id, int wHour, double sale)
    {
        name=nm;
        staffID=id;
        workingHours=wHour;
        Sales=sale;
    }

    public void calculateSalary(){
        salary = (workingHours*8);
    }

    public double displaySalary(){
        return salary;
    }

    public String displayName(){
        return name;
    }

    public String displayStaffID(){
        return staffID;
    }

    public double displayworkingHours(){
        return workingHours;
    }

    public double displaySales(){
        return Sales;

    }

    public void calculateCommission(){

        if(Sales >= 150 && Sales <= 300)
            commission= (0.05*Sales);

        else if(Sales >=301 && Sales <= 500)
            commission= (0.1*Sales);

        else if (Sales > 500)
            commission=(0.15*Sales);

        else
            commission= 0;

    }

    public double displayCommission(){
        return commission;
    }

}

This is the code for the main method:
import java.util.Scanner;
class TestStaff {
    static Scanner scan = new Scanner(System.in);
    public static void main(String arg[]){

        Staff staff1= new Staff();

        System.out.print("Enter your name: ");
        String nm=scan.nextLine();

        System.out.print("Enter your Staff ID: ");
        String id=scan.nextLine();

        System.out.print("Enter your working hours: ");
        int wHour=scan.nextInt();

        System.out.print("Enter your total sales: ");
        double sale=scan.nextDouble();

        staff1.setStaffInfo(nm, id, wHour, sale);
        staff1.calculateCommission();
        staff1.calculateSalary();
        System.out.println("\nStaff Name: " + staff1.displayName());
        System.out.println("Staff ID: " + staff1.displayStaffID());
        System.out.println("Hours worked: " + staff1.displayworkingHours());
        System.out.println("Total sales: RM" +staff1.displaySales());

        double com= staff1.displayCommission();
        double sala= staff1.displaySalary();
        double total= sala+com;

        System.out.println("Salary: RM" + total);

    }
}

A: When put object to System.out.println, the toString method of that object is called.
If you don't provide an overridden version then it will print something likes Staff@123f23 which is the object pointer.
So all you have to do is overload the toString method inside class Staff with your display logic. For example:
@Override
public String toString() {
    double com= staff1.displayCommission();
    double sala= staff1.displaySalary();
    double total= sala+com;

    return "Staff Name: " + staff1.displayName())
    + "\nStaff ID: " + staff1.displayStaffID())
    + "\nHours worked: " + staff1.displayworkingHours())
    + "\nTotal sales: RM" +staff1.displaySales())
    + "\nSalary: RM" + total );
}

A: Just override the to String method like this
public String toString(){
      //write which field you need to show
      return Double.toString(d);
      // Here you append other column as per your need.
}

A: Replace this
System.out.println("Hours worked: " + staff1.displayworkingHours());

with
System.out.println("Hours worked: " + Double.toString(staff1.displayworkingHours()));

and this
System.out.println("Total sales: RM" +staff1.displaySales());

with
System.out.println("Total sales: RM" + Double.toString(staff1.displaySales()));

Logic is, first covert your double column to string by using toString(yourDoubleColumn) and, concatenate string with a string
Ask me if you are still facing issues


text:
Q: Seg Faulting SPARC Assembly I am determining if a number is zero in my function. If it is zero I need to pass some string like "Is Zero" into the variable I have declared as B. My function to determine if it is zero works but when I try to pass the string into the variable B with my SPARC source code I seg fault.
Here is what I have been trying in my C driver:
void display( double, char* );
char B[100];
double x = 0.000;
display(x, &B);

printf("%s", B);

Here is my SPARC code:
 ZERO: .asciz "Is Zero\n"

.global display
.section ".text"
.align 4
display:
         save   %sp, -96, %sp

         mov    %i0, %o0
         mov    %i1, %o1
         mov%i2, %o2

         call   is_zero         ! check if number is zero
         cmp    %o0, 0
         bne    zero
         nop

zero:
        save    %sp, -96, %sp
        set     ZERO, %l0
        ldub    [%l0], %l1
        cmp     %l1, 0          ! exit when zero byte reached
        beq     done
        nop
        stb     %l1, [%i2]
        inc     %l0
        inc     %i2

        ba      zero
        nop
done:
        ret
        restore

A: &B is the pointer to char array B.
display function take a char pointer in 2nd parameter.
display(x, &B) should be display(x, B).


text:
Q: Get number of digits in a base10 integer It bugged me that std::to_string doesn't allow for custom allocators, so I'm writing my own implementation. For this it would be beneficial to know beforehand how many digits I need to allocate string space for. I could do it in multiple ways:
Use a for loop like demonstrated here:
int length = 1;
int x = 234567545;
while (x /= 10)
   length++;

Use base 10 logarithm + 1:
uint32_t x{234567};
double ds = std::log10(static_cast<double>(x)) + 1;
int digits = static_cast<int>(ds);

.. maybe other solutions.
Here's my code:
Demo
#include <concepts>
#include <cstdio>
#include <string>
#include <memory_resource>
#include <cinttypes>

using allocator_t = std::pmr::polymorphic_allocator<std::byte>;

template <std::integral T>
inline auto to_string(T number, allocator_t allocator = {}) -> std::pmr::string {
    // const std::size_t size = ???
    std::pmr::string str{ size, '\0', allocator };
    if constexpr(std::same_as<T, uint32_t>) {
        std::snprintf(&str.front(), size, "%" PRIu32, number);
    } else if constexpr (std::same_as<T, uint16_t>) {
        std::snprintf(&str.front(), size, "%" PRIu16, number);
    } else if constexpr (std::same_as<T, uint8_t>) {
        std::snprintf(&str.front(), size, "%" PRIu8, number);
    }
    // ...
    return str;
}

int main()
{
    uint32_t x = 256;
    printf("My number = %s\n", to_string(x).data());
}

The question is: What is the most efficient and robust way to get the number of digits of an integral number for this use-case?

A: I played around with a few options. Calculating the log base 10 was ridiculously slow (30000+ cycles). The first simple loop (while (x /= 10)) you posted was pretty hard to beat, but here's an option which appears to be a bit faster for inputs with several and similar in performance for those with only a few. The idea behind it was that subtraction/comparison is supposed to be much faster than division.
static inline uint8_t uint32digits(const uint32_t input) {
  uint8_t length = 1;
  length += (input >= 1000000000);
  length += (input >= 100000000);
  length += (input >= 10000000);
  length += (input >= 1000000);
  length += (input >= 100000);
  length += (input >= 10000);
  length += (input >= 1000);
  length += (input >= 100);
  length += (input >= 10);
  return length;
}

I counted machine cycles, which I know isn't a great way to benchmark, but it's simple and doesn't fall into the trap of measuring overly optimised code. For single digit numbers I got 104 vs 72 cycles, for 5 digit numbers I got 96 vs 176 cycles, and for 10 digit numbers 96 vs 240 cycles. As expected, my function's cost is pretty independent of the input.
EDIT:
Actually, this appears to be a little faster still...
static inline uint8_t mynumdigits(const uint32_t input) {
  return 1 + (input >= 1000000000) + (input >= 100000000) + (input >= 10000000) +
         (input >= 1000000) + (input >= 100000) + (input >= 10000) +
         (input >= 1000) + (input >= 100) + (input >= 10);
}

Here's a function template for dealing with all integral types. The only branching here occurs if T is some future type with more than 64 bits or if a signed type is used.
#include <limits>
#include <type_traits>

template <class T>
    requires std::is_unsigned_v<T>
constexpr static inline int intdigits(const T input) {
    int length = 1 + (input >= 10u) + (input >= 100u);

    if constexpr (std::numeric_limits<T>::max() > 0xFF) {
        // T is more than 8 bits
        length += (input >= 1000u) + (input >= 10000u);

        if constexpr (std::numeric_limits<T>::max() > 0xFFFF) {
            // T is more than 16 bits
            length +=
                (input >=       100'000u) +
                (input >=     1'000'000u) +
                (input >=    10'000'000u) +
                (input >=   100'000'000u) +
                (input >= 1'000'000'000u);

            if constexpr (std::numeric_limits<T>::max() > 0xFFFF'FFFF) {
                // T is more than 32 bits
                length +=
                    (input >=             10'000'000'000u) +
                    (input >=            100'000'000'000u) +
                    (input >=          1'000'000'000'000u) +
                    (input >=         10'000'000'000'000u) +
                    (input >=        100'000'000'000'000u) +
                    (input >=      1'000'000'000'000'000u) +
                    (input >=     10'000'000'000'000'000u) +
                    (input >=    100'000'000'000'000'000u) +
                    (input >=  1'000'000'000'000'000'000u) +
                    (input >= 10'000'000'000'000'000'000u);

                if constexpr (std::numeric_limits<T>::max() >
                              0xFFFF'FFFF'FFFF'FFFF)
                {   // T is more than 64 bits - future proofing.
                    // Make the recursive call unconditionally to make
                    // it branchless:
                    if (input > 0xFFFF'FFFF'FFFF'FFFF)
                        return length - 1 + intdigits(
                            input / 10'000'000'000'000'000'000u);
                }
            }
        }
    }
    return length;
}

template <class T>
    requires std::is_signed_v<T>
constexpr static inline int intdigits(const T input) {
    return intdigits(static_cast<std::make_unsigned_t<T>>(std::abs(input)));
}

A: After some tinkering I came up with the following solution:
Demo
#include <concepts>
#include <cstdio>
#include <string>
#include <memory_resource>
#include <limits>
#include <type_traits>

using allocator_t = std::pmr::polymorphic_allocator<std::byte>;

template <std::integral T>
constexpr std::size_t get_max_digits()
{
    T val = std::numeric_limits<T>::max();
    std::size_t cnt=1;
    while (val /= 10) {
        ++cnt;
    }
    if constexpr (std::unsigned_integral<T>) {
        return cnt;
    } else {
        return cnt+1;
    }
}

template <typename T> struct PRI{};
template<> struct PRI<signed char> { static constexpr const char* value = "%hhd"; };
template<> struct PRI<unsigned char> { static constexpr const char* value = "%hhu"; };
template<> struct PRI<char> : std::conditional_t<std::is_signed_v<char>, PRI<signed char>, PRI<unsigned char>>{};
template<> struct PRI<short> { static constexpr const char* value = "%hd"; };
template<> struct PRI<unsigned short> { static constexpr const char* value = "%hu"; };
template<> struct PRI<int> { static constexpr const char* value = "%d"; };
template<> struct PRI<unsigned int> { static constexpr const char* value = "%u"; };
template<> struct PRI<long> { static constexpr const char* value = "%ld"; };
template<> struct PRI<unsigned long> { static constexpr const char* value = "%lu"; };
template<> struct PRI<long long> { static constexpr const char* value = "%lld"; };
template<> struct PRI<unsigned long long> { static constexpr const char* value = "%llu"; };

template <typename T>
inline constexpr const char* PRI_v = PRI<T>::value;

template <std::integral T>
inline auto to_string(T number, allocator_t allocator = {}) -> std::pmr::string {
    constexpr std::size_t size = get_max_digits<T>();
    std::pmr::string str{ size, '\0', allocator };
    const std::size_t written_s = std::snprintf(&str.front(), size+1, PRI_v<T>, number);
    str.resize(written_s);
    return str;
}

int main()
{
    int x = -256325651;
    char ch = 'A';
    printf("Integer as string = %s\n", to_string(x).c_str());
    printf("char as string = %s\n", to_string(ch).c_str());
}

Output:
Integer as string = -256325651
char as string = 65

This will work for all major platforms (tested on x86, RISC-V and ARM) and for all common integral types. I decided allocate for the maximum number of digits and downsize to the actually used digits later. This will give me only one allocation syscall and one call to snprintf while the maxdigits calculation can be done at compile time. It should be reasonably fast.


text:
Q: Large ModelVisual3D stops being rendered I'm trying rending a fairly sizable (triangle count and span over the Viewport3D) ModelVisual3D which disappears if the last triangle (in the MeshGeometry3D of the model) leaves the screen, despite other parts of the model still being on screen.  The particular problem triangle is circled in red in the image below.  I say it's a large model, but when it's rendering properly it doesn't drop frame the frame rate.  There are, however, about 150 of the green arches, all in the same mesh.  Interestingly, the blue line does not exhibit the same problem.
I can work around the problem by breaking up the model into smaller pieces.  But, that's not ideal.
Things that don't work:

*

*Setting Viewport3D.ClipToBounds to false.

*Modifying
FarPlaneDistance or NearPlaneDistance
It may be worth noting that this is being hosted in WinForms.

EDIT: I take it back, the problem still exists even if I break up the model, just on a smaller scale (the last triangle of each model must remain on screen).

A: I've fixed it, but I don't understand the reason it works.
It looks like something about the point spacing around the corners being too small was causing a problem.  I reduced the spacing to .1 units and that seems to work.
If someone knows the reason this could be a problem, I'd love to hear it.


text:
Q: How do I insert a blank line every n lines using awk? I've got an input file like this:
line 1
line 2
line 3
line 4
line 5
line 6

I'd like to use awk to insert a blank line every few lines; for example, every two:
line 1
line 2

line 3
line 4

line 5
line 6

How can I get awk to put a blank line into my file every n lines?

A: More awkishness:
awk 'ORS=NR%5?RS:RS RS'

For example:
$ printf "%s\n" {1..12} | awk 'ORS=NR%5?RS:RS RS'
1
2
3
4
5

6
7
8
9
10

11
12

A: awk '{print; if (FNR % 5 == 0 ) printf "\n";}' your_file

I guess 'print' should be before 'printf', and FNR is more accurate for your task.

A: A more "awk-ish" way to write smcameron's answer:
awk -v n=5 '1; NR % n == 0 {print ""}'

The "1;" is a condition that is always true, and will trigger the default action which is to print the current line.

A: $ awk -v n=5 '$0=(!(NR%n))?"\n"$0:$0'

If you want to change 'n', please set the parameter 'n' by awk's -v option.

A: awk '{ if ((NR % 5) == 0) printf("\n"); print; }'

for n == 5, of course.  Substitute whatever your idea of n is.


text:
Q: Dirty electricity In the book "Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future" by Ashlee Vance it is mentioned that at Elon's house there was a problem with "dirty electricity" that was causing devices to overheat.
I've experienced this in a variety of places with my own devices.
In one case, while traveling abroad, my devices would not work at one of my host's house it was so bad. In fact, his top of the line U.S. blender he had just purchased burnt out within 2 weeks. I didn't have this problem at all with my other host's house in the same country, so I know it's not simply a voltage conversion issue.
What exactly is "dirty electricity", what causes it and is there a simple way to prevent it from doing damage to your electronics while traveling or at home?

A: First, if you're travelling, take care to look at your electrical devices' specs. Electrical standards change the voltage and frequency of the mains. Just because it isn't a "voltage" issue, doesn't mean your blender won't burn up. The wrong frequency can burn out motors.
The main is supposed to supply a sinusoidal of a certain frequency, amplitude, and power factor, \$A*sin(\omega t + \phi)\$. Anything that deviates from this is a flaw.
Things can cause this to deviate from this ideal. Large motors can (strongly) affect \$\phi\$ (therefore changing the power factor) and introduce noise. Non-linear loads can cause harmonics.
Power factor will cause the resistive elements, like the wiring, to heat up (through \$I^{2}R\$) without contributing to work.
As to the blender: harmonics, if not filtered by the device, can burn out electrical motors.


text:
Q: Must a dataset for a classifier be perfectly balanced? In machine learning it is generally accepted that the dataset for a binary classifier has to be balanced: EG. class 1 50%, class 0 50%.
My question is: has the dataset to be perfectly balanced (50/50)? I have a dataset with 1568 observations: class 1 is 47%, class 0 is 53%. Can this create issues?

A: Ideally, having 50% class for each one, will have nice results while training the model, since the model is looking to optimise the accuracy.
For example, imagine you have 99% class 0 and 1% class 1. When training, you will obtain a model that always classify 0, doing that, the model will obtain a general accuracy of 99%, but this is what you want? Balancing this data will help you avoid this type of "silly" models. This is an extreme case, but that's the reason why balanced class are used.
When balancing take care of overfitting with the  minority class, so the model will learn to classify the same sample multiple times.
Finally, if you are using such a balanced data like you say (47%, 53%) balancing is no needed. Probably you can start balancing around 35% / 65% or something like this. Obviously, the behaviour of the data with balancing depends on the datset.


text:
Q: Mongodb $project with $multiply return null I create a $project stage in my Mongodb Compass, in this stage I use $multiply to multiply a datafield with a number as in my screenshot. But why my result always return to null My stage screenshot with null return for TotalScore data field

A: The aggregation work as pipeline so the result of this projection pipeline will give you hop1score field and you won't be able to access it in same operation. So, Either make one more projection or use cond operator as first argument of multiply operator.


text:
Q: Check the CPU name in Powershell I'm trying to know if the processor name is equal or similar to a specific string value, but I don't find a good solution. Here is my code
$nameCPU = WMIC CPU Get Name
Write-host $nameCPU[2]   # The server has two different CPUs

$CheckName = $nameCPU[2] -eq "Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz"

Write-Host $CheckName

The output is something like this :
Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz
False

$CheckName is always False
Someone can help me ? Thanks

A: You can use the Win32_Processor class to get your CPU Name, the cmdlet you should use to query this class is Get-CimInstance.
Normally you would use -eq to compare 2 scalar values however if your server may have more than 1 CPU then the safest way to check it would be by using -in or -contains. Worth noting that both operators look for exact values in an array. Wildcards or regex don't work for them.
$cpuInfo = Get-CimInstance -ClassName Win32_Processor
$cpuInfo.Name -contains "Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz" # should be True


text:
Q: Tensor Product of Two Group Representations (Action Well-definedness) I am studying the basic of representation. Coming back from https://en.wikipedia.org/wiki/Tensor_product_of_representations, I am having trouble filling out details why tensor product of two (finite dimensional) representations $V$ and $W$ over $\mathbb{C}$ of a finite group $G$ is also a representation.
I know Is the tensor product of two representations a representation? has an answer but I cannot understand such "high level" reasoning yet.
From the first link above, the action is defined as $g.(v\otimes w):=(g.v)\otimes (g.w)$, but I am not sure about its well-definedness.
Question 1: This definition cannot be seen as $g$ acting on arbitrary element in the tensor product, right? I mean, isn't arbitrary element in the tensor product a linear combination? Hence, what would the "true" action of $g$ be?
I think if I assume the that $g$ acts on an arbitrary element by linearity (meaning it can pass through the sigma and scalars), then here is my attempt based on my understanding (but I am not sure maybe something is wrong):
We first choose a basis $\{v_i\}$ and $\{w_j\}$ for $V$ and $W$, respectively. Thus, all $\text{dim } V\times \text{dim } W$ elements $v_i \otimes w_j$ form a basis for $V\otimes W$. To show well-definedness, I take elements $a,b\in G$ and two more elements in $V \otimes W$, but the elements in this tensor product is not simply basic tensor, right? Hence, I take $\sum c_{i,j}(v_i\otimes w_j),\sum d_{i,j}(v_i\otimes w_j)\in V\otimes W$ instead. If $a=b$ and $\sum c_{i,j}(v_i\otimes w_j)=\sum d_{i,j}(v_i\otimes w_j)$, then by linear independence, $c_{i,j}=d_{i,j}$ for each $i,j$. Hence, $$\sum c_{i,j}((a.v_i)\otimes (a.w_j)) =\sum d_{i,j}((a.v_i)\otimes (a.w_j))\text{ (by $c_{i,j}=d_{i,j}$)}\\=\sum d_{i,j}((b.v_i)\otimes (b.w_j))\text{ (by well-definedness of each $G$-action on $V$ and $W$)}.$$
Thus, the action map is well-defined. I think showing it satisfies the action property + linearity should be OK.
Question 2: Is the above reasoning correct?
Any suggestion or guidance is really appreciated. Thanks!.

A: A representation $V$ of $G$ is a homomorphism $\rho :G \to GL(V)$, where $GL(V)$ is the group of automorphisms of V.
Then, if $g(v \otimes w)=g(v)\otimes g(w)$ gives a representation $V\otimes W$ of $G$, then it should be an automorphism of $V\otimes W$.
It's not necessary to check arbitrary elements of the tensor product. Indeed, the rule defines the action of $g$ only on elements in the form $v\otimes w$ because, although omitted from the definition sometimes, it's linear, so
$$g(\sum_i \alpha_i (v_i\otimes w_i))=\sum_i \alpha_i g(v_i\otimes w_i).$$
Now, the action is also well-defined, because
$$g((\alpha_1 v_1+\alpha_2v_2)\otimes w) = g(\alpha_1 v_1+\alpha_2 v_2)\otimes g(w) = (\alpha_1 g(v_1)+ \alpha_2 g(v_2))\otimes g(w)$$
$$= \alpha_1 g(v_1)\otimes g(w) +\alpha_2g(v_2)\otimes g(w) = \alpha_1g(v_1\otimes w) + \alpha_2 g(v_2\otimes w)$$
and in the same way,
$$g(v\otimes (\alpha_1 w_1+ \alpha_2w_2)) = \alpha_1g(v\otimes w_1) +\alpha_2g(v\otimes w_2).$$
Also, $ker(g)$ is trivial:
$$g(v\otimes w) = 0 \implies g(v)\otimes g(w)=0 \implies g(v)=0\ \lor \ g(w)=0$$
But since $g$ is an automorphism on $V$ and $W$, then $v=0$ or $w=0$ and $v\otimes w=0$.
Since $g$ is linear and $ker(g)$ is trivial, then $g$ is an automorphism of $V\otimes W$. The fact that $g^{-1}$ is inverse of $g$ as an automorphism follows from definition on $V$ and $W$ and can be checked directly, thus the action of $G$ is isomorphic to a subgroup of $GL(V\otimes W)$, and $V\otimes W$ is a representation of $G$ by $g(v\otimes w) = g(v)\otimes g(w)$.


text:
Q: Genesis Framework Child-Theme Shows Blank Blog Page I'm using the "Pretty Young Thing Child Theme" -- a child-theme developed by Studiopress for their Genesis framework for WordPress. Despite going to General Settings -> Reading Settings, setting "Front Page displays" to "A Static page" and defining and setting the Front page option and Posts page option to their relevant pages, the blog page is appearing blank.
All the post are there but the blog page just appears blank.
Does anybody know how I can solve this?

A: Have you tried:

*

*Setting "Posts page" to --- Select --- (i.e. blank)

*Creating a page named "Blog" (or whatever you want the blog page to
be named) and setting its template to "Blog"?

If that doesn't work, I would go to studiopress.com and post on their forum.


text:
Q: Fully reset a corrupted git submodule in SourceTree First off, I am not using command line git at all. I am only using SourceTree's gui interface. I would prefer to solve my problem this way; if possible.
Somehow, my submodule has become corrupted. Attempting to fetch or pull gives me the following error:

I haven't found any answers for this particular problem. I am fortunate in that my remote master is ok, 100% up to date, and I have no local changes. So, I think the easiest way will be to just fully reset my local submodule.
However, I can't figure out how to do so.
I considered trying to remove my submodule and then re add it. However, I have had problems with that in the past, and so am gun shy.
I found handfuls of posts about resetting to a specific commit. However, the SourceTree gui is failing to populate my history because of this error.
Any help would be appreciated
Thank you

A: You can try this

*

*Right click at your conflicted branch at BRANCHES and delete it.

*Double click at your remote branch at REMOTES to re-download and switch to that branch.

Easy, good luck.

A: I finally did get this fixed. I had to give up and use the command line.
I found this page (git fatal: failed to read object xxx: Invalid argument). That pointed me to using the "git fsck --full" command.
That pointed me to a very specific folder in the .git hierarchy that was corrupted.
I needed to delete this folder, but doing so wasn't easy. Windows would let me delete it. Not in safe mode. Not with cmd del or rmdir. I had to run a scan disk from windows on my entire drive. That ended up detecting the folder and removing it.
Finally, from there, I was able to fetch and pull master again.

A: From all the solutions I was able to find to perform an actually hard reset with proper cleanup and reinitialization of submodules nothing worked. So I ended up creating a custom script. Following will perform a full cleanup of your submodules and will recreate them as if you were cloning the parent repo.
#!/bin/bash

echo "Backing up current .gitmodules"
cp -f .gitmodules .gitmodules.bkp
has_submodules=$(echo "$(git submodule)")
if [ "$has_submodules" != "" ]; then
    git submodule deinit --force .
    rm -rf .git/modules
    git submodule | cut -c43- | while read -r line; do (git rm -f "$line"); done
fi

cp -f .gitmodules.bkp .gitmodules
PARAMS=("path" "url" "branch")
CHUNKS=${#PARAMS[@]}
PARAMS_STR=$(IFS='|'; echo "${PARAMS[*]}")

readarray -t SUBMODULES_INFO_ARRAY < <(git config -f .gitmodules --get-regexp '^submodule\..*\.('"$PARAMS_STR"')$')
SUBMODULES_INFO_ARRAY_STR=$(IFS='|'; echo "${SUBMODULES_INFO_ARRAY[*]}")

function process_submodules_parsed_array()
{
    name=${SUBMODULES_PARSED_ARRAY[0]}
    path=${SUBMODULES_PARSED_ARRAY[1]}
    repo_url=${SUBMODULES_PARSED_ARRAY[2]}
    branch=${SUBMODULES_PARSED_ARRAY[3]}
    echo "Running: git submodule add --force -b "$branch" --depth 1 --name "$name" -- "$repo_url" "$path""
    git submodule add --force -b "$branch" --depth 1 --name "$name" -- "$repo_url" "$path"
}
echo "Parsing current .gitmodules"
for((chunk=0; chunk<${#SUBMODULES_INFO_ARRAY[@]}; chunk+=CHUNKS))
do
    section_name="$(sed -nE 's/^submodule\.(.*?)\.'${PARAMS[0]}'\s(.*?)$/\1/p' <<< "${SUBMODULES_INFO_ARRAY[chunk]}")"
    SUBMODULES_PARSED_ARRAY=("$section_name")
    for ((param_i=0; param_i<CHUNKS; param_i+=1))
    do
    param_unparsed="${SUBMODULES_INFO_ARRAY[chunk+param_i]}"
    param_parsed="$(sed -nE 's/^submodule.*?\.'${PARAMS[param_i]}'\s(.*?)$/\1/p' <<< "$param_unparsed")"
    SUBMODULES_PARSED_ARRAY+=($param_parsed)
    done
    process_submodules_parsed_array
done
echo "Restoring .gitmodules"
mv -f .gitmodules.bkp .gitmodules
echo "Initializing submodules"
git submodule init
git submodule update


text:
Q: Angular/Rxjs - a more specific operator than map() when converting a response object to an array I have a service where my code does work. The problem is want to use a better operator than map() to convert the response object to an array of objects. I have tried toArray() but that seems to wrap the whole response into an array. Any Ideas? See the code below:
getCurrencies() {
const params = new HttpParams().set("key", this.key);
return this.http.get(this.url, { params }).pipe(
  map(resp => {
    const postArry = [];
    for (const key in resp) {
      if (resp.hasOwnProperty(key)) {
        postArry.push({ ...resp[key] });
      }
    }
    return postArry.slice(0, 30);
  })
);

}


text:
Q: Execute nltk.stem.SnowballStemmer in pandas I have a four column DataFrame with two columns of tokenized words that have had stop words removed and converted to lower case and am now attempting to stem.

I'm not sure if the apply() method accesses the series plus its individual cells or if I need another way of stepping into each record so tried both (I think!)
from nltk.stem import SnowballStemmer
stemmer = nltk.stem.SnowballStemmer('english')

I've tried:

df_2['Headline'] = df_2['Headline'].apply(lambda x: stemmer.stem(item) for item in x)

--------------------------------------------------------------------------- TypeError                                 Traceback (most recent call
  last)  in ()
  ----> 1 df_2['Headline__'] = df_2['Headline'].apply(lambda x: stemmer.stem(item) for item in x)
~\AppData\Local\Continuum\anaconda3\envs\learn-env\lib\site-packages\pandas\core\series.py
  in apply(self, func, convert_dtype, args, **kwds)    3192
  else:    3193                 values = self.astype(object).values
  -> 3194                 mapped = lib.map_infer(values, f, convert=convert_dtype)    3195     3196         if len(mapped) and
  isinstance(mapped[0], Series):
pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()
TypeError: 'generator' object is not callable

I believe this TypeError is similar to the one that says 'List' object is not callable and fixed that one with the apply() method and out of ideas here.
df_2['Headline'] = df_2['Headline'].apply(lambda x: stemmer.stem(x))

--------------------------------------------------------------------------- AttributeError                            Traceback (most recent call
  last)  in ()
  ----> 1 df_2['Headline'] = df_2['Headline'].apply(lambda x: stemmer.stem(x))
        2
        3 df_2.head()
~\AppData\Local\Continuum\anaconda3\envs\learn-env\lib\site-packages\pandas\core\series.py
  in apply(self, func, convert_dtype, args, **kwds)    3192
  else:    3193                 values = self.astype(object).values
  -> 3194                 mapped = lib.map_infer(values, f, convert=convert_dtype)    3195     3196         if len(mapped) and
  isinstance(mapped[0], Series):
pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()
 in (x)
  ----> 1 df_2['Headline'] = df_2['Headline'].apply(lambda x: stemmer.stem(x))
        2
        3 df_2.head()
~\AppData\Local\Continuum\anaconda3\envs\learn-env\lib\site-packages\nltk\stem\snowball.py
  in stem(self, word)    1415     1416         """
  -> 1417         word = word.lower()    1418     1419         if word in self.stopwords or len(word) <= 2:
AttributeError: 'list' object has no attribute 'lower'

A: You need to specify the axis for the apply.
Here is a full working example:
import pandas as pd

df = pd.DataFrame({
    'col_1' : [['ducks'], ['dogs']],
    'col_2' : [['he', 'eats', 'apples'], ['she', 'has', 'cats', 'dogs']],
    'col_3' : ['some data 1', 'some data 2'],
    'col_4' : ['another data 1', 'another data 2']
})
df.head()

Output
    col_1   col_2                   col_3       col_4
0   [ducks] [he, eats, apples]      some data 1 another data 1
1   [dogs]  [she, has, cats, dogs]  some data 2 another data 2

Now let us apply stemming for the tokenized columns:
import nltk
from nltk.stem import SnowballStemmer
stemmer = nltk.stem.SnowballStemmer('english')

df.col_1 = df.apply(lambda row: [stemmer.stem(item) for item in row.col_1], axis=1)
df.col_2 = df.apply(lambda row: [stemmer.stem(item) for item in row.col_2], axis=1)

Check the new content of the dataframe.
df.head()

Output
    col_1   col_2                   col_3       col_4
0   [duck]  [he, eat, appl]         some data 1 another data 1
1   [dog]   [she, has, cat, dog]    some data 2 another data 2


text:
Q: Copying other answers I've noticed a trend where some users post an answer as early as possible that's not very good but gets some up-votes. Then when better answers are posted, they simply copy/paste the contents of those answers, perhaps re-wording them a little, into their own.
Sometimes they even thank the person they are ripping-off for help with improving their answer. If that person had wanted to improve their answer, they would have edited it instead of posting their own.
This practice should be discouraged.
Related: Fastest Gun in the West Problem

A: What you have described is plagiarism.  Copying the entirety of someone else's answer is plagiarism, whether cited or not.  Flag it as such, with a proper description of what happened, and what the post is plagiarizing.
Of course if someone is using the ideas of another answer (with citation) to augment and improve their own original answer, then that's neither plagiarism nor otherwise problematic.  Creating a derived work of another answer that meaningfully improves on it is of course encouraged.


text:
Q: How to avoid to Chrome console to print JSON objects in short forms in javascript? I try to print image as byte array bsae 64 by using JSON.stringify(...)
but it prints only short version of it.
Instead:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEoAAABKCAYAAAAc0MJxAAAABHNCSVQICAgIfAhkiAAABHNJREFU\neJztmk1rJEUAhp+q7p6ezEycbIZsTA5uxMSD4B7US0BE8KAXxVMuwurVk/4Kf4D+AEHworiK6E1B\nBAksrCALukjIurLJqvmYmWQyHz1dXR5i2MRsZqp7prsTtp7rdKcf3nRXVVe/YmV1XWMZisxb4KJg\ngzLEBmWIDcqQsQWlAaU10TmZGsbtM3JQGuiqCK1h0nVwBHRUlFtgafm4o5ysNDgC3pifYrlW5lLB\noRVG/Nxo8839Ju1+hCvFaIbnxCdxUJHWOELw/tIMy7XKid+WKj4vTJX44PZfNPsKR6QfVto+iR+9\nINK8Pl89JXXEUxWfawu1zB7BtH0SB1VyHV6dfWzgMS/WyswVPVQGYaXtkyioUGtmfZeq5ww8zhGC\nJ8oeSqebVBY+iYKSCHqRxuRyPaVJe4TKwidZUAK2en02O/2Bxx2EEXfaQeqDeRY+iceoUGuub9QH\nHvP1ZpNGoMhihZC2T+KgClLy4/YBH/+xQ/C/qUQD395v8sW9Om4GS4MsfESS/agjkarnsBOEPFn2\nWZ4uMzfhshsobuwecKvZZcZ32Q8Vodb4UqY2VmXhEyuoINK4QnB1aoKXZio8M1lkrdXj83t17hwE\nAGg0c8UCb85XeX66xNp+j592WtzYbdOLNP4Yn8MsfYyD6qiIpyeLXLsyzdXqxKnfd3oh9b6i4kpm\ni96p/9Zaq8end3e52WhTdEa/u7L2MQqqqzQvz0zy7mKNokz+Hh1p+OTuDl9tNke6s/LwGXqVINI8\nd6nEe0szI0nB4TT+zkKNVy5X6CZcruflM/BKWkPREby9MD3WKf6tKzVqBSf2CjlPn4FBhVqzWPZZ\nKBXGZwVMew7PTk0Qxryp8vQZGFQEzBa9sUodMet76Jh3VJ4+sR7ygzDi+kaDeqBiSbRVxJcbDbZ7\nYazzzpNPrKD+7AR8uLbF7VY3lthGp89Ha1v8uh/vvPPkI2HwS/fxMbMgBQUpYq+BBOBJgXfs9SHp\nYJyXjwsoztgSdgX8tt/lu7/38aTgVrPD4B2fARcS8MN2i16kUVpzs96OvX+dp49YWV3vAv5ZBygN\nYaQ5Ct8RsFjxee3xKpd9l1rBYargnliwBZGm2VfsBortIOT7f/b4pdFB68PbV//3d5K8oOblI1ZW\n1/eAyTiyodb0lGbCkUx6kpIj8aXAFQLF4W9tFdEKIw7CiIIUeCnutWTh4wJBXDFXCFxXoIG9vqLZ\nVxyfWYU4HAeEEJTd9D9GZ+HjAp2kggIe7BZm9/nuTNL0GTrrWQ6RQDVviYuABB7+xdByAomt/hhh\nQzLEBmWIDcoQG5QhNihDbFCG2KAMsa1gQ2wr2BDbCjbEtoINsa1gQ2wr2BDbCjbEtoKNr5HkJNsK\nNse2gg2xrWADbCvYQMi2godgW8G2FWxbweP0sa1gQx/bCjb0sa1gQx/bCjbEtoINGRqUbQUfMnAr\n2LaCHzB0wWlbwYZBPYxHtRUcm0e1FZyYR60VbDFAAq28JS4CEvTveUtcBCTIz/KWuAj8Cy9vAbfs\nZ+QcAAAAAElFTkSuQmCC\n

I get:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEoAAABKCAYAAAAc0MJxAAAABHNCS…e1FZyYR60VbDFAAq28JS4CEvTveUtcBCTIz/KWuAj8Cy9vAbfs\nZ+QcAAAAAElFTkSuQmCC\n
                                                                          ^^^

I tried:
JSON.stringify(visible_groups);
JSON.stringify(visible_groups, undefined, 2);

How to get rid of it?
[EDIT]
I know that its proper print and URL contains full text, but I try to copy to clipboard full version
Thanks,

A: That's just an artefact of how you're looking at it in the Chrome console, it's not in the real string. JSON.stringify doesn't arbitrarily elide your data.
Answering your updated question:

I know that its proper print and URL contains full text, but I try to copy to keyboard full version

console.log(visible_groups[0].mAvatarImgBase64Str); (or something like that, obviously I can't see much in that screenshot, no idea which index you want) should dump it to the console in a way you can copy it. If this is coming across the network, you can probably also get it from the Network tab.


text:
Q: How to get picker label and value and pass to a function I am trying to get my picker label and value in a function because they all carry different values and I will need both the label and value content to work with. Thank you for your help
  onValueChangeInvoiceType(value: string){
    this.setState({
      invoiceType: value,
    });
  }

  <Picker
    mode="dropdown"
    style={{flex: 1}}
    textStyle={{color: '#696969' }}
    selectedValue={this.state.invoiceType}
    onValueChange={this.onValueChangeInvoiceType.bind(this)}>
      <Picker.Item label="Select Option" value="" />
      <Picker.Item label="BOP" value="1" />
      <Picker.Item label="UNASSESSED BUS PROP" value="2" />
      <Picker.Item label="UNASSESSED RES PROP" value="3" />
      <Picker.Item label="FEES" value="4" />
      <Picker.Item label="FINES" value="5" />
      <Picker.Item label="BUILDING PLAN PERMIT" value="6" />
      <Picker.Item label="PERMIT CHARGES" value="7" />
      <Picker.Item label="RENT" value="8" />
      <Picker.Item label="PERMIT" value="9" />
      <Picker.Item label="BUSINESS PROPERTY RATE" value="12" />
      <Picker.Item label="RESIDENCE PROPERTY RATE" value="13" />
  </Picker>
</Item>

I want to know how I can pass the label content also to the onValueChangeInvoiceType function.

A: Here's a possible solution for you. I use a key to fetch the value/label combo from a lookup object. I use a key property for the lookup, since I want something I know will be unique. It can be anything you want. I'm not familiar with the particular control you're using, but this approach should work. Run the snippet below to see it function

const options = [
  {value:'-1', label:'Select...', key:'-1'},
  {value:'1', label:'BOP', key:'A'},
  {value:'2', label:'UNASSESSED BUS PROP', key:'B'},
  {value:'3', label:'UNASSESSED RES PROP', key:'C'},
  {value:'4', label:'FEES', key:'D'},
  {value:'5', label:'FINES', key:'E'},
];

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: '',
      label: ''
    };
  }

  onChange = (e) => {
    const opt = options.find(op => op.key === e.target.value);
    if(opt){
      this.setState({
        value: opt.value,
        label: opt.label
      })
    }
  }

  render() {
    return (

        <select onChange={this.onChange}>
          {options.map(({key,label}) => (
            <option key={key} label={label} value={key} />
          ))}
        </select>

Value: {this.state.value}

Label: {this.state.label}

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));


text:
Q: Coding arrays in constraint JuMP Please consider the following image:

I know when I use a:b in @constraint it means an array from a to b. I need to code the arrays like {a_j,b_j} in @constraint of the mentioned code. Can you please help me to code that?

A: I understand that you are asking about a custom indice iteration over a single constraint. This can be done in JuMP as:
using JuMP, Cbc
m = Model(Cbc.Optimizer)
@variable(m,x[1:3,1:3]>=0)
@constraint(m, con[ (i,j) in [(1,2),(2,3),(3,3)] ], x[i,j] >= 5)

Let us have a look what we got:
julia> println(m)
Feasibility
Subject to
 con[(1, 2)] : x[1,2] >= 5.0
 con[(2, 3)] : x[2,3] >= 5.0
 con[(3, 3)] : x[3,3] >= 5.0
 x[1,1] >= 0.0
 x[2,1] >= 0.0
 x[3,1] >= 0.0
 x[1,2] >= 0.0
 x[2,2] >= 0.0
 x[3,2] >= 0.0
 x[1,3] >= 0.0
 x[2,3] >= 0.0
 x[3,3] >= 0.0

A: A key point to understand is that--unlike AMPL and GAMS--there is no specialized
syntax for constructing and managing sets in JuMP. Instead, you can use any
available Julia syntax and datastructures.
Examples:
using JuMP
N = 10
model = Model();
@variable(model, x[1:N]);
@constraint(model, [s=1:3], sum(x[j] for j in 1:N if mod(j, s) == 0) == 1)

using JuMP
N = 10
model = Model();
@variable(model, x[1:N]);
d = [Set([1, 2, 3]), Set([2, 4, 6])]
a = [Set([3, 4]), Set([5])]
J(s) = [j for j in 1:2 if s in union(d[j], a[j])]
@constraint(model, [s=1:2], sum(x[j] for j in J(s)) == 1)


text:
Q: How to make the determinant formula visible even in cases when det=0 When I compute the determinant analytically in Mathematica, I do it with
Det[{{a, b}, {c, d}}]

which gives the output
-b c + a d

I would like to see this formula even if the determinant is zero as
Det[{{a, b}, {-a, -b}}]

which yields the output
0

instead of something like
-b (-a) + a (-b)

This is just a small example, but my matrices are a little larger, and I need to figure out analytically why some determinants are zero and some are not.
Any ideas?

A: One possibility is to temporarily inactivate the arithmetic operators, like so:
Block[{Times = Inactive[Times], Plus = Inactive[Plus]},
      Det[{{a, b}, {-a, -b}}]]
   a*(-1*b)+-1*b*(-1*a)

A: You could try:
m = {{a, b}, {-a, -b}};

Det[Map[ToBoxes, m, {2}]] // DisplayForm
(* -b (-a)+a (-b) *)


text:
Q: Why does Git's stash commit need two parents? Why does Git's stash commit need two parents?
In the Hacker's Guide to Git, I see this mental model for stashes:

The guide tells me that stash@{0} needs both A and B as parents.  Why? Why doesn't the stash just point to B, getting rid of the need for C?  I think I am missing something in my Git comprehension.

A: Because two things are stashed: the indexed content and the worktree content.  Both are derived from the checked-out commit.  When popping the stash, both can be restored.

A: It doesn't always require two parents, sometimes it actually requires three.
The following diagram illustrate the simplest scenario, with two parents:
       .----S
      /    /
-----H----I

Here H represents your current head, which is the master branch in your example, and two child commits are created when you run git-stash.
The first is I, which represents the index at the time of stashing. In other words, this commit contains the changes that were staged before stashing. It has a single parent, which is the commit which HEAD pointed to. The second (S) is the stash commit, which contains files that were modified before stashing. It has two commits because its changes might be on top of those in I and those in H, that is, they might affect files that were staged or not.
The other scenario happens when you provide the -u switch to the stash command, which tells Git to also stash untracked files. The diagram now becomes:
       .----S----.
      /    /    /
-----H----I    U

The new U commit has all the changes introduced by the untracked files. Notice that it wouldn't make sense for this commit to have any parents since those files don't exist in the current HEAD. The stash commit S now has three parents: H, I and U and now when applying the stash commit Git will also apply the untracked changes.
You can see those diagrams and the diffs clearly by running something like git log --graph stash@{0} or gitk stash@{0}.


text:
Q: PtrToStringUni doesnt work in windows 10 So i have been using urlmon.dll's help with getting the MIME type of files' data as suggested in This answer, and its been working fine in windows 7.
However, on windows 10 the same code generates System.AccessViolationException when trying to create a string from the mime pointer.
this is the problematic code:
uint mimeType;
FindMimeFromData(0, null, data, 256, null, 0, out mimeType, 0);
var mimePointer = new IntPtr(mimeType);
//Exception is thrown on the next line
var mime = Marshal.PtrToStringUni(mimePointer);

The code works fine on windows 7 and on the same files, however when running this on windows 10 i suddenly get Access Violation.
Did anyone else encounter this error ?

A: uint mimeType;
FindMimeFromData(0, null, data, 256, null, 0, out mimeType, 0);
var mimePointer = new IntPtr(mimeType);

This is surely wrong at 64 bits... A IntPtr is 64 bits (it is a memory address)... How could a uint (a 32 bits) contain it?
And if we take a look at the pinvoke site the signature should be:
[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
static extern int FindMimeFromData(IntPtr pBC,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
    [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)]
    byte[] pBuffer,
    int cbSize,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
    int dwMimeFlags,
    out IntPtr ppwzMimeOut,
    int dwReserved);

very important while the documentation of the method is very poor on msdn, calling FindMimeFromData will cause a memory leak: you have to free the ppwzMimeOut you receive... The problem is that it isn't clear how: here it is suggested to use CoTaskMemFree, that is Marshal.FreeCoTaskMem. I'll say that it is right, tested with:
byte[] bytes = File.ReadAllBytes("someimage.jpg");

while (true)
{
    IntPtr ptr1;
    int success1 = FindMimeFromData(IntPtr.Zero, null, bytes, bytes.Length, null, 0, out ptr1, 0);
    Marshal.FreeCoTaskMem(ptr1);
}

If I remove the Marshal.FreeCoTaskMem and take a look with the TaskManager, the memory used by the process will go up quite quickly... If I restore the Marshal.FreeCoTaskMem, the memory will remain stable.


text:
Q: domap resulting on error 'google' is not defined I'm make use of GMLib some time ago to create same forms with Delphi 7 that did must interact with google maps.
At time this work great, (begin of year) until now the project stay paused, now I came back to work with him and the code that I was written back in time is not running any more.
For some reason when I run: GMap.DoMap;
I did get back a error of javascript with message:

'google' is not defined

. This occur in different lines of javascript at different times of execution and at end the program breaks on an exception.
First of all I updated my component to last version (1.2.4) once this is originally written using the 1.1.0, but this not solved my case.
Then I've tryed to find at google anyone with the same problem, but I can't find one solution. So please, if someone could help me on this, thanks.

So, sorry for posting this too soon, now that I did test the code on other machine, this run perfectly.
Well, obviously this is not a component problem, but yes a incompatibility, my pc is running Windows 8, and I have a lot of things installed on him, but I will try figure out what is causing this.


text:
Q: How to apply patches for updating VB.NET application over the internet? Hello dearest community,
First of all, I hope my intention is not missconcept.
I would like to add an update from the internet mechanism for my newly VB.NET application.
The idea is simple. That is, I ZIP all of the binary that need to be changed, upload it in my own hosting site, and download it using my Update Application, extract and overwrite the existing binary.
It works, quite well. But the problem is, the size of the binary itself is quite big (around 36MB). I am thinking of patches. That is, can we upload only the patch file, it surely make the download small isn't?
But I am not getting any good result on implementing it in Windows environment.
Any idea?
Thanks

A: why reinvent the reinvent the wheel, Microsoft already provide a very good way of doing this called Click Once Deployment.
http://msdn.microsoft.com/en-us/library/t71a733d(v=vs.80).aspx

A: How many files are in the zip? Is it one large executable, or is the zip only supposed to hold the files that have changed? If it only holds the files that changed, then expanding the zip should, theoretically, only overwrite the files contained in the .zip.
Also, is there a reason you're not using git, or some other DVCS to deploy just changes to your app? In addition to tracking code changes, they will intelligently apply just changes when using them as the source of deployments.


text:
Q: responsive issue with bootstrap on mobile and tablet Site: http://www.partyfacepainting.co.uk/test
Bootstraps responsive features don't seem to be working on iPhone or iPad for this site for some reason. They work fine on the desktop when I reduce the size of the browser window. I've searched the topic and the only answer seems to be in relation to not adding:
> <meta name="viewport" content="width=device-width,
> initial-scale=1.0"/>

but I have this in and it's still not responsive. I have created a few sites with bootstrap now and never had this problem in the past. I have even tried uploading an unedited version of the bootstrap files with one of their starter templates as the index file (you can see that here: http://www.partyfacepainting.co.uk) and even that's not working. I just can't figure this out! Any help would be much appreciated.

A: Your page is structured like this:
<html>
  <head>
    <title>Party Face Painting</title>
      <meta name="keywords" content="">
      <meta name="description" content="">
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <!-- you need a viewport meta tag up here -->
  </head>
  <frameset rows="100%">
    <frame ...>
      #document
      <!DOCTYPE html>
        <html lang="en">
          <head>
            ...
            <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
            <!-- you have a viewport meta tag within the frameset here -->
            ...
          </head>
          ...
    </frame>
    ...
  </frameset>
</html>

You do not have a viewport meta tag on the outermost page, only within the frame


text:
Q: How to add items to class property array in php? I have a class property which is an array. I have some $data array which I would like to add to that array without using a foreach loop.
Check out this sample code:
<?php
    class A {
    public $y = array();
    public function foo() {
        $data = array('apples', 'pears', 'oranges');
        array_merge($this->y, $data);
    }
}

$a = new A();
$a->foo();
print_r($a->y);
assert(sizeof($a->y)==3);

Expected result:
Array (
    [0] => apples
    [1] => pears
    [2] => oranges
)

Actual result:
Array ( )
PHP Warning:  assert(): Assertion failed on line 16

A: Change the function definition as follows:
public function foo() {
        $data = array('apples', 'pears', 'oranges');
        $this->y = array_merge($this->y, $data);
}

The documentation clearly states that the merged array is returned back. So, the original array passed in the parameter remains untouched.


text:
Q: Why Is The Size of ptr3 2? //The output for this code is observed to be 4 4 2 ? I dont get why is it 2 for ptr3?please help
#include<stdio.h>

int main()
{
char huge *near *far *ptr1;
char near *far *huge *ptr2;
char far *huge *near *ptr3;
printf("%d, %d, %d\n", sizeof(ptr1), sizeof(ptr2), sizeof(ptr3));
return 0;
}

A: near, far, and huge pointers are non-standard.
In implementations that support them (usually for very old x86 systems), a specific location in memory can be specified by a segment and an offset. A near pointer contains only an offset, leaving the segment implicit. Thus it requires less space than a far pointer.
Modern compilers do not use any of these keywords. I suggest you find yourself a newer compiler; there are plenty of free ones available.
See this question for more information.
Incidentally, printf's "%d" format requires an argument of type int; sizeof yields a result of type size_t, which is a different type. You can change your printf call to:
printf("%d, %d, %d\n", (int)sizeof ptr1, (int)sizeof ptr2, (int)sizeof ptr3);

(The modern way to do that is:
printf("%zu, %zu, %zu\n", sizeof ptr1, sizeof ptr2, sizeof ptr3);

but an implementation that supports near and far pointers isn't likely to be modern enough to support "%zu", which was introduced in C99.)

A: this far near and huge are the concepts used in old DOS-compilers.
For more you can see this link.
Which will explain everything about how are these implemented internally.
Due to this implementation you are getting the size like this.

A: Just to remove a layer of confusion, so you can use the other answer.
Declaration of a near pointer looks like this:
type near* variable;

Or like this:
near type* variable;

Where type is any type. In your example, someone is trying to confuse you because type is itself a pointer type: char far *huge *. However, no matter what it points to, a near pointer occupies 2 bytes.
(I guess someone is trying to confuse you on purpose because there is no chance such constructs appear in real code)

A: I think you are using an old compailer (may be turboc c).Latest compiler not support this functionality.
near pointers don't have a selector - they have an implied selector. They can access 64k off the virtual address space on a 286 and earlier and 4Gb of the addresss space on a 386 or later.
far pointers have an explicit selector. However when you do pointer arithmetic on them the selector isn't modified.
huge pointers have an explicit selector. When you do pointer arithmetic on them though the selector can change.


text:
Q: Getting crash on android 23.0.1 I tested this code on an emulator which has android marshmallow, there is no crash on emulator . I can't see logcat error because i am sending debug apk to my friend and he is telling me there is a crash . Can you guys guess whats the problem. its simple two lines code. crash happens on button click and code inside it is here....
       if(Build.VERSION.SDK_INT >= 23){
            if(checkSelfPermission(
                    Manifest.permission.READ_SMS)
                    == PackageManager.PERMISSION_GRANTED && checkSelfPermission(
                    Manifest.permission.SEND_SMS)
                    == PackageManager.PERMISSION_GRANTED){

                prepareSend();

            }else  {
                if (!shouldShowRequestPermissionRationale(
                        Manifest.permission.SEND_SMS)) {

                    requestPermissions(
                            new String[]{Manifest.permission.READ_SMS, Manifest.permission.SEND_SMS},
                        1);
                }}
            }else{

                prepareSend();
            }

Other code is fine here is prepare send there are no crashes on devices lower than 23.
          public void prepareSend() {
        String phones = extractPhones();
        if (TextUtils.isEmpty(phones) || TextUtils.isEmpty(messageText.getText().toString()) || TextUtils.isEmpty(bomb.getText().toString()) || TextUtils.isEmpty(delay.getText().toString()))
            Toast.makeText(this,"One or more required field is empty.",Toast.LENGTH_LONG).show();
        else {
            //Toast.makeText(this,phones,Toast.LENGTH_LONG).show();
            intent = new Intent(getBaseContext(),FreshService.class);
            intent.putExtra("message",messageText.getText().toString().trim());
            intent.putExtra("bombs",Integer.parseInt(bomb.getText().toString()));
            int delayLong = Integer.parseInt(delay.getText().toString());
            intent.putExtra("interval",delayLong);
            intent.putExtra("phones", phones);

            startService(intent);
            //Toast.makeText(getBaseContext(),"Service started successfully interval:" + delayLong,Toast.LENGTH_SHORT).show();
            btnSend.setEnabled(false);
            btnStop.setEnabled(true);
            doBindService();
        }

}


text:
Q: Custom Max-Pooling layer for image classification I want to make a custom pooling layer in a CNN model using keras tensorflow.
For visual description (click here)
In the above picture it shows a maxpooling operation on a 4x4 feature map with 2x2 filter and the output is a 2x2 feature map. I want two 2x2 featuremap instead. One is the same as this one and other picks the 2nd largest activation.
I have searched so much, this is what I have found similar to what I am trying. But it is just picking the k maximum for the whole tensor. Anyone, please help me.
class KMaxPooling(Layer):
"""
K-max pooling layer that extracts the k-highest activations from a sequence (2nd dimension).
TensorFlow backend.
"""
def __init__(self, k=1, **kwargs):
    super().__init__(**kwargs)
    self.input_spec = InputSpec(ndim=3)
    self.k = k

def compute_output_shape(self, input_shape):
    return (input_shape[0], (input_shape[2] * self.k))

def call(self, inputs):

    # swap last two dimensions since top_k will be applied along the last dimension
    shifted_input = tf.transpose(inputs, [0, 2, 1])

    # extract top_k, returns two tensors [values, indices]
    top_k = tf.nn.top_k(shifted_input, k=self.k, sorted=True, name=None)[0]

    # return flattened output
    return Flatten()(top_k)


text:
Q: The NumberFormat property is not taking effect in a Function that needs to return a formatted date Excel VBA issue:
Another person had a problem with the NOW() function because they wanted it to return a static date & time w/o needing to Copy & Paste the value back.  I suggested a user-defined function which correctly returns the current date & time in a static manner.  The problem is that the NumberFormat property is being ignored & the result that pops out is a number.
I've tried several other formatting solutions, but these are also ignored or result in errors.
Public Function DateNow() As Date

    ActiveCell.NumberFormat = "[$-en-US]m/d/yy h:mm AM/PM;@"
    DateNow = Now

End Function

Expected result would be a static current date & time.  To re-iterate; the code is correct except the part that says ActiveCell.NumberFormat... which is not taking effect.
Edit: I've read the comments below and tried to update it to include a call to a sub, but still no luck.  Could someone direct me to the workaround?  Thanks.
Public Function DateNow() As Date
    DateNow = Now
    Call DateSub(ActiveCell)
End Function
Public Sub DateSub(rg As Range)

    rg.NumberFormat = "[$-en-US]m/d/yy h:mm AM/PM;@"

End Sub

A:  Sub test()
      ActiveCell = DateNow
      ActiveCell.NumberFormat = "[$-en-US]m/d/yy h:mm AM/PM;@"
 End Sub

 Public Function DateNow() As Date

     DateNow = Now

 End Function

A: Please try the following since formatting it important so lets format value the within the function it self. Hope! it serves the purpose. In case it helps please mark it accepted answer.
Public Function DateNow() As String

    DateNow = Format(Now, "[$-en-US]m/d/yy h:mm AM/PM;@")

End Function


text:
Q: Keep file open while writing big data? We need to export data to a csv file.
The approach is:

*

*fopen the csv file once

*fputcsv after x lines dump the data to file (x = 100, 500 or 1000)

*fclose close it after writing all data

30.000 lines take about 1 minute to parse and write to file.
Writing after 100 lines is the fastest so far.
How can I speed my export up? It is not about our data parsing algorithms, but rather file management and writing.
Here are some relevant code blocks:
  // -- path and file creation functions
  $strPhpTmpDir = sys_get_temp_dir();
  $strTmpDir = $strPhpTmpDir . DIRECTORY_SEPARATOR . uniqid();
  $bOk = mkdir($strTmpDir, 0777);
  $this->m_strTmpPath = $strTmpDir;

  $strFile = 'csv-' . time() . '-' . rand() . '.csv';
  $this->m_strTmpFile = $this->m_strTmpPath . DIRECTORY_SEPARATOR . $strFile;

  touch($this->m_strTmpFile);

  // -- open function
  if (is_file($this->m_strTmpFile) && is_writable($this->m_strTmpFile)) {
     $this->m_oFile = fopen($this->m_strTmpFile, 'w');
  }

  // -- dump function
  foreach($arData as $arLine) {
     fputcsv($this->m_oFile, $arLine, ';', '"');
  }

A: If you've tinkered with the write interval and found that 100 is the fastest, you've probably done as much as you can.
If this is in a script called from a shell rather than a webpage, there are alternatives.

*

*Alternative 1 - write the export script in a compiled language rather than an interpreted one. C?

*Alternative 2 - output the CSV lines to stdout and pipe that output into a file within the OS using redirection

*Alternative 3 - If possible, check out the caching options within your OS
Not having tried any of the above (and option 1 was struck out after seeing your code snippet), it could be that you will get a speed up as you're closer to the OS when creating the file rather than having PHP loop and perform the writing


text:
Q: Embed URL to coordinates, kml or geojson I've got a complex directions URL and embed URL that I would like to get polylines for. Once I can get them into polylines or something similar I can convert to final format: GeoJSON.
Direction Link
-or-
Embed Link
I have looked at the API's and I can't find anything that accepts or would decode the PB (what is this? it's not a protocol buffer). So far this is as far as I've got:
//php
$pb_array = explode('!', $pb);
foreach($pb_array as $key => $value){
    echo "$key - $value
";
}

===

1 - 1m73
2 - 1m12
3 - 1m3
4 - 1d1472548.9575794793
5 - 2d-72.8191002664707
6 - 3d43.87505426780168
7 - 2m3
8 - 1f0
9 - 2f0
10 - 3f0
11 - 3m2
12 - 1i1024
13 - 2i768
14 - 4f13.1
15 - 4m58
16 - 3e0
17 - 4m5
18 - 1s0x0%3A0xa58b3d6041ba69f8
19 - 2sGuilford+Welcome+Center
20 - 3m2
21 - 1d42.8120069
22 - 2d-72.56614689999999
23 - 4m3
24 - 3m2
25 - 1d43.3893165
26 - 2d-72.40772249999999
27 - 4m5
28 - 1s0x4cb52e78df455c83%3A0xb6946ec850907db8
29 - 2s130+Lower+Michigan+Road%2C+Pittsfield%2C+VT+05762
30 - 3m2
31 - 1d43.76898
32 - 2d-72.815214
33 - 4m4
34 - 1s0x0%3A0xea2de48bba82cc86
35 - 3m2
36 - 1d44.042544
37 - 2d-72.6046997
38 - 4m5
39 - 1s0x0%3A0x6bb602ed58bf4413
40 - 2sJay+Peak+Resort
41 - 3m2
42 - 1d44.9379515
43 - 2d-72.5045433
44 - 4m5
45 - 1s0x4cb392aaa4333a07%3A0x160aef1559868340
46 - 2sDolly+Copp+Campground+Rd%2C+Gorham%2C+NH+03581
47 - 3m2
48 - 1d44.335842199999995
49 - 2d-71.21837339999999
50 - 4m5
51 - 1s0x4cb392684201a94d%3A0xfa4a6f490a05429d
52 - 2sMt+Washington+Auto+Road%2C+1+Mount+Washington+Auto+Road%2C+Gorham%2C+NH+03581
53 - 3m2
54 - 1d44.288384099999995
55 - 2d-71.22459599999999
56 - 4m5
57 - 1s0x4cb38e798f42c3d9%3A0xc3b88e4dac01db12
58 - 2sMt+Washington
59 - 3m2
60 - 1d44.270585399999995
61 - 2d-71.3032723
62 - 4m5
63 - 1s0x89e2a7fa444124d5%3A0xe3ed24b6f864eba0
64 - 2sWells%2C+ME
65 - 3m2
66 - 1d43.322232899999996
67 - 2d-70.5805209
68 - 4m5
69 - 1s0x89e2ba813e828c71%3A0x8cdf74380f6a933d
70 - 2sLibby's+Oceanside+Camp%2C+York+Street%2C+York%2C+ME
71 - 3m2
72 - 1d43.147162
73 - 2d-70.626173
74 - 5e1
75 - 3m2
76 - 1sen
77 - 2sus
78 - 4v1472497940601

The closest hints I could find are from this thread. I will keep looking but I'm stuck.
I'm trying to create an API based solution that has an input of one of these URL's and returns a GeoJSON.

A:
would decode the PB (what is this? it's not a protocol buffer)

For the record, because this overflow question keeps popping up on google results: it is a protocol buffer. PB litteraly stands for protocol buffer.
It's just a different ASCII encoding (a compact URL encoding reminiscent of the binary encoding, not the usual JSON-like text encoding. When you squint at it it's not that much different than torrent's structure encoding), and Google doesn't provide us the .proto file.
For each field:

*

*first character is the id (identifies the field according to the corresponding .proto file)

*second character is the type of the field

*

*m is for message

*s is for string

*i, j, u, v are for various type of ints

*f, d are for floating points

*e is for enum

*the rest is the payload

So to unpack the fields you're seeing (even if we don't have the .proto file):

*

*1m73 message of type 1, containing 73 elements (the whole message set)

*

*1m12 submessage of type 1, contains 12 elements (probably information about the view box in the map box)

*

*1m3 sub-sub-message type 1, contains 3 elements (probably map coordinates)

*

*1d1472548.9575794793 first double field (probably zoom level)

*2d-72.8191002664707 second double field (probably longitude)

*3d43.87505426780168 third double field (probably latitude)

*2m3 second sub-sub-sub message (no idea given that it's not filled. Maybe a starting point if you code a route instead of a single point ?)

*

*1f0, 2f0, 3f0  the three members, currently just zero

*3m2 third block (looks like a screen resolution)

*

*1i1024, 2i768 : 1024x768 ? (and probably the omited field 3 would have been the color depth if present ??)

*4f13.1 no idea, but it's a float

*4m58 next message with 58 elements (to me it looks like a bunch of POI that we need to display in the box)

*

*3e0 an enum, set to zero (this one would be completely impossible to interpret without a proto or without experimenting, as you need the list of enums)

*4m5 five more elements probably a map poi
- 1s0x0%3A0xa58b3d6041ba69f8 string '0x0:0xa58b3d6041ba69f8', note the use of Url_encoded character. In turn it looks like a pair of hex numbers, maybe a GUID ?
- 2sGuilford+Welcome+Center string, the name with plus instead of blank (like most URLs)
- 3m2 two elements to come
- 1d42.8120069 and 2d-72.56614689999999 doubles probably map coordinates

*4m3 again a message of type 4 in this level, so probably another poi
- 3m2, 1d43.3893165, 2d-72.40772249999999 but this one only specifies coordinates, and nothing else

*4m5 another poi
- 1s0x4cb52e78df455c83%3A0xb6946ec850907db8 different pair of hex, GUID
...you got the idea...

*5e1 another bunch of information probably general settings

*

*3m2 this setting is a message (and looks like a locale)

*

*1sen, 2sus locale is en_US

*4v1472497940601 some other large number...

Note: the original proto that Google doesn't show us, is probably a single multi level structure. Thus, the sub-sub-message ID don't have always the same meaning: they aren't global ID, but ID within the parent message.

*

*inside a sub message ID 1 (view box ?), the sub-sub message 3 seems to be resolution.

*inside a sub message ID 4 (POIs ?), the sub-ID 3 isn't even a message but some enum

*inside a sub message ID 5 (parameters), the sub-sub message 3 is a locale

A: Well, here's my sloppy but working solution. My needs required GeoJSON, but others can use the google maps service to get the desired output once you have the lat/lng array.
$embed = '<iframe src="https://www.google.com/maps/embed?pb=!1m73!1m12!1m3!1d1472548.9575794793!2d-72.8191002664707!3d43.87505426780168!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m58!3e0!4m5!1s0x0%3A0xa58b3d6041ba69f8!2sGuilford+Welcome+Center!3m2!1d42.8120069!2d-72.56614689999999!4m3!3m2!1d43.3893165!2d-72.40772249999999!4m5!1s0x4cb52e78df455c83%3A0xb6946ec850907db8!2s130+Lower+Michigan+Road%2C+Pittsfield%2C+VT+05762!3m2!1d43.76898!2d-72.815214!4m4!1s0x0%3A0xea2de48bba82cc86!3m2!1d44.042544!2d-72.6046997!4m5!1s0x0%3A0x6bb602ed58bf4413!2sJay+Peak+Resort!3m2!1d44.9379515!2d-72.5045433!4m5!1s0x4cb392aaa4333a07%3A0x160aef1559868340!2sDolly+Copp+Campground+Rd%2C+Gorham%2C+NH+03581!3m2!1d44.335842199999995!2d-71.21837339999999!4m5!1s0x4cb392684201a94d%3A0xfa4a6f490a05429d!2sMt+Washington+Auto+Road%2C+1+Mount+Washington+Auto+Road%2C+Gorham%2C+NH+03581!3m2!1d44.288384099999995!2d-71.22459599999999!4m5!1s0x4cb38e798f42c3d9%3A0xc3b88e4dac01db12!2sMt+Washington!3m2!1d44.270585399999995!2d-71.3032723!4m5!1s0x89e2a7fa444124d5%3A0xe3ed24b6f864eba0!2sWells%2C+ME!3m2!1d43.322232899999996!2d-70.5805209!4m5!1s0x89e2ba813e828c71%3A0x8cdf74380f6a933d!2sLibby's+Oceanside+Camp%2C+York+Street%2C+York%2C+ME!3m2!1d43.147162!2d-70.626173!5e1!3m2!1sen!2sus!4v1472497940601" width="600" height="450" frameborder="0" style="border:0" allowfullscreen>';

$array = array();
preg_match( '/src="([^"]*)"/i', $embed, $array ) ;
list($pre, $pb) = split("pb=", $array[1]);

if($pb == "" || strpos($pb, "!") === false)
    die(json_encode(array("success"=>false)));

//echo "PB Extracted:
";
//echo $pb;
///echo "

Decode:
";
$pb_array = explode('!', $pb);

$coords = array();
$address;$addressHex;
$results = array();
foreach($pb_array as $key => $value){
    //uncomment to debug output
    //echo "$key - $value
";

    if($value == "3m2" || $value == "2m2"){
        //3m2 seems to be the divider of these 'places'
        if(count($coords) != 3) //don't add the center of map data (3 coordinates [height, lng, lat])
            array_push($results, array("coords"=>$coords,"address"=>$address,"addressHex"=>$addressHex));
        $coords = array(); //reset array
    }else{
        $type = substr($value, 1, 1);
        $stype = substr($value, 0, 2);
        $value = substr($value, 2);
        //echo "$type - $value
";
        if($type == "d"){
            //Found Lat,Lng
            array_push($coords, $value);
        }else if($stype == "2s"){
            //Address
            $address = $value;
        }else if($stype == "1s"){
            //Address Encoded in some way
            $addressHex = $value;
        }
    }
}

//echo "

Google Result
";
//echo json_encode($results);

//echo "

Mapbox API:
";
$waypoints = array();
for($i=0;$i<count($results);$i++){
    if(count($results[$i]["coords"])){
        $lat = $results[$i]["coords"][0];
        $lng = $results[$i]["coords"][1];
        array_push($waypoints, "$lng%2C$lat");
    }
}
$waypoints = implode("%3B", $waypoints); //convert to string

$mapbox_api_key = "pk.eyJ1I.....";
$url = "https://api.mapbox.com/directions/v5/mapbox/driving/$waypoints.json?steps=false&alternatives=false&overview=full&geometries=geojson&access_token=$mapbox_api_key";

//echo "

Mapbox Response:
";
$response = file_get_contents($url);

$json = json_decode($response,true);
//echo "

Mapbox Geometry:
";
$coordinates = $json["routes"][0]["geometry"]["coordinates"];

$geojson = (array("type"=>"FeatureCollection","features"=>array(array("type"=>"Feature","geometry"=>array("type"=>"LineString","coordinates"=>$coordinates),"properties"=>array()))));

echo json_encode(array("success"=>true, "geojson"=>$geojson));


text:
Q: How can i add right join to other table in this code I have this code runninh:
SELECT IDLOTE,
       SUM(CASE WHEN FECHAMOVTO='2020-01-01'
                THEN cargo
                ELSE 0
                END) *4 as saldo,
       SUM(CASE WHEN FECHAMOVTO>'2019-12-31' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23 or idconcepto=24)
                THEN cargo
                ELSE 0
                END) as saldo2,
       SUM(CASE WHEN FECHAMOVTO<='2019-12-31'
                THEN cargo-abono
                ELSE 0
                END) as saldo3,
        SUM(CASE WHEN FECHAMOVTO<'2020-01-01'
                THEN cargo-abono
                ELSE 0
                END) as saldo4,
        SUM(CASE WHEN FECHAMOVTO>='2020-01-01' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23)
                THEN cargo
                ELSE 0
                END) as saldo5
FROM polizamovtos
GROUP BY IDLOTE
HAVING SUM(cargo) > SUM(abono)

So, i need to add right join on idlote with the table propietarios
I try with this code:
SELECT IDLOTE,
   SUM(CASE WHEN FECHAMOVTO='2020-01-01'
            THEN cargo
            ELSE 0
            END) *4 as saldo,
   SUM(CASE WHEN FECHAMOVTO>'2019-12-31' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23 or idconcepto=24)
            THEN cargo
            ELSE 0
            END) as saldo2,
   SUM(CASE WHEN FECHAMOVTO<='2019-12-31'
            THEN cargo-abono
            ELSE 0
            END) as saldo3,
    SUM(CASE WHEN FECHAMOVTO<'2020-01-01'
            THEN cargo-abono
            ELSE 0
            END) as saldo4,
    SUM(CASE WHEN FECHAMOVTO>='2020-01-01' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23)
            THEN cargo
            ELSE 0
            END) as saldo5
FROM polizamovtos t1
INNER JOIN asignarlotes on asignarlotes.IDLOTE=polizamovtos.idlote
GROUP BY IDLOTE
HAVING SUM(cargo) > SUM(abono)

A: With the second table, mysql doesn't know which column to choose, when they have the same name like IDIOTE, so choose one.
I changed the alias for polizamovtos  to p and give a to asignarlotes, that makes it easier to read and you know always which table you want to use
SELECT p.IDLOTE,
   SUM(CASE WHEN FECHAMOVTO='2020-01-01'
            THEN cargo
            ELSE 0
            END) *4 as saldo,
   SUM(CASE WHEN FECHAMOVTO>'2019-12-31' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23 or idconcepto=24)
            THEN cargo
            ELSE 0
            END) as saldo2,
   SUM(CASE WHEN FECHAMOVTO<='2019-12-31'
            THEN cargo-abono
            ELSE 0
            END) as saldo3,
    SUM(CASE WHEN FECHAMOVTO<'2020-01-01'
            THEN cargo-abono
            ELSE 0
            END) as saldo4,
    SUM(CASE WHEN FECHAMOVTO>='2020-01-01' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23)
            THEN cargo
            ELSE 0
            END) as saldo5
FROM polizamovtos p
INNER JOIN asignarlotes a on a.IDLOTE=p.idlote
GROUP BY p.IDLOTE
HAVING SUM(cargo) > SUM(abono)


text:
Q: C++ Event Handler I am pretty new to C++ and I recently encountered the following problem: hwo do I handle events in C++? I have worked with XNA and this stuff there is easy (or at least it is easy to do what I need): you can just write myObject.MyObjectEvent+=MyObjectEventHandler(functionToStartOnEvent)
does this have an equivalent in C++?


text:
Q: Overflow-X: hidden doesn't work with animation I'm working on a website with animated elements using CSS3. One problem I have is the vertical scrolling bar. So there's an element that is constantly sliding from left to right and back:
@keyframes waves {
  0% {left:-50px;}
  50% {left: 0px;}
  100% {left: -50px;}
}

So that this works, the object is bigger than the screen size. Now of course the vertical scrolling bar appears. How can I hide that?
I put the element in a container, where I defined overflow-x: hidden but somehow it didn't work. Maybe I just did a mistake? What method should I use?
Here's the fiddle:
https://jsfiddle.net/hsdoy3t4/
Thank you very much for your help.

A: Because it's taking default margin of body tag.
Set margin:0 for body tag.

body{
  margin:0;
}
#home {
 width: 100vw;
 overflow-x: hidden;
}

#object {
 background-image: url('http://www.1000skies.com/800trim.jpg');
 width: calc(100% + 50px);
 height: 158px;
  position: relative;
 -webkit-animation: waves 2s infinite;
    -moz-animation: waves 2s infinite;
    animation: waves 2s infinite;
}

@-webkit-keyframes waves {
  0% {left:-50px;}
  50% {left: 0px;}
  100% {left: -50px;}
}

@-moz-keyframes waves {
  0% {left:-50px;}
  50% {left: 0px;}
  100% {left: -50px;}
}

@keyframes waves {
  0% {left:-50px;}
  50% {left: 0px;}
  100% {left: -50px;}
}


text:
Q: install opencv python mac osx 10.11? I'm trying to install opencv so I can use it in a python program. My computer is a little old and I can't update osx past 10.11. Is it still possible to install opencv? I don't need it to be opencv4 if that's an issue.
I've tried using pip, pip3, and homebrew. They all download it and then it won't actually import in python correctly. Everything eventually says that it needs to be osx 10.12.
Here's the exact error I'm getting:
File "<stdin>", line 1, in <module>
  File "/anaconda3/lib/python3.7/site-packages/cv2/__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: dlopen(/anaconda3/lib/python3.7/site-packages/cv2/cv2.cpython-37m-darwin.so, 2): Symbol not found: _clock_gettime
  Referenced from: /anaconda3/lib/python3.7/site-packages/cv2/.dylibs/libavutil.56.22.100.dylib (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib
 in /anaconda3/lib/python3.7/site-packages/cv2/.dylibs/libavutil.56.22.100.dylib

Thanks!

A: Try conda install :
conda install --channel https://conda.anaconda.org/menpo opencv3

OR
conda install -c menpo opencv

Then import
import cv2

There seems to be a problem with the brew installation according to https://github.com/Homebrew/homebrew-science/issues/3024 but you can try the below too
---------- OR ----------
First, create a venv (Virtual Enviorment)
python3 -m venv /path/to/new/virtual/environment

Then using brew :
brew uninstall opencv
brew install opencv3

OR
Then using pip :
pip3 install opencv-python

Finally, import using :
import cv2

This should work but in the case doesn't it might mean that you've installed anaconda with python in that case try:
conda install -c menpo opencv

Finally, import using :
import cv2


text:
Q: Why is logging back in necessary after adding user to docker group? In the Docker documentation, discussing how to give a non-root user permission to use Docker, it instructs, after adding the user to the docker group,

Log out and log back in so that your group membership is re-evaluated.
If testing on a virtual machine, it may be necessary to restart the virtual machine for changes to take effect.
On a desktop Linux environment such as X Windows, log out of your session completely and then log back in.

Why is it necessary to log out and back in?  Why wouldn't having the necessary permissions (i.e., by being a member of the docker group) be sufficient?


text:
Q: Multi-thread object→object cache map in Java? I want a collection in Java which:

*

*maps arbitrary Objects to Objects (not String or otherwise restricted keys only)

*will be used as a cache; if the key is not in the cache, a value will be computed (this doesn't have to be built into the collection)

*will be accessed from multiple threads simultaneously

*will never have items removed from it

*must be very efficient to read (cache hit); not necessarily efficient to write (cache miss)

It's OK if cache misses simultaneously in multiple threads cause redundant computations; the typical case is that the cache is mostly filled by one thread at first.
A synchronized block around a thread-unsafe hashtable fails the efficient-to-read criterion. Thread-local caches would be straightforward but mean that new threads are expensive since they have full copies of the cache.
Java 1.5 built-ins, or one-or-few class files we can copy into our MIT-licensed project, are preferred, rather than large external libraries.

A: Use the java concurrent hashmap
ConcurrentHashMap<object, object> table;

public object getFromCache(object key)
{
    value = table.get(key);

    if (value == null)
    {
        //key isn't a key into this table, ie. it's not in the cache
        value = calculateValueForKey(key)
        object fromCache = table.putIfAbsent(key, value);
    }

    return value;
}

/**
* This calculates a new value to put into the cache
*/
public abstract object calculateValueForKey(object key);

N.b. This is not longer a general solution for multithreaded caching, since it relies on the stated fact that objects are immutable, and thus object equivalence is not important.

A: This is my own idea for a solution, but I'm not an expert on threaded programming, so please comment/vote/compare to other answers as you feel appropriate.
Use a thread-local variable (java.lang.ThreadLocal) which contains a per-thread hashtable used as a first-level cache. If the key is not found in this table, synchronized access is done to a second-level cache, which is a synchronized-access hashtable shared by all threads. In this way, the calculation of the cache value is only ever done once, and it is shared among all threads, but each thread has a local copy of the mapping from keys to values, so there is some memory cost (but less than having independent per-thread caches), but reads are efficient.

A: How about something like this SingletonCache class from one of my projects?
public abstract class SingletonCache<K, V> {

    private final ConcurrentMap<K, V> cache = new ConcurrentHashMap<K, V>();

    public V get(K key) {
        V value = cache.get(key);
        if (value == null) {
            cache.putIfAbsent(key, newInstance(key));
            value = cache.get(key);
        }
        return value;
    }

    protected abstract V newInstance(K key);
}

To use it, you extend it and implement the newInstance method which creates a new value in case of a cache miss. Then call the get method with a key to get an instance which corresponds that key. Here is an example of how it is used.
That class guarantees that for each key, only one instance is returned, but the newInstance method may be called multiple times, in which case the first computed instance is used and the rest are discarded. Also note that this cache does not remove old instances, but stores all values indefinitely (in my use case there is a limited number of instances that must be cached). Reading from a ConcurrentHashMap does not use locking, so it should satisfy your efficiency requirement.

A: How about the cache described in section 5.6 of Concurrency In Practice, by Brian Goetz? It's outlined here.
It only uses classes from the java.util.concurrent package.
The linked article builds up a cache and describes the weaknesses of each version, until final version is an efficient cache in which only one concurrent thread will compute an absent entry.
I've cut and pasted the final code below, but its worth reading through the article and thinking about the issues outlined. Or even better - buy the book - it's great.
import java.util.concurrent.*;

public class Memoizer<A, V> implements Computable<A, V> {
  private final ConcurrentMap<A, Future<V>> cache
      = new ConcurrentHashMap<A, Future<V>>();
  private final Computable<A, V> c;
  public Memoizer(Computable<A, V> c) { this.c = c; }
  public V compute(final A arg) throws InterruptedException {
      while (true) {
          Future<V> f = cache.get(arg);
          if (f == null) {
              Callable<V> eval = new Callable<V>() {
                  public V call() throws InterruptedException {
                      return c.compute(arg);
                  }
              };
              FutureTask<V> ft = new FutureTask<V>(eval);
              f = cache.putIfAbsent(arg, ft);
              if (f == null) {
                  f = ft;
                  ft.run();
              }
          }
          try {
              return f.get();
          } catch (CancellationException e) {
              cache.remove(arg, f);
          } catch (ExecutionException e) {
          // Kabutz: this is my addition to the code...
          try {
             throw e.getCause();
          } catch (RuntimeException ex) {
              throw ex;
          } catch (Error ex) {
              throw ex;
          } catch (Throwable t) {
              throw new IllegalStateException("Not unchecked", t);
          }
        }
     }
  }
}


text:
Q: Min area enclosing rectangle from set of n points I want to find minimal enclosing rectangle for set of n points. First I found convex hull.
If I have a convex hull from set of points ( I got it by doing Graham scan) stored as a sorted list. And from every edge of that convex hull, by binary search I found the point with the most distance. Now having that one edge and point with max distance, how can I find the rest of 2 points so I could make a rectangle. I know that at least two points of extremes of that convex hull must be on minimal enclosing rectangle (Xmin, Xmax, Ymin, Ymax). How can I use that? Does one need to be on edge of polygon and is there any way to do it like this?
Reason I am doing this way is that I need O(nlogn) time complexity.
Every help is appreciated.
Example:

In this example we have Xmin and Ymax on rectangle, but not Xmin or X max


text:
Q: How to get max/min element from a boost multiarray I'm wondering a simple way to find the maximum/minimum element of a boost multiarray, an object of 3 indices as the following:
int iDepth=10,iWidth=10,iHeight=10;
boost::multi_array<GLfloat, 3> image(boost::extents[iDepth][iWidth][iHeight]);

A: This should work :
std::max_element( image.origin(), image.origin() + image.num_elements());

A: Using member data() is more correct because:

*

*ensures that image is actually a contiguous (compact array).

*scans from the beginning of the array, even if the first elements is not [0][0].... (origin() means the address of [0][0]... even if the array "starts" at a different point, e.g. [1][1]....

std::max_element( image.data(), image.data() + image.num_elements());

A: Did you try something like:
std::max_element( image.begin(), image.end());


text:
Q: transfer textfile contents into database python I'm a little new to python/sqlite. I'm trying to transfer the contents of a textile into a database. The textile is formatted like this:
hello hello hello
hello hello hello hello hello
hello hello hello hello

I parse the textile into a 2d list with each line as its own tuple i.e. [hello, hello, hello]. I would like to transfer this list into a database where each element is an attribute and each tuple is its own row - with a few blank attributes since each line is of different length.
I keep the error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied

I'm not sure why this is. I thought I addressed this with my query_string variable. If anyone could help me, that would be great. My code is below:
import sqlite3

ins = open( "foo.txt", "r" )
parseTable = []

for line in ins:
   row = line.rstrip().split(',')
   parseTable.append(row)

#print parseTable

conn = sqlite3.connect('sample.db')
c = conn.cursor()

c.execute('''CREATE TABLE sample (Item_0 TEXT, Item_1 TEXT, Item_2 TEXT, Item_3 TEXT, Item_4 TEXT)''')

query_string = 'INSERT INTO sample VALUES (?, ?, ?, ?, ?)'

c.executemany(query_string, parseTable)

conn.commit()

A: You need to add in some extra None values to pad the rows:
for line in ins:
    row = line.split()[:5]
    row.extend([None] * (5 - len(row)))
    parseTable.append(row)

This splits your sample data on spaces (not commas), caps rows to at most 5 elements, then adds None values if the length is below 4 elements.
The None values are translated into NULLs for the missing columns for those rows.
Demo:
>>> import sqlite3
>>> ins = '''\
... hello hello hello
... hello hello hello hello hello
... hello hello hello hello
... '''.splitlines()
>>> parseTable = []
>>> for line in ins:
...     row = line.split()[:5]
...     row.extend([None] * (5 - len(row)))
...     parseTable.append(row)
...
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('''CREATE TABLE sample (Item_0 TEXT, Item_1 TEXT, Item_2 TEXT, Item_3 TEXT, Item_4 TEXT)''')
<sqlite3.Cursor object at 0x1083d8960>
>>> query_string = 'INSERT INTO sample VALUES (?, ?, ?, ?, ?)'
>>> c.executemany(query_string, parseTable)
<sqlite3.Cursor object at 0x1083d8960>
>>> conn.commit()
>>> c.execute('SELECT * FROM sample')
<sqlite3.Cursor object at 0x1083d8960>
>>> for row in c:
...     print row
...
(u'hello', u'hello', u'hello', None, None)
(u'hello', u'hello', u'hello', u'hello', u'hello')
(u'hello', u'hello', u'hello', u'hello', None)


text:
Q: Creating and initialising a list of objects and assigning them values from a dictionary I have a class with the attributes name and address. I need to create several instances of that class using a dictionary of the format {name:age}. The name and address of each object should come from the dictionary elements.
I am using Python 3.2.

A: How about this:
>>> d = {"Mark": 32, "Jack": 25, "Jane":30}
>>> class Person():
...     def __init__(self,name,age):
...         self.name = name
...         self.age = age
...     def __str__(self):
...         return "{0} is {1} years old.".format(self.name, self.age)
...
>>> a = [Person(name,age) for name, age in d.items()]
>>> print(a[0])
Jane is 30 years old.