text:
Q: FPGA spartan 3 - X mod 3 inside combinatorial process without clock I am working on a project which one part pivots around finding X mod 3 with and FPGA spartan 3 (Xilinx),
inside a combinatorial process.
in fact in this project there are some other modules which are sequential, before this ALU module.
but inside the ALU module, it is not allowed to use sequential process.
so I tried to use one method from here:

Here is an simple way to do it by hand. Since 1 = 22 mod 3, we get 1 =
  22n mod 3 for every positive integer. Furthermore 2 = 22n+1 mod 3.
  Hence one can determine if an integer is divisible by 3 by counting
  the 1 bits at odd bit positions, multiply this number by 2, add the
  number of 1-bits at even bit posistions add them to the result and
  check if the result is divisible by 3.
Example: 5710=1110012. There are 2 bits at odd positions, and 2 bits
  at even positions. 2*2 + 2 = 6 is divisible by 3. Hence 57 is
  divisible by 3.

I have posted my codes down there. the problem is that after I concatenate the odd bits and even bits in two different signals:
        mod_un_t1 <= A(6) & A(4)& A(2) & A(0);
        mod_un_t2 <= A(7) & A(5)& A(3) & A(1);

I lose all data and no if statement works after that. I simulated my code with a  test-bench. but it always gives:
result <= "00000000";

I have tested it and I found out that no data would be pass down after that concatenation.
I cannot use sequential network and count-up and count-down methods, or shift register method which all of them work with clk and sequential process.
Could any one please help me, to solve the problem in my code, and if anyone has a better method or better implementation way let me be through this nowhere!!!
and this is my code:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
Use Ieee.std_logic_unsigned.all;

entity ALU is
   port ( A          : in  std_logic_vector (7 downto 0);   -- Input A
          B          : in  std_logic_vector (7 downto 0);   -- Input B
          FN         : in  std_logic_vector (3 downto 0);   -- ALU functions provided by the ALU_Controller (see the lab manual)
          result       : out std_logic_vector (7 downto 0);   -- ALU output (unsigned binary)
           overflow   : out std_logic;                       -- '1' if overflow ocurres, '0' otherwise
           sign       : out std_logic                        -- '1' if the result is a negative value, '0' otherwise
        );
end ALU;

architecture behavioral of ALU is

signal mod_un_t1: std_logic_vector (3 downto 0);
signal mod_un_t2: std_logic_vector (3 downto 0);
signal mod_un_t3: std_logic_vector (3 downto 0);
signal mod_un_t4: std_logic_vector (3 downto 0);
signal mod_unsigned: std_logic_vector (3 downto 0);

signal mod_si_t1: std_logic_vector (3 downto 0);
signal mod_si_t2: std_logic_vector (3 downto 0);
signal mod_si_t3: std_logic_vector (3 downto 0);
signal mod_si_t4: std_logic_vector (3 downto 0);
signal mod_signed: std_logic_vector (3 downto 0);

begin
   process ( FN, A, B , result_tmp)
   begin
        result <= (others => '0');
        mod_un_t1 <= (others => '0');
        mod_un_t2 <= (others => '0');
        mod_un_t3 <= (others => '0');
        mod_un_t4 <= (others => '0');
        mod_unsigned <= (others => '0');
        mod_si_t1 <= (others => '0');
        mod_si_t2 <= (others => '0');
        mod_si_t3 <= (others => '0');
        mod_si_t4 <= (others => '0');
        mod_signed <= (others => '0');

        if (FN = "0100") then -- Unsigned (A) mod 3
            mod_un_t1 <= A(6) & A(4)& A(2) & A(0);
            mod_un_t2 <= A(7) & A(5)& A(3) & A(1);

            if(mod_un_t1= "1111") then
              mod_un_t3 <= "1000";
            elsif(mod_un_t1 = "1110" or mod_un_t1 = "1101" or  mod_un_t1 = "1011" or mod_un_t1 = "0111") then
                mod_un_t3 <= "0110";
            elsif(mod_un_t1 = "1100" or mod_un_t1 = "1010" or mod_un_t1 = "1001" or mod_un_t1 = "0110" or mod_un_t1 = "0101" or mod_un_t1 = "0011") then
                mod_un_t3 <= "0100";
            elsif(mod_un_t1 = "0001" or mod_un_t1 = "0010" or mod_un_t1 = "0100" or mod_un_t1 = "1000") then
                mod_un_t3 <= "0010";
            elsif (mod_un_t1 = "0000") then
                mod_un_t3 <= "0000";
            end if;

            if (mod_un_t2 = "1111") then
                mod_un_t4 <= "0100";
            elsif (mod_un_t2 = "1110" or mod_un_t2 = "1101" or mod_un_t2 = "1011" or mod_un_t2 = "0111") then
                mod_un_t4 <= "0011";
            elsif(mod_un_t2 = "1100" or mod_un_t2 = "1010" or mod_un_t2 = "1001" or mod_un_t2 = "0110" or mod_un_t2 = "0101" or mod_un_t2 = "0011") then
                mod_un_t4 <= "0010";
            elsif(mod_un_t2 = "0001" or mod_un_t2 = "0010" or mod_un_t2 = "0100" or mod_un_t2 = "1000") then
                mod_un_t4 <= "0001";
            elsif(mod_un_t2 = "0000") then
                mod_un_t4 <= "0000";
            end if;

            mod_unsigned <= mod_un_t3 + mod_un_t4;

            if  (mod_unsigned = "0010" or  mod_unsigned = "0101" or mod_unsigned ="0111" or mod_unsigned = "1010") then
                result <= "00000001";
            elsif (mod_unsigned = "0001" or mod_unsigned = "0100" or mod_unsigned = "1000" or mod_unsigned = "1011") then
                result <= "00000010";
            elsif (mod_unsigned = "0000" or mod_unsigned = "0011" or mod_unsigned = "0110" or mod_unsigned = "1001") then
                result <= "00000000";
            end if;
        end if;

   end process;
end behavioral;

A: The signals that don't seem to have assignments are missing from the process sensitivity list. They could otherwise be variables, allowing their use during the current simulation cycle without generating delta cycles because signal assignment doesn't take effect until the end or the current simulation cycle.
Candidates for variables appear to be:
signal mod_un_t1: std_logic_vector (3 downto 0);
signal mod_un_t2: std_logic_vector (3 downto 0);
signal mod_un_t3: std_logic_vector (3 downto 0);
signal mod_un_t4: std_logic_vector (3 downto 0);
signal mod_unsigned: std_logic_vector (3 downto 0);

signal mod_si_t1: std_logic_vector (3 downto 0);
signal mod_si_t2: std_logic_vector (3 downto 0);
signal mod_si_t3: std_logic_vector (3 downto 0);
signal mod_si_t4: std_logic_vector (3 downto 0);
signal mod_signed: std_logic_vector (3 downto 0);

These declarations could be changed to object class variable and moved to the process (before the begin). The signal assignments for them (<=) would be switched to variable assignment (:=).
You could simply put those that show up on the right hand side of an assignment  in the sensitivity list, but that would cause extra delta cycles.
If there's a reason to keep them signals you could consider breaking your process up into multiple processes and/or other concurrent statements.
There's a result_tmp in the sensitivity list that doesn't have a declaration or an assignment in the code you've shown.
... could you please also give a short example for breaking the process up into multiple processes and/or other concurrent statements?
Aarchitecture foo of ALU is

    signal mod_un_t1: std_logic_vector (3 downto 0);
    signal mod_un_t2: std_logic_vector (3 downto 0);
    signal mod_un_t3: std_logic_vector (3 downto 0);
    signal mod_un_t4: std_logic_vector (3 downto 0);
    signal mod_unsigned: std_logic_vector (3 downto 0);

    signal mod_si_t1: std_logic_vector (3 downto 0);
    signal mod_si_t2: std_logic_vector (3 downto 0);
    signal mod_si_t3: std_logic_vector (3 downto 0);
    signal mod_si_t4: std_logic_vector (3 downto 0);
    signal mod_signed: std_logic_vector (3 downto 0);
    -- dummy
    signal result_tmp: std_logic_vector(7 downto 0);

begin

    -- Concurrent signal assignments - these are just wires
    mod_un_t1 <= A(6) & A(4)& A(2) & A(0);
    mod_un_t2 <= A(7) & A(5)& A(3) & A(1);

UNPROC1:
    process (FN, mod_un_t1)
    begin
    if FN = "0100" then
        case mod_un_t1 is
            when "0000" =>
                mod_un_t3 <= "0000";
            when "0001" | "0010" | "0100" | "1000" =>
                mod_un_t3 <= "0010";
            when "1100" | "1010" | "1001" | "0110" =>
                mod_un_t3 <= "0100";
            when "1110" | "1101" | "1011" | "0111" =>
                mod_un_t3 <= "0100";
            when others =>
            end case;
    else
    --
    end if;
end process;

UNPROC2:
    process (FN, mod_un_t2)
    begin
    if FN = "0100" then
        if mod_un_t2 = "1111" then
            mod_un_t4 <= "0100";
        elsif mod_un_t2 = "1110" or mod_un_t2 = "1101" or mod_un_t2 = "1011" or mod_un_t2 = "0111" then
            mod_un_t4 <= "0011";
        elsif mod_un_t2 = "1100" or mod_un_t2 = "1010" or mod_un_t2 = "1001" or mod_un_t2 = "0110" or mod_un_t2 = "0101" or mod_un_t2 = "0011" then
            mod_un_t4 <= "0010";
        elsif mod_un_t2 = "0001" or mod_un_t2 = "0010" or mod_un_t2 = "0100" or mod_un_t2 = "1000" then
            mod_un_t4 <= "0001";
        elsif mod_un_t2 = "0000" then
            mod_un_t4 <= "0000";
        end if;
    else
        --
    end if;
end process;

ALU_PROC:  -- keep all the arithemetic operations in one process
    process (FN, mod_un_t3, mod_un_t4)
    begin
        if FN = "0100" then
             mod_unsigned <= mod_un_t3 + mod_un_t4;
        else

        end if;
    end process;

OUT_PROC: -- keep all the result assignment in one process
process (FN, mod_unsigned)
    begin
        if FN = "0100" then
            if  mod_unsigned = "0010" or  mod_unsigned = "0101" or mod_unsigned ="0111" or mod_unsigned = "1010" then
                result <= "00000001";
            elsif mod_unsigned = "0001" or mod_unsigned = "0100" or mod_unsigned = "1000" or mod_unsigned = "1011" then
                result <= "00000010";
            elsif mod_unsigned = "0000" or mod_unsigned = "0011" or mod_unsigned = "0110" or mod_unsigned = "1001" then
                result <= "00000000";
            else
            --
            end if;
        end if;
    end process;

end architecture foo;


text:
Q: Method for the push notification messages to reach the website user In terms of websites, How does push notification get displayed ?
Does service workers periodically check the web server for new data and display as notification
or
Server sends message to user based on user IP address or other network details ? in this case website background does not need to check server periodically.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PDO associative arrays - return associative I have this code:
$dbInstance = DB_Instance::getDBO();
$statement = $dbInstance->prepare("SELECT id, name FROM language ORDER BY id");
$statement->execute();
$rows = $statement->fetchAll();

//Create associative array wuth id set as an index in array
$languages = array();
foreach($rows as $r) {
    $languages[$r['id']] = $r['name'];
}
return $languages;

I can't figure out how to use PDO-statement to achieve the same result that array $languages produces. I've tried some different fetch_styles.
I've tried some different styles and I could get like:
[0] svenska
[1] engelska

but I want like:
[1] svenska
[2] engelska

(where 1 and 2 are the values of id in database)
I guess I could create a function and call that with FETCH_FUNC but I'm not sure that would be so great either.
Is the above the best/cleanest way to do it?

A: I think you might be looking for $result = $sth->fetch(PDO::FETCH_ASSOC);
Reference: http://php.net/manual/en/pdostatement.fetch.php
[edit] oops to late :)

A: Everybody forgot about the
$sth->fetchAll(PDO::FETCH_KEY_PAIR);

A: Not really sure if there's any better way. You could try this?
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

$languages = array();

function getLangs($col, $row) {
     $languages[$col['id']] = $col['name'];
}

array_walk($rows, 'getLangs');

There's nothing wrong with foreach loops. I'd actually use what you've got. It's hard to get cleaner than that...
UPDATE:
After carefully re-reading your question, what you REALLY should be asking is whether you can format your QUERY in such a way that the results are returned in a different format.
The way that your normal SELECT query is returned is thusly:
+----+----------+
| id |     name |
+----+----------+
|  1 |  svenska |
|  2 | engelska |
| .. |      ... |
| .. |      ... |
+----+----------+

$row = array(
    row_1 => array(
        id   => "1",
        name => "svenska"
    ),
    row_2 => array(
        id   => "2",
        name => "engelska"
    ),
    row_3 => array(
        id   => "...",
        name => "..."
    ),
    row_4 => array(
        id   => "...",
        name => "..."
    )
)

$row[$row_number][$column_name] = $value

What you're asking for is for some way to return your query results like THIS:
// Query result is only one row, with each 'id' as column name
// And the 'name' from the same row as it's value...

+---------+----------+-----+-----+-----+
|       1 |        2 | ... | ... | ... |
+---------+----------+-----+-----+-----+
| svenska | engelska | ... | ... | ... |
+---------+----------+-----+-----+-----+

$row = array(
    row_1 => array(
          1 => "svenska",
          2 => "engelska",
        ... => "...",
        ... => "...",
        ... => "..."
    )
)

$languages = $row[row_1];
$languages[$id] = $name;

I'm not entirely sure you CAN do this in SQL, to be perfectly honest. I would also recommend against it, even if you could. It would be horrendous for a scaling table. If your table is static, then why not format it in the way I just mentioned to begin with? Why not just have it in a static PHP array in an include file?

A: <?php
$dbhost = 'somehost';
$dbuser = 'someuser';
$dbpw = 'somepw';
$dbname = 'somename';
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,];
$dsn = "mysql:host=$dbhost;dbname=$dbname;";
$pdo = new PDO($dsn, $dbuser, $dbpw, $options);

$data = $pdo->query("SELECT * FROM language")->fetchAll(\PDO::FETCH_UNIQUE);
var_dump($data);

FETCH_UNIQUE does the trick...


text:
Q: How to delete a particular view on the click of button in a ListView in Android? I have made a custom view that consists of two text views and one button. I just want when i click on the button then the respective view is gone and list adjust itselt.
here is my MainActivity.java
package com.dv.deletev;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    ListView lv;
    String name[]={"Ankit","Arora","Arun","yadav"};
    String no[]={"AnAnaAN","cccc","bbbbb","aaa"};
    static CustomAdapter obj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv=(ListView)findViewById(R.id.listView1);

        obj=new CustomAdapter(MainActivity.this,name,no);

        lv.setAdapter(obj);
    //obj.notifyDataSetChanged();
    }

    public static  CustomAdapter take()
    {
        return obj;
    }
}

CustomAdapter.java
package com.dv.deletev;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.dv.deletev.*;

public class CustomAdapter extends ArrayAdapter<String>
{

String name[];
String no[];
    Context con;
    MainActivity a;
    public CustomAdapter(Context con,String a[],String b[])
    {
        super(con,R.layout.second,a);
        name=a;
        this.con=con;
        no=b;
        }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
    LayoutInflater lv=(LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView=lv.inflate(R.layout.second, null);

    TextView tv1=(TextView)convertView.findViewById(R.id.textView1);
    TextView tv2=(TextView)convertView.findViewById(R.id.textView2);
    Button  bt=(Button)convertView.findViewById(R.id.button1);
        final List<String> arr1;
        final List<String> arr2;
        arr1=(List<String>) Arrays.asList(name);
        arr2=(List<String>) Arrays.asList(no);

        final ArrayList<String> arr=new ArrayList<String>(arr1);
        final ArrayList<String> ar=new ArrayList<String>(arr2);

    bt.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

        arr.remove(position);
        ar.remove(position);
        a.take().notifyDataSetChanged();

        //CustomAdapter.this.notifyDataSetChanged();}

        }
    });
        tv1.setText(name[position]);
        tv2.setText(no[position]);

        return convertView;
    }

}

Second.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/textView2"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"

            android:text="Button" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView1"
            android:layout_marginLeft="30dp"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView2"
            android:layout_alignParentTop="true"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>

activity_main.xml
-----------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.dv.deletev.MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

    </ListView>

</RelativeLayout>

there is no such problem on logic part everything works fine, ListView appeared is what i wanted but on the click of button nothing happens.
Any suggestions...?

A: There are a lot of problems in this code, sorry if i will seem salty, i fixed only some necessary things:

*

*two arrays of string with same length passed in an adapter. It's better to use a custom object that wraps these two string instead of two arrays

*the transformation to arraylist without any purpose

*the reference to the adapter from activity context instead from the adapter itself

*the confusion about use arrays items but remove lists items

*the code indentation

*the code variable's name

package com.dv.deletev;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.dv.deletev.*;

public class CustomAdapter extends ArrayAdapter<String>
{

String name[];
String no[];
    Context con;
    MainActivity a;
    //declare them global
    ArrayList<String> arr;
    ArrayList<String> ar;
    public CustomAdapter(Context con,String a[],String b[])
    {
        super(con,R.layout.second,a);
        name=a;
        this.con=con;
        no=b;
        // initialize them in constructor
        arr = new ArrayList<String>(Arrays.asList(name));
        ar = new ArrayList<String>(Arrays.asList(no);
        }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
    LayoutInflater lv=(LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView=lv.inflate(R.layout.second, null);

    TextView tv1=(TextView)convertView.findViewById(R.id.textView1);
    TextView tv2=(TextView)convertView.findViewById(R.id.textView2);
    Button  bt=(Button)convertView.findViewById(R.id.button1);

    bt.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

        arr.remove(position);
        ar.remove(position);
        notifyDataSetChanged();

        //don't use reference of the adapter itself from the activity
        //a.take().notifyDataSetChanged();

        //CustomAdapter.this.notifyDataSetChanged();}

        }
    });
        // set them to list
        tv1.setText(arr.get(position));
        tv2.setText(ar.get(positon));

        return convertView;
    }
}

A: You convert the array to a list and remove the list item but you don't convert the list back to the array, so the remove is lost.
ArrayAdapter already has a remove() method, you should just use that.


text:
Q: SQL help to insert into daily sale table from slaes table plus associated dimensions Still learning developer, and SQL, trying to figure out the best way of doing this.
I want to run a procedure that will take all of the records in SALES, find the associated TERMINALID, MERCHANTID, MERCHANT.BANKACC, MERCHANT.PHONE, and insert them into the DAILYSALE table (which I've created with all the appropriate columns).

Just still trying to get my head around the simplest way of doing this. I know it's not particularly complicated, but I'm still in the beginner stages of learning.

A: INSERT INTO DAILYSALE
(RECEIPTNO, TERMINALID, MERCHANTID, BANKACC, PHONE)
SELECT s.RECEIPTNO, s.TERMINALID, p.MERCHANTID, m.BANKACC, m.PHONE
FROM SALE s
INNER JOIN POSID p ON s.TERMINALID = p.TERMINALID
INNER JOIN MERCHANT m ON p.MERCHANTID = m.MERCHANTID


text:
Q: Need to open an excel file manually in the middle of a macro First time posting so please be kind.
From a template file, I am running a macro to create a new folder with a copy of the template file in it. I then rename it and update it. At one point, I need to manually download a file from a website and open it and then start another macro to finish the update.
I initially tried to do that from one unique macro but I got issues as the macro would keep running before the excel file had time to open.
I have now split my macro in 2. At the end of the 1st macro, I call a userform with instructions and a continue button. The idea is that I would download the file while the userform is opened and click on "continue" when the file is opened.
For some reason, the file does not open at all. It seems like either the userform or the macro stops the file from opening. However, If I run it using the debug function, It works fine...
Public strSN As String, strPart As String, strPath As String

Sub create_new()

' Create Folder if it doesn't exist
'Dim strSN As String, strPart As String, strPath As String

'strSN = SerialNumber.Value
'strPart = PartNumber.Value
'strPath = "M:\Quality\QUALITY ASSURANCE\DOC\Rental Folder\Scanned MRB's\"

' close userform
welcomeform.Hide

'set Microsoft scription runtime reference to allow creation of folder macro

On Error Resume Next
ThisWorkbook.VBProject.References.AddFromGUID "{420B2830-E718-11CF-893D-    00A0C9054228}", 1, 0
On Error GoTo 0

If Not FolderExists(strSN) Then
'Serial Number folder doesn't exist, so create full path
FolderCreate strPath & strSN

End If

' Create new file in new folder

On Error Resume Next

ActiveWorkbook.SaveCopyAs Filename:=strPath & strSN & "\" & strPart & " " & strSN & " " & "SNR.xlsm"

If Err.Number <> 0 Then
    MsgBox "Copy error: " & strPath & "TEMPLATE SNR.xlsm"
End If
On Error GoTo 0

' open new file without showing it or opening macros

Application.EnableEvents = False   'disable Events
Workbooks.Open Filename:=strPath & strSN & "\" & strPart & " " & strSN & " " & "SNR.xlsm"
Application.EnableEvents = True    'enable Events

' Modify serial number and part number in traceability summary form

Sheets("Traceability Summary Form").Activate
Sheets("Traceability Summary Form").Unprotect
Range("A7").Value = strSN
Range("C7").Value = strPart

' update file with ITP

Call Download_itp

End Sub

Sub Download_itp()

downloaditp.Show

End Sub

In the download_itp userform:
Sub continue_Click()

Call update_traceable_items

End Sub

Then the 2nd macro starts with code:
Sub update_traceable_items()
'
' Macro to update the SNR tab with the traceable items from the ITP
'

downloaditp.Hide

' copy ITP in file

Application.ActiveProtectedViewWindow.Edit
ActiveSheet.Name = "ITP"
ActiveSheet.Copy after:=Workbooks(strPart & " " & strSN & " " & "SNR.xlsm").Sheets("SNR template")

Any help would be appreciated!
Thanks

A: The UserForm is being displayed modally, which probably prevents you from "opening" the recently downloaded file. When UserForm is displayed modally, the user is prevented from "interacting" with any part of Excel Application that is not the UserForm itself -- so you can't select cells or worksheets, you can't open files or close files, etc.
This is the default behavior for UserForms, but fortunately there is an optional parameter for the .Show method which allows you to display the form "modelessly":
downloaditp.Show vbModeless

This allows you to interact with the Excel Application while the form is open.
Note: If the file is on a shared network location, you can probably handle this better by using a FileDialog object to allow you to "browse" to the location of the file, and open it, all within the scope of your main procedure, like:
With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    .Show

    If .SelectedItems.Count <> 1 Then
        MsgBox "No file selected!", vbCritical
        Exit Sub
    Else
        Dim NewWorkbook as Workbook
        Set NewWorkbook = Workbooks.Open(.SelectedItems(0))
    End If
End With


text:
Q: hide composer vendor folder that's inside docroot We have setup about two dozen internal web applications. Now years later, I'd like to start using packages from external sources and installing items by using Composer which manages packages. I've never needed it before but would like to try adding some extra functionality to these sites.
The problem is none of these internal websites were setup with /project/public_html/ structures. The document root is the main directory inside WAMP.
So the DOCUMENT_ROOT directories look something like this:
c:\wamp64\www\my-site1\
c:\wamp64\www\my-site2\
c:\wamp64\www\my-site3\

Each project is different and might require different php packages. I'd like to be able to use Composer to manage the packages.
When you run Composer is creates a vendor folder. I know that good practice dictates that we should put it in a structure like this:
C:\wamp64\www\my-project1\vendor  //for vendor code
C:\wamp64\www\my-project1\public_html //for DOCUMENT_ROOT

But what I have ended up with is thus:
C:\wamp64\www\my-site1\vendor  //for vendor code specific to site1
C:\wamp64\www\my-site2\vendor  //for vendor code specific to site2

Can I use apache rewrite rules to hide this vendor folder and all child folders from the public web? Idea being it would deny a user that types in http://my-site1/vendor/somevendor/somefile.php but would still allow my scripts to require or include and use the files in that directory when needed.
Alternatively can I put vendor here:
 C:\wamp64\www\vendor

and then somehow only include the vendor projects that I want? Not all vendor packages to every project, some way to specify which classes or packages I want to use on a per site basis.

A: You may consider keeping vendors outside of docroot with following files structure:
c:\wamp64\www\my-site1\
c:\wamp64\www\my-site2\
c:\wamp64\www\my-site3\
c:\wamp64\www\vendors\my-site1\
c:\wamp64\www\vendors\my-site2\
c:\wamp64\www\vendors\my-site3\

Configuring vendor directory in composer.json:
"config": {
    "vendor-dir": "../vendors/my-site1"
},

And including autoloader in your index.php:
require __DIR__ . '/../vendors/my-site1/autoload.php';

If you can't change directory for vendors, you may use mod rewrite to disallow access to vendor directory. Put this into your main .htaccess file (for example to c:\wamp64\www\my-site1\.htaccess:
RewriteEngine on

RewriteRule ^vendor/(.*)?$ / [F,L]
RewriteRule ^composer\.(lock|json)$ / [F,L]

Using .htaccess inside of vendor directory will also work, bu it is easy to accidentaly delete this file - usually vendor directory is not versioned in VCS and many problems with composer are solvable  by "delete vendor directory and run composer install again" (which will also remove your .htaccess and make vendor directory accessible from web).

A: You can simply place a .htaccess file in your vendor folder with:
Order allow,deny
Deny from all

Files inside the vendor folder won't be accessible by typing url in a browser but will be available for your scripts.

A: Utilizing @wizardnx answer, you can update your composer.json to add the .htaccess file to the vendor directory after running composer install command as following:
{
    "require": {
        "robmorgan/phinx": "^0.13.4"
    },
    "scripts": {
        "post-update-cmd": [
            "php -r \"file_put_contents('vendor/.htaccess', 'Order allow,deny' . PHP_EOL . 'Deny from all');\""
        ]
    }
}


text:
Q: ZeroRPC bind multi-port for process I want to bind multi-port at server and wait client connect. After I bind more than one port. The first port is okay, but the second port client can not connect. The below are my sample code.
class HelloRPC(object):
  def hello(self, name):
        print   "this is server"
        return "Hello"
s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")

s1 = zerorpc.Server(HelloRPC())
s1.bind("tcp://0.0.0.0:5000")

s.run()
s1.run()

A: The call for s.run() blocks, preventing you from being able to get to s1.run().
One way to deal with this is to use gevent to spawn multiple greenlets to run the server:
import zerorpc
import gevent

class HelloRPC(object):
    def hello(self, name):
        print "this is server"
        return "Hello"

s = zerorpc.Server(HelloRPC())
s.bind("tcp://127.0.0.1:5001")

s1 = zerorpc.Server(HelloRPC())
s1.bind("tcp://127.0.0.1:5002")

gevent.joinall([gevent.spawn(s.run), gevent.spawn(s1.run)])

With that, you can run:
> zerorpc tcp://127.0.0.1:5002 hello world
connecting to "tcp://127.0.0.1:5002"
'Hello'
> zerorpc tcp://127.0.0.1:5001 hello world
connecting to "tcp://127.0.0.1:5001"
'Hello'

Check out the ZeroRPC tests for more examples of how to run multiple servers.

A: You can also create just one server instance and bind it to several ports as follows:
class HelloRPC(object):
  def hello(self, name):
        print   "this is server"
        return "Hello"
s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.bind("tcp://0.0.0.0:5000")

s.run()

Note that this is different than the example that you provided. While in your example, two clients connecting to different ports will interact with distinct instances of the HelloRPC class, in my example they will interact with the same HelloRPC instance.


text:
Q: Assetic how to merge css and scss files I try to use Assetic to merge my css and scss files into one, however there was a bug during compilation. When I enter in the console: php app/console assetic:dump
My code:
{% stylesheets
"@PortalSlubnyMainBundle/Resources/public/scss/main.scss" filter="compass"
"@PortalSlubnyMainBundle/Resources/public/css/*"

%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

A: OK I found the solution.
1. First rename jquery-ui-1.10.3.custom.min.css to jquery-ui-1.10.3.custom.min.scss
2. Second thanks to scss compatibility with css I can do sth like this in my template file:
{% stylesheets filter='?uglifycss' filter="cssrewrite" filter="compass"
"@PortalSlubnyMainBundle/Resources/public/scss/settings.scss"
%}
   <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

settings.scss
/* foundation files */
@import "foundation";

/* compass specific files */
@import "compass/css3/images";

/* portalslubny variables files - must be imported before scss files */
@import "variables.scss";

/* other css files converted to scss */
@import "jquery-ui-1.10.3.custom.min";

/* portalslubny scss files */
@import "main.scss";
@import "header.scss";
@import "footer.scss";


text:
Q: Выбор инструмента Стоит цель для самообразования, загрузить картинку на файлообменник без API
Просто закинуть файл через форму и получить ссылку.
Знаю что можно это сделать с помощью Selenium, наверно самое простое, но это довольно медленно.
А как ещё можно взаимодействовать (без API) ?


text:
Q: What's the ActiveRelation (arel) equivalent to :from I have this named_scope in one of my models:
named_scope :latest_100,
            :from => '(select * from videos order by videos.created_at desc limit 0, 100) as videos'

Its purpose is to create a pool of the last 100 videos (returning that results as 'videos' so the other scopes operate on that dataset), and then I can chain scopes after that and filter records out of that pool of results.
# video.rb
named_scope :most_popular, :order => 'popularity'
named_scope :take_5, :limit => 5

# video_controller.rb
# it gets the latest 100 videos, then sorts those by popularity, and takes the top 5.
@videos = Video.latest_100.most_popular.take_5

Is there an equivalent statement for Arel?

A: There exists a .from() method in Arel.
I used it in the following manner:
# video.rb
scope :latest_100, from('(select * from videos limit 100 order by created_at desc) as videos')
scope :most_popular, order('popularity')
scope :take_5, limit(5)

# video_controller.rb
@videos = Video.latest_100.most_popular.take_5

The latest_100 will create a pool of valid videos from which you can pull the top 5 most popular.


text:
Q: Warning: You should not use  and  in the same route;  will be ignored Hello i try to protected route if is no auth but it is not work
Warning: You should not use Route component and Route render in the same route; Route render will be ignored
App.js
  import React, { Fragment, useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import NavBar from './component/Layout/NavBar';
import Landing from './component/Layout/Landing';
import Login from '../src/component/Auth/Login';
import Register from '../src/component/Auth/Register';
import Dashboard from './component/dashboard/Dashboard';
import Alert from './component/Auth/Alert';
import PrivateRoute from './component/routing/PrivateRoute';

import './App.css';

// Redux
import { Provider } from 'react-redux';
import store from './store';
import setAuthToken from './utils/token';

import { loadUser } from './action/auth';

if (localStorage.token) {
  setAuthToken(localStorage.token);
}
const App = () => {

  useEffect(() => {
    store.dispatch(
      loadUser());
  }, []);

  return (
    <Provider store={store}>
      <Router>
        <Fragment>
          <NavBar />
          <Route exact path="/" component={Landing}></Route>
          <section className="container">
            <Alert />
            <Switch>
              <Route exact path="/login" component={Login}></Route>
              <Route exact path="/register" component={Register}></Route>
              <PrivateRoute exact path="/dashboard" component={Dashboard}></PrivateRoute>
            </Switch>
          </section>
        </Fragment>
      </Router>
    </Provider>
  );
};

export default App;

PrivateRoute.js
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';

const PrivateRoute = ({
  componet: Component,
  auth: { isAuthenticated, loading },
  ...rest
}) => (
  <Route
    {...rest}
    render={props =>
      !isAuthenticated && !loading ? (
        <Redirect to="/login" />
      ) : (
        <Component {...props} />
      )
    }
  />
);

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

Warning: You should not use "Route component" and "Route render" in the same route; "Route render" will be ignored
how can I fix it ?

A: Use <Route render={() => <YourComponent />} /> instead of <Route component={YourComponent} />.
Don't combine two of those, react does not like that.

A: From route rendering method:

There are 3 ways to render something with a <Route>:
- <Route component>
- <Route render>
- <Route children>

Each is useful in different circumstances. You should use only one of these props on a given

PrivateRoute contains both component and render prop. You can only use one rendering method but not both.
<PrivateRoute exact path="/dashboard" component={Dashboard}></PrivateRoute> // here

const PrivateRoute = ({
  ...
}) => (
  <Route
    render={props => ()} // here
  />
);

FIX
: Rename component prop to comp since it's acting as an HOC:
// rename prop to `comp`
<PrivateRoute exact path="/dashboard" comp={Dashboard}></PrivateRoute>

const PrivateRoute = ({
  comp: Component, // use comp prop
  auth: { isAuthenticated, loading },
  ...rest
}) => (
  <Route
    {...rest}
    render={props =>
      !isAuthenticated && !loading ? (
        <Redirect to="/login" />
      ) : (
        <Component {...props} />
      )
    }
  />
);


text:
Q: How to create an index.html page with a web address In Windows there is an option to allow you create an index.html file which opens a specific web address when clicked on it. How can I create a similar file in Mac?
I want to have a file called index.html and when clicked, a web address www.example.com should open in the default browser.

A: If you are determined to use an HTML file, you can create one with a text editor (e.g. the built-in TextEdit; make sure you use the Plain Text view rather than the Rich Text which is the default).
Your HTML file should contain a so-called meta-refresh tag for this:
<meta http-equiv="refresh" content="0; url=http://www.example.com/" />

The page will automatically redirect upon loading.
Alternatively, because this sounds like an XY-problem: create a shortcut to the page on your Desktop, as described by Joonas.

A: Drag favicon from a browser to the desktop or into Finder.
This creates a .webloc file, which will open in the default browser when opened.

In some sites you may have to drag the lock icon, info icon... or whatever is on the immediate left from the site url in the address bar. You may also try selecting the url and dragging that, but that doesn't work in Chrome at least, I believe.

Works in Safari, Chrome and Firefox

I should also mention that you should be able to do this with any link elements in a website as well. It may not work if javascript is used load things when the link is clicked.


text:
Q: How to add a filter on all @RequestMapping methods of a Spring servlet? Can I add a filter for any @RequestMapping method in any @RestController?
I want that filter to apply on the mapping object. Thus, after the request has been mapped to the DTO, but before the @RequestMapping method executes.
Is that possible at all?
@RestController
public class MyServlet {
    @RequestMapping(method = GET)
    public void get(GetDTO dto) {
    }

    @RequestMapping(method = POST)
    public void get(PostDTO dto) {
    }
}

A: You can use interceptors:
public interface HandlerInterceptor {

    boolean preHandle(HttpServletRequest request,
                      HttpServletResponse response,
                      Object handler) throws Exception
}

From javadocs:

Intercept the execution of a handler. Called after HandlerMapping
  determined an appropriate handler object, but before HandlerAdapter invokes the handler.

See also In a Spring-mvc interceptor, how can I access to the handler controller method?

A: You could use aspects, setting a point cut before calling the method you want to intercept.
Something like:
@Before("execution(* ..MyServlet.*(*)) && args(param)")
public void beforeGetDTOMethod(GetDTO param) {
    // Advice implementation
}

That will intercept calls to any method within MyServlet class with a GetDTO parameter.
If what you are trying to achieve is update the input parameter you need to go for an around advice.
Bear in mind that, when working with aspects, you are working with proxies.
Before advice
Passing parameters to advice
The AspectJ documentation


text:
Q: Azure Deployment - How to add an assembly? My project is working fine on localhost, but I would like to push my project on a Windows Azure Cloud Service.
I did everything nice to publish the project. However I have missing assemblies for the deployment :
Warning 1   The web project 'MyProject' is dependent on the following
MVC assembly: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\
v2.0\Assemblies\Microsoft.Web.Infrastructure.dll. MVC assemblies must be added to
the package or installed on the virtual machine for your web role. For more details
about this, see the following help page: http://go.microsoft.com/fwlink/?LinkId=218227.

I checked the references and the Microsoft.Web.Infrastructure is inside of the project.

Could someone could help me to add this assembly to the publish package ?
Thanks

A: You should set the "Copy Local" Property to "True" on Properties Window.


text:
Q: How to map the value of a h:selectBooleanCheckbox in a ui:repeat with in ui:repeat Please help me how to map the value in h:selectBooleanCheckbox in a ui:repeat within a ui:repeat
I have tried the below code but selected values not populated in javabean
bean:
public Map<String, Map<String, Boolean>> getSelectedAttributeValues() {
      return selectedAttributeValues;
}

public void setSelectedAttributeValues(Map<String, Map<String, Boolean>> selectedAttributeValues) {
    this.selectedAttributeValues = selectedAttributeValues;
}

xhtml:
<ui:repeat value="#{productListForm.catalogueAttributeNames}" var="catAttrName">

<h:outputText value="#{catAttrName}"/>

                    <ui:repeat value="#{productListForm.catalogueResultBean.catalogueAttributes[catAttrName]}" var="productAttr">

                            <h:selectBooleanCheckbox id="selectedAttr" value="#{productListForm.selectedAttributeValues[catAttrName][productAttr.value]}"/>
                            <h:outputLabel for="selectedAttr">
                                <h:outputText value="#{productAttr.valueDisplay}"/>
                            </h:outputLabel>

                    </ui:repeat>

                        <h:commandLink styleClass="product_search_update_link" action="#{productListForm.filterAction}">
                            <h:outputText  value="#{text['productSearch.result.updateResult']}"/>
                        </h:commandLink>

     </ui:repeat>

After selecting a check box java bean had empty hashmap and there is no values with boolean flag.
what is wrong in the above code?
Thanks in advance


text:
Q: package error when building spfx webpart I am using the following breadcrum sample. To reproduce the error use command: gulp serve
Error I  got:

./src/extensions/siteBreadcrumb/SiteBreadcrumbApplicationCustomizer.ts
  Module parse failed: C:\Users\username\Projets\26_name\Code\Breadcrumb\sp-dev-fx-extensions\samples\react-application-breadcrumb\src\extensions\siteBreadcrumb\SiteBreadcrumbApplicationCustomizer.ts Unexpected token (15:16)
  You may need an appropriate loader to handle this file type.
  | import { ISiteBreadcrumbProps } from './components/ISiteBreadcrumb';
  |
  | const LOG_SOURCE: string = 'SiteBreadcrumbApplicationCustomizer';
  |
  | /**`


text:
Q: What can cause '/var/lib/mysql/mysql.sock' to get deleted? All of a sudden I started to get this error message on my CentOS WHM Cpanel LAMP stack:
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

I restarted the MySQL server via WHM, MySQL started working again however, in just a few seconds/minutes it went down and the above error message returned. This happened several times.
I Googled around for a solution and confirmed that '/var/lib/mysql/mysql.sock' was missing and simply created an empty file '/var/lib/mysql/mysql.sock', restarted the MySQL server via WHM and MySQL started working again and it did not go down this time.
My question is, what could have caused this in the first place?
And shouldn't the initial restart restore any missing /var/lib/mysql/mysql.sock file? Also, why did the restart work and then the error returned?
If the /var/lib/mysql/mysql.sock file was missing, the restart should not have worked until I recreated the /var/lib/mysql/mysql.sock file?
Before the first failure, the server load did peak (but did not peak after).
Also, I got this error:
Access denied for user 'root'@'localhost' (using password: YES)

I changed the password via WHM which stopped that error, but then, the sock errors didn't go away.
Any ideas what happened?

A: It will require some more investigation but here are a few specific things to be aware of.
1.) When you are unable to connect to MySQL have you verified with "service mysql status" to check if it is running?  The chances are it probably is not and that also explains why mysql.sock would go away (when MySQL is shutdown you will see mysql.sock is deleted - you can test this with "service mysql shutdown")
2.) Note that recreating the mysql.sock as a plain file has no effect even if the server was running still (though I doubt it was running).  mysql.sock is a socket and not a normal file and can only be created through restarting MySQL.
3.) Most importantly you should browse your /var/lib/mysql/*.err log for errors which should give you a clue or hint of what the issue is.
4.) If #3 does not help clarify things you want to check your Apache logs for unusual activity.  A lot of database crashes or shutdowns are related to DOS attacks, hacking or even cPanel updates that fail (in the order of most likely from my experience).


text:
Q: C++ Builder - No DragLeave event handler. I am trying to find or create an event handler for when my item is dragged outside a form, im using C++ Builder 2007.
You can use Mouse Leave and also use WndProc but this will only work when the user is not dragging (ie has the mouse button pressed too).
Any ideas?
Thanks

A: VCL drag-and-drop only works within the VCL window, and only when dragging over VCL controls.  In order to drag something outside of the window, you have to use OLE drag-and-drop instead by implementing the IDropSource and IDataObject interfaces and pass them to the DoDragDrop() function.


text:
Q: arrayByAddingObjectsFromArray? I am not sure what I am doing wrong here? I have tried various combinations to try and copy an array into variable mmm.  I am trying to learn how to create a 2D array and then run a loop to place init_array into 10 columns.
// NSMutableArray *mmm = [NSMutableArray arrayWithCapacity: 20];
NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @"a", @"b", @"cat", @"dog", nil];
NSMutableArray *mmm; //= [NSMutableArray arrayWithObjects: @"1", @"2", @"3", @"4", nil];

[mmm arrayByAddingObjectsFromArray:kkk];

NSLog(@"Working: %@",[mmm objectAtIndex:3]);

thanks...
so this works from the given answer:
NSMutableArray *mmm = [NSMutableArray arrayWithCapacity: 20];
NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @"a", @"b", @"cat", @"dog", nil];

[mmm addObjectsFromArray:kkk];

NSLog(@"Working: %@",[mmm objectAtIndex:3]);

A: arrayByAddingObjectsFromArray: returns a new (autoreleased) NSArray object. What you want is addObjectsFromArray:.

A: arrayByAddingObjectsFromArray: returns a new NSArray that includes the objects in the receiver followed by the objects in the argument. The code you posted there, with mmm unset, will probably just crash since mmm doesn't point to an NSArray object. If you had assigned an array to mmm, then it would return (@"1", @"2", @"3", @"4", @"a", @"b", @"cat", @"dog") — but you don't assign the result to any variable, so it just goes nowhere. You'd have to do something like NSArray *yetAnotherArray = [mmm arrayByAddingObjectsFromArray:kkk].
If you have an NSMutableArray and you want to add objects from another array, use addObjectsFromArray:.


text:
Q: Converting date to GMT I want to convert a date to GMT.
I get a date in BST, I want to convert it to GMT without time zone conversion.
Example:
**If the BST date is: Wed June 26 13:30:13 BST 2019
I want to convert it to Wed 26 Jun 2019 13:30:13 GMT**
I want to ignore the timezone info and return the same date as GMT.
For this I am trying
        private SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            private SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            private SimpleDateFormat dateFormatGmtText = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss 'GMT'");

              dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
          String textDate = dateFormatLocal.format(date);

//Date is Wed June 26 13:30:13 BST 2019
    private Date toGMTDate(final Date date) {
            String textDate = dateFormatLocal.format(date);
            try {
                String[] dateParts = textDate.split("\\+");
                textDate = dateParts[0] + "+0000";
                return dateFormatGmt.parse(textDate);
            } catch (ParseException e) {
                return null;
            }
        }

        private String toGMT(final Date date) {
            return dateFormatGmtText.format(toGMTDate(date));
        }

When I call toGMT it returns Wed 26 Jun 2019 14:30:13 GMT
I am not sure why it is so?
What is wrong here?

A: java.time
You said you can't use the modern date and time API, but for other readers I should like to present that option first. SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome, so I recommend avoiding them.
I am assuming that BST is for British Summer Time (other interpretations exist). And I am assuming that you cannot avoid getting an old-fashioned Date object.
private static DateTimeFormatter formatter
        = DateTimeFormatter.ofPattern("EEE dd MMM yyyy HH:mm:ss z", Locale.UK);
private static ZoneId britain = ZoneId.of("Europe/London");
private static ZoneId gmt = ZoneId.of("Etc/GMT");

private static String toGMT(final Date date) {
    ZonedDateTime britishTime = date.toInstant().atZone(britain);
    ZonedDateTime gmtTime = britishTime.withZoneSameLocal(gmt);
    return gmtTime.format(formatter);
}

Try it out with your Date of Wed Jun 26 13:30:13 BST 2019:
    String textDate = dateFormatLocal.format(date);
    System.out.println(textDate);

    System.out.println(toGMT(date));

Output is:

2019-06-26T13:30:13+0100
Wed 26 Jun 2019 13:30:13 GMT

Whenever you get an old-fashioned Date, the first thing to do is to convert it to Instant. Then do any further conversions from there. The key to changing time zone and keeping the date and time of day (hour-minute-second of day) is the withZoneSameLocal method of the ZonedDateTime class.
I recommend specifying locale for the formatter.

I am not sure why it is so? What is wrong here?

A Date hasn't got, as in cannot have a time zone. It's a point in time, nothing more. YourtoGMTDate method returns a point in time that is an hour later: The time you gave it was 13:30:13+0100, and it returned 13:30:13+0000, which is the same point in time as 14:30:13+0100. Next you formatted this point in time using a formatter that used your default time zone, Europe/London, and therefore produced 14:30:13, but at the same time printed GMT in the string — the result you reported.

…the new time library, but for some reasons I can't use them.

If you really have got an evil boss that either forces you to use Java 1.4 or 1.5 and/or forbids the use external dependencies, the pretty simple hack is:
private String toGMT(final Date date) {
    return dateFormatGmtText.format(date);
}

The cheating is: Your dateFormatGmtText uses your default time zone, Europe/London, but lies and prints GMT in the formatted string. This gives the same output as above — the output you asked for. Compared to your code I am just leaving out the date conversion.
Link: Oracle tutorial: Date Time explaining how to use java.time.


text:
Q: When is a module over $R$ and $S$ an $R \otimes S$-module? Suppose $M$ is a module over $R$ and $S$, commutative rings with $1$.
Under what conditions is $M$ also a $R \otimes S$-module?
Also, a more general question: How to construct a structure of a $R \otimes S$-module? In other words, when one wants to construct a map from $R \otimes S$ to another ring, one can use the universal property of tensor products. What can one do to have a structure of a $R \otimes S$-module?

A: Commutativity is unimportant. If $R, S$ are two rings and $M$ is a (left) module over both of them, then all you know is that $M$ is a (left) module over the free product $R*S$ by the universal property of the free product (a slight misnomer as the free product is actually the coproduct in the category of rings). The free product is very different from the tensor product, and among other things is often noncommutative even if $R, S$ are commutative; for example the free product of $\mathbb{Z}[x]$ with itself is $\mathbb{Z} \langle x, y \rangle$, the ring of noncommutative polynomials in two variables (e.g. the free ring on two elements).
To get an $R \otimes S$-module structure you need to assume that the actions of $R$ and $S$ commute, i.e. that $r(s(m)) = s(r(m))$ for all $r \in R, s \in S$.
To get $R \otimes S$-modules in general, take a tensor product $M \otimes N$ where $M$ is an $R$-module and $N$ is an $S$-module.

A: For general rings there is a one-to-one correspondence between $R-S$ bimodule structures on $M$ and the $R\otimes S^{op}$ module structures on $M$.
In your case, when $S$ is commutative, this amounts to an $R\otimes S$ module.  I can't immediately think of an example of a module over two commutative rings which cannot be a bimodule over them... maybe this is already addressed by the QY's post earlier.
Update:
So, you will be able to get an $R\otimes S$ structure exactly when you can get an $R-S$ bimodule structure. This is indeed more restrictive than merely being a module over the two rings. Mariano Suárez-Alvarez came up with a neat example at An $R$ module and $S$ module that cannot be an $R$-$S$ bimodule demonstrating that it's not always possible to make an $R\otimes S$ module out of $M$.

A: I think I found a nice way of constructing an $R \otimes S$-module structure.
Notice that the data of an $R$-module structure (for any ring $R$) is given by:

*

*an abelian group $M$, and

*a homomorphism of rings $R \rightarrow End(M)$, where $End(M)$ is the ring of group endomorphisms of $M$ (where the operations are addition and composition).

Having said that, to construct an $R \otimes S$-module structure on $M$, we just need a ring homomorphism from $R \otimes S$ to $End(M)$. This can be constructed using the usual universal property of tensor products.
As an example, let $M$ is an $R$-module and an $S$-module such that the actions of $R$ and $S$ commute. Assume these structures are given by maps $\varphi: R \rightarrow End(M)$ and $\psi: R \rightarrow End(M)$, then we can define a structure of $R \otimes S$-module on $M$ via the ring homomorphism
$r \otimes s \mapsto \varphi(r) \circ \psi(s)$.


text:
Q: What are "combinatorial factors" in the Lagragian? I'm reading "Renormalization" by John C. Collins and in the fifth chapter "Renormalization" under the subchapter 5.6 "Relation to $\mathcal L$", he defines the Lagrangian and its components.  Then he says:

Now that we have developed a convenient notation, the most difficult part of the proof is to ensure that the combinatorial factors come out right.

What are "combinatorial factors" here?


text:
Q: Long term data saving in assembly 8086 I am building a school project in assembly 8086, and it's some kind of library management program, which you can choose your library, add customers to your list, add books and more. I am trying to save my data for long term using txt files but I don't know how to make it most efficient. Is there another way to save my data in assembly? Like database or XML?

A: This question is probably "too broad" for SO, but I will still "answer" it, because in comments it would get too crowded, need some formatting for this one.

to make it most efficient

In what way most efficient?
For smallest size on disk you can use some compression, but that will hurt performance (and also it's not trivial to code it, especially in 16 bit 8086 real mode with limited amount of memory, any modern compression scheme would be pain or underperform, as they often need tens-hundreds of mega bytes of memory to build up dictionary tables/etc).
For performance and code simplicity you may probably rather design your own custom binary file format, dumping memory state to disk and reloading it as such, with some good memory structures for data and making the data occupy consecutive blocks of memory, dumping/reading the whole block is simplest to code, and will perform reasonably.
For easiest data checking and further re-usability of data some kind of TXT/json/XML file format would be better, so even human can read/modify the stored data outside of your code, but this will require more coding, some code to format current binary data in memory into the textual representation, which gets written to disk, and some parser to read such textual data back and convert them into the binary structures/values in the memory.
I find XML pointlessly verbose and being both ineffectively large (when compared to binary data), and still difficult to edit by human, as the XML tags require lot of writing, whenever it makes sense, I prefer JSON over XML, as it is a bit simpler to write it by hand in pure text editor without any assist, and it's a bit simpler to read. But there are situations where XML makes lot more sense, as it's slightly different thing. In case of data dump like you are asking for, I guess having custom TXT file (with some custom formatting rules, how to create the structure of data) or JSON is enough, I don't see where XML would bring something helpful to it.
Maybe start with the binary dump+reload of whole data structure from memory, as that should be easiest to code, then try to write by hand few TXT files to see if you can figure out some nice way how to structure the data, and try to write then formatter-writer and parser for such data.
As your target platform is DOS I guess (from the "8086" limit), there are just OS services to write/read certain amount of bytes to/from file. No formatting/processing whatsoever is provided by DOS, so everything around TXT/XML/database/... is up to you and your code. You can read/write block of bytes with DOS services, anything above that must be programmed by you. (or you can try to find some library, but as that technology is now like 20+ years dead and obsolete... good luck)


text:
Q: google map : get user's location like google I would like to center a gmap to the user's location. Like google map itself, when you're going on maps.google.com, the center is our own location.
I found this http://www.w3schools.com/html/html5_geolocation.asp but like the tuto says, the user has to approve it because this code give you the exact lat and lng.
But google map doesn't ask this (or maybe?), maybe because the position isn't very sharp, and only shows the city and not the exact position ? This is what i want to do, get an approximate position and center the map to the city where the user is located + the cities around is enough, i don't want to know where the user is exactly located.
im using javascript
Can you help me ?
Thanks

A: I recommend a website www.iptolatlng.com which is available for US users only, but there are other sites like it that will provide approximate location in latitude/longitude based on IP address.
http://www.telize.com/ is another one since the first link seems to no longer work.


text:
Q: ListPreference Dropdown I am using preference screen in Tabhost,so it was displaying the preference background white in order to fix it I used a theme which changed background color to black
but the same is appled to the listprefernce dropdown list as well and I can't see any option
as idiotic question as it sounds it has been killing me for hours
thanks in advance


text:
Q: JSON Stringify - PHP json_decode I am new to JSON,ofr a project of my own I need to send array of objects to the server. Basically, I have a Question object, which has a couple of properties, like question, optionA, optionB etc. I have an array of Question objects.
example:
qArray = new Array();
qArray.push(new Question("where do you live?", "England", "ıtaly", "Usa");

I am adding a lot of questions objects to this array and in the end, I need to send this array to the server, like this:
$.post("backend-stuff/aj-save-test.php", { testName : $("#testName").val().toString(), 'questions' : JSON.stringify(qArray)}, function(result){
        alert(result);
    });
}

In PHP, I use this,
$questions = json_decode($_POST["questions"]);
$testName = $_POST["testName"];

Problem is that I cant read data, either I am sending it in the wrong way or whats wrong is on the php side.
Thank you for answers, I checked Google before sending the question, so please forgive me if this is so easy but for me its not so.

A: To convert stdClassObject to an array, check out get_object_vars().


text:
Q: Extract more rows from a left join with Laravel I have to extract the rows where the created_at is inside the week. Unfortunately, only one line is extracted from me and no more lines as I expected. Why?
Query:
 $scadenze = DB::table('processi')
 ->leftJoin('scadenze', 'processi.id', '=', 'scadenze.processo_id')
 ->where('responsabile',$utente->id)
 ->whereNotIn('scadenze.stato', [4,5])
 ->whereBetween('scadenze.termine_stimato',[\Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
 ->avg('tempistica');

This query extract just one row, but in reality many more lines should be extracted.

A: Because ->avg('tempistica'); return average value from all your rows in this query, i.e. return just one value.

A: Solution:
I was wrong to use the avg with sum function. The rows were extracted correctly but instead of being added (by timing) an average was made. Thank you all for your help.


text:
Q: How to use url: instead of data: for onExpandRow function? I followed the example for onExpandRow, however I can't figure out how to use the row information that is passed with a url for my table instead of the data tag. Currently it just replicates my whole table in the expand function, not just the rows data. Probably a simple fix but I am missing it.
onExpandRow: function (index, row, $detail) {
console.log(row)
  $detail.html('

').find('table').bootstrapTable({
            url: 'table.php',
            columns:[{
                field: 'mfr_name',
                title: 'manufacturer'},
                {field: 'phone_number',
                title: 'phone'},
            ],

        })

The example has the data saved in a variable and uses the data: call instead of the url: one.
var data = [{
'col1': '1.1',
'col2': '1.2',
'nested': [{
'col3': '1.3',
'col4': '1.4',
'col5': '1.5'
}]
 onExpandRow: function(index, row, $detail) {
  console.log(row)
  $detail.html('

').find('table').bootstrapTable({
    clickToSelect: true,
    columns: [{
      field: 'select',
      checkbox: true
    }, {
      field: 'col3',
      title: 'Col3'
    }, {
      field: 'col4',
      title: 'Col4'
    }, {
      field: 'col5',
      title: 'Col5'
    }],
    data: row.nested,

A: Did you mean something like this:
http://jsfiddle.net/eitanmg/m41ok0ue/12/
The main change is when expanding the row, it will make AJAX call to get the data you want from remote resource and not from local variable.
 $(function () {
  $('#table').bootstrapTable({
    data: data,
    detailView:true,
    onExpandRow: function (index, row, $detail) {
    $detail.html('Loading request...');
    $.ajax({
        type: "GET",
        url: "/your_custom_url_that_contains_the_data",
        success: function (result) {
          $detail.html('

').find('table').bootstrapTable({
          columns: [{
              field: 'select',
              checkbox: true
              }, {
              field: 'col1',
              title: 'Col1'
              }, {
              field: 'col2',
              title: 'Col2'
              }, {
              field: 'col3',
              title: 'Col3'
          }],
          data: JSON.parse(result),
          });
        }
      });
    }
  });
});


text:
Q: How to get the difference of two objects by subtracting properties, regardless of depth level? I want to subtract the values of two objects of the exact same structure. Although one answer exists here, it's limited to objects of no-depth. In my case, I'm looking for a robust solution that would allow subtracting objects of any depth, as long as they're of the same structure.
Example
Consider the following two objects, earthData2022 and earthData2050:
const earthData2022 = {
  distanceFromSun: 149280000,
  continents: {
    asia: {
      area: 44579000,
      population: 4560667108,
      countries: { japan: { temperature: 62.5 } },
    },
    africa: { area: 30370000, population: 1275920972 },
    europe: { area: 10180000, population: 746419440 },
    america: { area: 42549000, population: 964920000 },
    australia: { area: 7690000, population: 25925600 },
    antarctica: { area: 14200000, population: 5000 },
  },
};

const earthData2050 = {
  distanceFromSun: 149280000,
  continents: {
    asia: {
      area: 44579000,
      population: 4560767108,
      countries: { japan: { temperature: 73.6 } },
    },
    africa: { area: 30370000, population: 1275960972 },
    europe: { area: 10180000, population: 746419540 },
    america: { area: 42549000, population: 964910000 },
    australia: { area: 7690000, population: 25928600 },
    antarctica: { area: 14200000, population: 5013 },
  },
};

Please note that both objects have:

*

*exact same structure

*all values are numbers, either integers or decimals. There are no strings or booleans, nor arrays.

I want to subtract: earthData2050 - earthData2022 to get a new object:
// desired output
// continents' areas aren't expected to change so their diff is `0`
// likewise, the distance of earth from sun
const earthDataDiff = {
  distanceFromSun: 0,
  continents: {
    asia: {
      area: 0,
      population: 100000,
      countries: { japan: { temperature: 11.1 } },
    },
    africa: { area: 0, population: 40000 },
    europe: { area: 0, population: 100 },
    america: { area: 0, population: -10000 },
    australia: { area: 0, population: 3000 },
    antarctica: { area: 0, population: 13 },
  },
};

As mentioned above, it's tempting to use the sweet answer given here:
function mySub(x, y) {
  return Object.keys(x).reduce((a, k) => {
    a[k] = x[k] - y[k];
    return a;
  }, {});
}

However, when calling mySub() we get this unsurprising output:
mySub(earthData2050, earthData2022)
// {"distanceFromSun":0,"continents":null}

My question, therefore, is how I can recursively subtract all entries, no matter how deep, provided that the objects have the same structure. Also, as I'm running this code on Node, I'm happy to utilize any new ECMAScript feature that may come in handy.

A: recursion is your friend here

const earthData2022 = {
  distanceFromSun: 149280000,
  continents: {
    asia: {
      area: 44579000,
      population: 4560667108,
      countries: { japan: { temperature: 62.5 } },
    },
    africa: { area: 30370000, population: 1275920972 },
    europe: { area: 10180000, population: 746419440 },
    america: { area: 42549000, population: 964920000 },
    australia: { area: 7690000, population: 25925600 },
    antarctica: { area: 14200000, population: 5000 },
  },
};

const earthData2050 = {
  distanceFromSun: 149280000,
  continents: {
    asia: {
      area: 44579000,
      population: 4560767108,
      countries: { japan: { temperature: 73.6 } },
    },
    africa: { area: 30370000, population: 1275960972 },
    europe: { area: 10180000, population: 746419540 },
    america: { area: 42549000, population: 964910000 },
    australia: { area: 7690000, population: 25928600 },
    antarctica: { area: 14200000, population: 5013 },
  },
};

function mySub(x, y) {
  const result = {}
  Object.keys(x).forEach((key) => {
    if (typeof x[key] === 'number') {
      result[key] = x[key] - y[key]
    } else {
      result[key] = mySub(x[key], y[key])
    }
  });
  return result;
}

console.log(mySub(earthData2050, earthData2022));

A: Declarative/functional solution:
const difference = (obj1, obj2) => Object.entries(obj1).reduce((t, [key, value]) => {
    const obj2Value = obj2[key];
    return {
        ...t,
        [key]: typeof value === "object" ?
            difference(value, obj2Value) :
            value - obj2Value
    };
}, {});

Explaination
Object.entries converts the object to a two-dimensional array of key value pairs. Using array.reduce to iterate over the pairs, it can reduce the array to an object. An analogy of this would be when you're reducing a broth to a sauce while cooking. If the value of the property is an object, the resulting property should be the difference of the difference of the sub-object (recursion). If not, it has to be a number and can therefore be subtracted.
Further reading:

*

*Array.prototype.reduce

*Recursion (function calling itself)

*Object.entries

A: @Scott's answer is remarkably efficient and elegant. In his post he comments -

This only works if your note is correct, that the two objects have identical structures and that leaf nodes are all numbers. We'd have to get more sophisticated if we wanted to handle other cases.

I wanted to share what that would look like. Here we write objDiff as a specialization of zipMap -
const objDiff = zipMap((p, q) =>
  is(p, Number) && is(q, Number)
    ? p - q
    : { error: "cannot compute", left: p, right: q }
)

Where is and zipMap is defined as -
const is = (t, T) => t?.constructor === T

const zipMap = f => (p, q) =>
// Object
  is(p, Object) && is(q, Object)
    ? unique(Object.keys(p), Object.keys(q))
        .reduce((r, k) => Object.assign(r, ({ [k]: zipMap(f)(p[k], q[k]) })), {})
// Array
: is(p, Array) && is(q, Array)
    ? unique(p.keys(), q.keys())
        .map(k => zipMap(f)(p[k], q[k]))
// Else
: f(p, q)

Which depends on unique -
const unique = (p, q) =>
  Array.from(new Set([...p, ...q]))

To demo this, I added a sampleArray property to each object and a hello: "world" key pair to one. Run the code below to objDiff now works on asymmetric inputs and mixed values types -

const is = (t, T) => t?.constructor === T

const unique = (p, q) =>
  Array.from(new Set([...p, ...q]))

const zipMap = f => (p, q) =>
// Object
  is(p, Object) && is(q, Object)
    ? unique(Object.keys(p), Object.keys(q))
        .reduce((r, k) => Object.assign(r, ({ [k]: zipMap(f)(p[k], q[k]) })), {})
// Array
: is(p, Array) && is(q, Array)
    ? unique(p.keys(), q.keys())
        .map(k => zipMap(f)(p[k], q[k]))
// Else
: f(p, q)

const objDiff = zipMap((p, q) =>
  is(p, Number) && is(q, Number)
    ? p - q
    : { error: "cannot compute", left: p, right: q }
)

const earthData2022 = {sampleArray: [10, 20, 30], distanceFromSun: 14928e4, continents: {asia: {area: 44579e3, population: 4560667108, countries: {japan: {temperature: 62.5}}}, africa: {area: 3037e4, population: 1275920972}, europe: {area: 1018e4, population: 746419440}, america: {area: 42549e3, population: 96492e4}, australia: {area: 769e4, population: 25925600}, antarctica: {area: 142e5, population: 5e3}}}
const earthData2050 = {sampleArray: [9, 40, 30, 100], distanceFromSun: 14928e4, continents: {asia: {area: 44579e3, population: 4560767108, countries: {japan: {temperature: 73.6}}}, africa: {area: 3037e4, population: 1275960972}, europe: {area: 1018e4, population: 746419540}, america: {area: 42549e3, population: 96491e4}, australia: {area: 769e4, population: 25928600}, antarctica: {area: 142e5, population: 5013, hello: "world"}}}

console.log(objDiff(earthData2050, earthData2022))
.as-console-wrapper {max-height: 100% !important; top: 0}

{
  "sampleArray": [
    -1,
    20,
    0,
    {
      "error": "cannot compute",
      "left": 100,
      "right": undefined
    }
  ],
  "distanceFromSun": 0,
  "continents": {
    "asia": {
      "area": 0,
      "population": 100000,
      "countries": {
        "japan": {
          "temperature": 11.099999999999994
        }
      }
    },
    "africa": {
      "area": 0,
      "population": 40000
    },
    "europe": {
      "area": 0,
      "population": 100
    },
    "america": {
      "area": 0,
      "population": -10000
    },
    "australia": {
      "area": 0,
      "population": 3000
    },
    "antarctica": {
      "area": 0,
      "population": 13,
      "hello": {
        "error": "cannot compute",
        "left": "world",
        "right": undefined
      }
    }
  }
}

A: Here's a pretty simple recursive approach:

const objDiff = (x, y) =>
  Object .fromEntries (Object .entries (x) .map (
    ([k, v]) => [k, Object (v) === v ? objDiff (v, y [k]) : v - y [k]]
  ))

const earthData2022 = {distanceFromSun: 14928e4, continents: {asia: {area: 44579e3, population: 4560667108, countries: {japan: {temperature: 62.5}}}, africa: {area: 3037e4, population: 1275920972}, europe: {area: 1018e4, population: 746419440}, america: {area: 42549e3, population: 96492e4}, australia: {area: 769e4, population: 25925600}, antarctica: {area: 142e5, population: 5e3}}}
const earthData2050 = {distanceFromSun: 14928e4, continents: {asia: {area: 44579e3, population: 4560767108, countries: {japan: {temperature: 73.6}}}, africa: {area: 3037e4, population: 1275960972}, europe: {area: 1018e4, population: 746419540}, america: {area: 42549e3, population: 96491e4}, australia: {area: 769e4, population: 25928600}, antarctica: {area: 142e5, population: 5013}}}

console .log (objDiff (earthData2050, earthData2022))
.as-console-wrapper {max-height: 100% !important; top: 0}

We take the entries in your first object and map them to new entries with the same key and a value which is either the result of a recursive call or the subtraction, based on whether the first value is an object or a number.  Then we use Object .fromEntries to rebuild a new object.
This only works if your note is correct, that the two objects have identical structures and that leaf nodes are all numbers.  We'd have to get more sophisticated if we wanted to handle other cases.


text:
Q: Annotation Validation Ok, first I can valid the user if I am using @Valid and the incoming is User instance instead of json string. That works fine e.g:
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
    userRep.save(user);
    return "redirect:/";
}

So the question is how can I create some kind of API and the incoming is Json string, and validate the annotation automatically, for example, @Email, @NotEmpty? What is the best practice?
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json) {
  User user = User.fromJsonToUser(json);
  return new ResponseEntity<String>(user.toJson(),header,HttpStatus.CREATED);
}

User.class
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotEmpty
    @Length(max = 30)
    private String firstName;

    @Email
    @NotEmpty
    @Length(min = 3 , max = 50)
    private String primaryEmail;

}

A: Simply let Spring parse the String to a User and annotate it with the same @Valid annotation:
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody @Valid User user) {
    return new ResponseEntity<String>(user.toJson(), header, HttpStatus.CREATED);
}

or even
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<User> createFromJson(@RequestBody @Valid User user) {
    return new ResponseEntity<User>(user, header, HttpStatus.CREATED);
}


text:
Q: While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1788 I came across few similar articles but it didn't help to fix the problem.
This is the code snippet i am using:
private void GetUsersFromGroup(
        PrincipalContext principalContext,
        string groupName,
        bool isAdminGroup,
        IList<User> users,
        HashSet<string> userIds)
    {
        log.Info($"Attempting to find {groupName} group");
        GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, groupName);
        log.Info($"Successfully found {groupName} group");

        log.Info($"Attempting to read users from group {group.DistinguishedName}");
        var addedUserIds = new List<string>();
        foreach (var userPrincipal in group.Members.OfType<UserPrincipal>())
        {
            if ((userPrincipal.Enabled ?? false) && !userIds.Contains(userPrincipal.UserPrincipalName))
            {
                users.Add(new User(userPrincipal.UserPrincipalName, userPrincipal.Sid.Value, userPrincipal.DisplayName, userPrincipal.EmailAddress, isAdminGroup));
                userIds.Add(userPrincipal.UserPrincipalName.ToLower());
                addedUserIds.Add(userPrincipal.UserPrincipalName);
            }
        }
        log.Info($"Successfully read users from group {group.DistinguishedName}. Users read: {string.Join(", ", addedUserIds)}");
}

Error details

System.DirectoryServices.AccountManagement.PrincipalOperationException: While trying to resolve a cross-store reference, the SID of the target principal could not be resolved.  The error code is 1788.
     at System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o)
     at System.DirectoryServices.AccountManagement.ADUtils.DirectoryEntryAsPrincipal(DirectoryEntry de, ADStoreCtx storeCtx)
     at System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.get_CurrentAsPrincipal()
     at System.DirectoryServices.AccountManagement.PrincipalCollectionEnumerator.MoveNext()
     at System.Linq.Enumerable.d__95`1.MoveNext()

Please advise.
Thank you.

A: It's likely that the group contains an account from another domain that doesn't exist anymore.
When a group contains a user from an external trusted domain (not in the same AD forest) it stores a "foreign security principal" object, which contains the SID of the object. The domain that the account is on really has no idea that the account is added to a group on another domain. So if that account is deleted, the group is not automatically updated.
When you look at the Members collection, it tries to look up the account and give you a UserPrincipal object, but it cannot because the account doesn't exist anymore.


text:
Q: Xml based bean creation possible wiht RoboGuice? I want to define beans into xml file and want to inject it using RoboGuice in android app, is it possible with RoboGuice?

A: I believe, the answer is NO.

Though you can inject objects of simple types. A simple example:
Place this in your res/values folder:
<resources>
    <item name="flag" type="bool">false</item>
</resources>

And this in your res/values-land folder:
<resources>
    <item name="flag" type="bool">true</item>
</resources>

In your activity:
@InjectResource(R.bool.flag) private Boolean flag;

Now you can use flag to determine whether device is in landscape mode.


text:
Q: Run multiple Python programs on the same server (Ubuntu Server 12.04) I am creating a webservice in Python and I have a question. I want to separate the user login user data. For this I am creating two different Python programs.
For example:
login.py -> localhost: 8080
userData.py -> localhost: 8081
My question is: how I can run these two programs on the same server? Is there a Python application server that is easy to use?
Thank you very much!

A: If the webserver is embedded in the application, you may want to use some "watchdog" application to start/stop/restart.
Ubuntu uses upstart.
I like to use supervisord for this as well.
If the application supports some webserver integration protocol like FCGI or WSGI (python's standard), you may want to deploy it using a webserver. I've used apache mod_wsgi for a long time, lately I tend to use nginx+uwsgi. Apache is a fine webserver, but nginx+wsgi   scale better.
[update]

Applications use Bottle + PyMongo (MongoDB) What do you recommend to be scalable?

First you should follow the advice on your framework documentation about deployment (bottle is not verbose about this subject, so I understand why you are asking).
B1 comment is right. You definitely want to place the database and application on distinct servers.
For maximum scalability with minimum fuzz you may want to look at some PasS provider like heroku, instructions here. This makes sense specially if you are a developer and not a system administrator.

A: Since you are on Ubuntu, using bash:
./login.py &
./userData.py &

This will run both scripts in the background.
If you want these scripts to keep on running after you close your shell:
at now < ./login.py
at now < ./userData.py

A: Tornado is a very easy to use application server. You can listen on different ports with different request handlers.
It is scalable and can handle thousands of connections. We use it to handle our console server. The simple hello world code really tells you all you need to know. I've added another HttpServer so that the single ioloop is handling requests on two different ports :
import tornado.ioloop
import tornado.web
from tornado.httpserver import HttpServer

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

class OtherHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Goodbye, world")

application1 = tornado.web.Application([
    (r"/", MainHandler),
])
application2 = tornado.web.Application([
    (r"/", OtherHandler),
])

if __name__ == "__main__":
    HttpServer(application1).listen(8080)
    HttpServer(application1).listen(8081)
    tornado.ioloop.IOLoop.instance().start()

http://www.tornadoweb.org/


text:
Q: Bittrex INVALID_MARKET_ORDER I am POSTing the following data to Bittrex:
POST /v3/orders HTTP/1.1

Content-Type: application/json
Api-Key: xxxxxxxx
Api-Timestamp: 1609676708784
Api-Content-Hash: xxxxxxxxx
Api-Signature: xxxxxxxx

{
    "direction": "BUY",
    "marketSymbol": "CVC-BTC",
    "quantity": "5000",
    "timeInForce": "GOOD_TIL_CANCELLED",
    "type": "MARKET"
}

The data is given in a shortened way for convenience.
Bittrex responds with :
{"code":"INVALID_MARKET_ORDER"}
I am following the API documentation at https://bittrex.github.io/api/v3#/definitions/NewOrder
Question: What is wrong in the order POSTed to Bittrex?

A: Okay, I found the solution.
Instead of GOOD_TIL_CANCELLED, use IMMEDIATE_OR_CANCEL, and it will work.
The documentation on https://bittrex.github.io/api/v3#/definitions/NewOrder does not mention this. The documentation at Bittrex should be updated to indicated that the field timeInForce is different for market or limit orders.


text: Q: Which is the correct way to insert data from dynamodb to elasticsearch via Logstash or lambda? I want to insert data from multiple tables as a single document in AWS Dynamodb to Elasticsearch. Currently, I have set a trigger on one of my tables in Dynamodb and called a Lambda function which inserts the document in Elasticsearch. But recently I read this article and got a bit confused to understand that which is the correct approach, using Logstash or Lambda function?


text:
Q: Hadoop Distributed Cache - modify file I have a file in the distributed cache. The driver class, based on the output of a job, updates this file and starts a new job.  The new job need these updates.
The way I currently do it is to replace the old Distributed Cache file with a new one (the updated one).
Is there a way of broadcasting the diffs (between the old file and the new one) to all the tasks trackers which need the file ?
Or is it the case that, after a job (the first one, in my case) is finished, all the directories/files specific to that job are deleted and consequently it doesn't even make sense to think in this direction ?

A: I think that distributed cache is not build with such scenario in mind. It simply put files locally.
In Your case I would suggest to put file in HDFS and make all interested parties to take it from there
As an optimization you can give this file high replication factor and it will be local to most of the tasks.


text:
Q: Python format function I have a value formatter
def formatter(value):
    return '{:.8f}'.format(value)

but instead of always returning to 8 decimal places I want to return to max of 8 decimal places so.
input                 |     desired_output
100                   |          100
100.01                |         100.01
3.1232342341312323434 |       3.12323423

How do I do that?
this is for applying to a large array of numbers. That then gets sucked up into a sql server at the moment the numbers keep overflowing the limits that the dba has set.
thanks

A: You can do it like this:
'{:^<stringwidth>.8f}'.format(value).rstrip('0').rstrip('.')

where stringwidth is the width of your desired output wherein the value should be centered.

A: The first solution doesn't work if the stringwidth is greater than the number of characters that makes your numbers, because it adds spaces around the string and the rstrip doesn't have any effect.
For it to work, first you should round it (and strip, if necessary), and then, as the second step - center it. Thus, we have:
numbers = [100, 100.01, 3.1232342341312323434]

for number in numbers:
    rounded_number = '{:.8f}'.format(i).rstrip('0').rstrip('.')
    centered_number = '{:^14}'.format(rounded_number)  # substitute 14 with the desired width
    print (centered_number)

    # Or, as a one-liner
    # print ('{:^14}'.format('{:.8f}'.format(i).rstrip('0').rstrip('.')))

Output:
     100
    100.01
  3.12323423

A: Answering your question:
Just use float presentation type '{:g}' instead '{:f}' as described in the Format Specification Mini-Language. This discards trailing zeros automatically. Additionally it switches to exponential notation if required.
def formatter(value):
    return "{:^14.8g}".format(value)

l = [100, 100.01, 3.1232342341312323434,
     0.000000000000123, 1234567899.999]

for x in l:
    print(formatter(x))

Output:
     100
    100.01
  3.1232342
   1.23e-13
1.2345679e+09

Some probably useful extension of your formatter function
Changing the formatter function a little to allow you to set precision and width of the printed field when calling it:
def formatter(value, precision, width):
    return "{{:^{}.{}g}}".format(width, precision).format(value)

l = [100, 100.01, 3.1232342341312323434,
     0.000000000000123, 1234567899.999]

for x in l:
    print(formatter(x, 5, 20))

Output:
             100
            100.01
            3.1232
           1.23e-13
          1.2346e+09

I found the nested format() function on this page about Pandas Formatting Snippets


text:
Q: Arch installation gets stuck /dev/vda1 is apparently in use by the system; will not make a filesystem here I am trying to install arch on my virt-manager
I create four partition

and I am trying to format the partition as per arch wiki installation guide
but I am getting this error:

/dev/vda1 is apparently in use by the system; will not make a filesystem here!

spend too much time on surfing no proper solution founded or maybe not understandable for me


text:
Q: Remotely administrate a machine I'm zero-knowledged about Windows administration, so my question is really basic but nonetheless i wasn't able to find any reference.
If I am in a network and I have administrative privileges on the various machine, how can I remotely tweak users account settings? Like, I am Local\Administrator, how can I change Local\JohnDoe's desktop on the machine Pc13 or enable/disable audio and so on? Remote desktop is enabled on Pc13.
Thanks.

A: For the most part you can connect remotely through RDP by typing "MSTSC" in the run/search line of Windows.  You'll just insert the name/ip of the box you're trying to connect to and then you'll have a remote session you can manage.
Couple of things to note:

*

*On a desktop version of Windows, you can only connect to one session at a time using RDP.  For example, if Local\JohnDoe is logged in and you log in as Local\Administrator, JohnDoe will be logged off.

*In some cases, you may be better off managing the desktop by performing the following: Right Click on My Computer, choose "Manage."  Right click on "Computer Management" and choose, "Connect to another computer".  Type in the name of the computer to be managed.

*Be aware of Windows firewall.  It could prohibit some remote administration if it isn't configured.

Good luck!

A: If you are talking about Windows XP or newer machines, I would definitely use the Computer management tool.  You can do this remotely as well.  On your machine, go to Start - Run, then type compmgmt.msc in the run box.  This will bring up the console for your local PC.  To switch to another, go to Action, then connect to another computer.
Under the system tools tree on the left, you can manage local users and groups, local disks and many other things.  To disable sound for instance, you can disable the Windows Audio service, under Services & applications, Services.


text:
Q: How does python return list from functions? List passed is immutable? def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
    i = j - 1
    while (i >= 0) and (A[i] > key):
        A[i+1] = A[i]
        i = i-1
    A[i+1] = key

    return A

print insertion_sort([8, 1, 3, 4, 9, 5, 2])

Now this prints: [8, 1, 3, 4, 9, 5, 2]
But I assume, I am mutating the list A, then why is the return value the same?

A: Your code is wrong with current indentation. It should be like this, right?
def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        while (i >= 0) and (A[i] > key):
            A[i+1] = A[i]
            i = i-1
        A[i+1] = key

    return A

A: As already mentioned, the indentation is incorrect.
And lists are mutable!


text:
Q: Tornado with_timeout correct usage I've got a web-server that runs some shell command. The command usually takes a couple of seconds, but in some occasions it takes more and in that case the client (it is not a web-browser or curl) disconnects.
I have no possibility to fix the client, so I thought about fixing the server. It is based on tornado framework. I rewrote it using tornado.gen.with_timeout function, but for some reason it doesn't work as I expect. I set timeout to 5 seconds, so when querying the server I expect to get either "finished in X seconds" (where X < 5) or "already took more than 5 seconds... still running". And in both cases I expect to get response in less than 5 seconds.
Here is the code:
import os
import json
import datetime
import random

from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application
from tornado.gen import coroutine, with_timeout, TimeoutError, Return

@coroutine
def run_slow_command(command):
    res = os.system(command)
    raise Return(res)

class MainHandler(RequestHandler):
    @coroutine
    def get(self):
        TIMEOUT = 5
        duration = random.randint(1, 15)

        try:
            yield with_timeout(datetime.timedelta(seconds=TIMEOUT), run_slow_command('sleep %d' % duration))
            response = {'status' : 'finished in %d seconds' % duration}
        except TimeoutError:
            response = {'status' :  'already took more than %d seconds... still running' % TIMEOUT}

        self.set_header("Content-type", "application/json")
        self.write(json.dumps(response) + '\n')

def make_app():
    return Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8080)
    IOLoop.current().start()

And here is the  output from curl:
for i in `seq 1 5`; do curl http://127.0.0.1:8080/; done
{"status": "finished in 15 seconds"}
{"status": "finished in 12 seconds"}
{"status": "finished in 3 seconds"}
{"status": "finished in 11 seconds"}
{"status": "finished in 13 seconds"}

What am I doing wrong?

A: Although run_slow_command is decorated with coroutine it's still blocking, so Tornado is blocked and cannot run any code, including a timer, until the os.system call completes. You should defer the call to a thread:
from concurrent.futures import ThreadPoolExecutor

thread_pool = ThreadPoolExecutor(4)

@coroutine
def run_slow_command(command):
    res = yield thread_pool.submit(os.system, command)
    raise Return(res)

Or, since you just want the Future that's returned by submit, don't use coroutine at all:
def run_slow_command(command):
    return thread_pool.submit(os.system, command)

Instead of using os.system, however, you should use Tornado's own Subprocess support. Putting it all together, this example waits 5 seconds for a subprocess, then times out:
from datetime import timedelta
from functools import partial

from tornado import gen
from tornado.ioloop import IOLoop
from tornado.process import Subprocess

@gen.coroutine
def run_slow_command(command):
    yield gen.with_timeout(
        timedelta(seconds=5),
        Subprocess(args=command.split()).wait_for_exit())

IOLoop.current().run_sync(partial(run_slow_command, 'sleep 10'))


text:
Q: Cannot run sh file while extracting hadoop files via cmd I am a starter in hadoop and I'm trying to install hadoop framework on Window 8.1.
After certain hit and trail method i was able to extract hadoop files from .tar file and using maven for building up the framework.
While it was in progress, a error occurred stating that cannot run sh file present in such and such directory.
Please see the attached image of the error:

A: sh (which Maven is not able to execute, according to the error) is Linux shell command. You might need to check the documentation how to build Hadoop sources on Windows.


text:
Q: Limit by percent instead of number of rows without subqueries I would like to select the top 1% of rows; however, I cannot use subqueries to do it. I.e., this won't work:
SELECT * FROM mytbl
WHERE var='value'
ORDER BY id,random()
LIMIT(SELECT (COUNT(*) * 0.01)::integer FROM mytbl)

How would I accomplish the same output without using a subquery with limit?

A: You can utilize PERCENT_RANK:
WITH cte(ID, var, pc) AS
(
  SELECT ID, var, PERCENT_RANK() OVER (ORDER BY random()) AS pc
  FROM mytbl
  WHERE var = 'value'
)
SELECT *
FROM cte
WHERE pc <= 0.01
ORDER BY id;

SqlFiddleDemo

A: I solved it with Python using the psycopg2 package:
    cur.execute("SELECT ROUND(COUNT(id)*0.01,0)
                 FROM mytbl")
    nrows = str([int(d[0]) for d in cur.fetchall()][0])
    cur.execute("SELECT *
                 FROM mytbl
                 WHERE var='value'
                 ORDER BY id, random() LIMIT (%s)",nrows)

Perhaps there is a more elegant solution using just SQL, or a more efficient one, but this does exactly what I'm looking for.

A: If I got it right, you need:

*

*Random 1% sample of all rows,

*If some id is within the sample, all rows with the same id must be there too.

The follow sql should do the trick:
with ids as (
    select   id,
             total,
             sum(cnt) over (order by max(rnd)) running_total
    from     (
               select id,
                      count(*) over (partition by id) cnt,
                      count(*) over () total,
                      row_number() over(order by random()) rnd
               from   mytbl
             ) q
    group by id,
             cnt,
             total
)
select   mytbl.*
from     mytbl,
         ids
where    mytbl.id = ids.id
and      ids.running_total <= ids.total * 0.01
order by mytbl.id;

A: I don't have your data, of course, but I have no trouble using a sub query in the LIMIT clause.
However, the sub query contains only the count(*) part and I then multiply the result by 0.01:
SELECT * FROM mytbl
WHERE var='value'
ORDER BY id,random()
LIMIT(SELECT count(*) FROM mytbl)*0.01;


text:
Q: SQLite sort COLLATE LOCALIZED doesn't work I have an SQLite database created with SQLite Database Browser. Database contains some Turkish specific letters. To sort them alphabetically i tried the following code, but it doesn't work.
I am using SQLiteAssetHelper
What may be wrong?
public Cursor getAuthors() {

    SQLiteDatabase db = getWritableDatabase();
    db.setLocale(new Locale("tr","TR"));

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String[] sqlSelect = { "_id", "name", "surname", "photoName" };
    String sqlTables = "authors";

    qb.setTables(sqlTables);
    Cursor c = qb.query(db, sqlSelect, null, null, null, null,
            "name,surname COLLATE LOCALIZED ASC");

    c.moveToFirst();

    return c;

}

A: "name,surname COLLATE LOCALIZED"

sorts the name column with the default collation and the surname column with the localized collation.
To sort both columns with the localized collation, you have to specify the collation for both:
"name COLLATE LOCALIZED, surname COLLATE LOCALIZED"