text:
Q: simple axi lite slave application I am using Vivado 2015.3 and a Zybo board and I am trying to implement a very simple AXI lite IP which recieves a character from the PS and sends back the same value +1.
I just switched from planahead on which the generated vhdl files for the IP were quite simpler (in my opinion) and now I couldn't find any usefull tutorial for this case.
My question is where inside the 2 generated vhdl files (my_ip_0_v1_0_S00_AXI and my_ip_0_v1_0) should I add the "+1"?
Thanks :)
my_ip_0_v1_0_S00_AXI.vhd :
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity my_ip_0_v1_0_S00_AXI is
generic (
    -- Users to add parameters here

    -- User parameters ends
    -- Do not modify the parameters beyond this line

    -- Width of S_AXI data bus
    C_S_AXI_DATA_WIDTH  : integer   := 32;
    -- Width of S_AXI address bus
    C_S_AXI_ADDR_WIDTH  : integer   := 4
);
port (
    -- Users to add ports here

    -- User ports ends
    -- Do not modify the ports beyond this line

    -- Global Clock Signal
    S_AXI_ACLK  : in std_logic;
    -- Global Reset Signal. This Signal is Active LOW
    S_AXI_ARESETN   : in std_logic;
    -- Write address (issued by master, acceped by Slave)
    S_AXI_AWADDR    : in std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0);
    -- Write channel Protection type. This signal indicates the
        -- privilege and security level of the transaction, and whether
        -- the transaction is a data access or an instruction access.
    S_AXI_AWPROT    : in std_logic_vector(2 downto 0);
    -- Write address valid. This signal indicates that the master signaling
        -- valid write address and control information.
    S_AXI_AWVALID   : in std_logic;
    -- Write address ready. This signal indicates that the slave is ready
        -- to accept an address and associated control signals.
    S_AXI_AWREADY   : out std_logic;
    -- Write data (issued by master, acceped by Slave)
    S_AXI_WDATA : in std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
    -- Write strobes. This signal indicates which byte lanes hold
        -- valid data. There is one write strobe bit for each eight
        -- bits of the write data bus.
    S_AXI_WSTRB : in std_logic_vector((C_S_AXI_DATA_WIDTH/8)-1 downto 0);
    -- Write valid. This signal indicates that valid write
        -- data and strobes are available.
    S_AXI_WVALID    : in std_logic;
    -- Write ready. This signal indicates that the slave
        -- can accept the write data.
    S_AXI_WREADY    : out std_logic;
    -- Write response. This signal indicates the status
        -- of the write transaction.
    S_AXI_BRESP : out std_logic_vector(1 downto 0);
    -- Write response valid. This signal indicates that the channel
        -- is signaling a valid write response.
    S_AXI_BVALID    : out std_logic;
    -- Response ready. This signal indicates that the master
        -- can accept a write response.
    S_AXI_BREADY    : in std_logic;
    -- Read address (issued by master, acceped by Slave)
    S_AXI_ARADDR    : in std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0);
    -- Protection type. This signal indicates the privilege
        -- and security level of the transaction, and whether the
        -- transaction is a data access or an instruction access.
    S_AXI_ARPROT    : in std_logic_vector(2 downto 0);
    -- Read address valid. This signal indicates that the channel
        -- is signaling valid read address and control information.
    S_AXI_ARVALID   : in std_logic;
    -- Read address ready. This signal indicates that the slave is
        -- ready to accept an address and associated control signals.
    S_AXI_ARREADY   : out std_logic;
    -- Read data (issued by slave)
    S_AXI_RDATA : out std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
    -- Read response. This signal indicates the status of the
        -- read transfer.
    S_AXI_RRESP : out std_logic_vector(1 downto 0);
    -- Read valid. This signal indicates that the channel is
        -- signaling the required read data.
    S_AXI_RVALID    : out std_logic;
    -- Read ready. This signal indicates that the master can
        -- accept the read data and response information.
    S_AXI_RREADY    : in std_logic
);
end my_ip_0_v1_0_S00_AXI;

architecture arch_imp of my_ip_0_v1_0_S00_AXI is

-- AXI4LITE signals
signal axi_awaddr   : std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0);
signal axi_awready  : std_logic;
signal axi_wready   : std_logic;
signal axi_bresp    : std_logic_vector(1 downto 0);
signal axi_bvalid   : std_logic;
signal axi_araddr   : std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0);
signal axi_arready  : std_logic;
signal axi_rdata    : std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
signal axi_rresp    : std_logic_vector(1 downto 0);
signal axi_rvalid   : std_logic;

-- Example-specific design signals
-- local parameter for addressing 32 bit / 64 bit C_S_AXI_DATA_WIDTH
-- ADDR_LSB is used for addressing 32/64 bit registers/memories
-- ADDR_LSB = 2 for 32 bits (n downto 2)
-- ADDR_LSB = 3 for 64 bits (n downto 3)
constant ADDR_LSB  : integer := (C_S_AXI_DATA_WIDTH/32)+ 1;
constant OPT_MEM_ADDR_BITS : integer := 1;
------------------------------------------------
---- Signals for user logic register space example
--------------------------------------------------
---- Number of Slave Registers 4
signal slv_reg0 :std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
signal slv_reg1 :std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
signal slv_reg2 :std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
signal slv_reg3 :std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
signal slv_reg_rden : std_logic;
signal slv_reg_wren : std_logic;
signal reg_data_out :std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
signal byte_index   : integer;

begin
-- I/O Connections assignments

S_AXI_AWREADY   <= axi_awready;
S_AXI_WREADY    <= axi_wready;
S_AXI_BRESP <= axi_bresp;
S_AXI_BVALID    <= axi_bvalid;
S_AXI_ARREADY   <= axi_arready;
S_AXI_RDATA <= axi_rdata;
S_AXI_RRESP <= axi_rresp;
S_AXI_RVALID    <= axi_rvalid;
-- Implement axi_awready generation
-- axi_awready is asserted for one S_AXI_ACLK clock cycle when both
-- S_AXI_AWVALID and S_AXI_WVALID are asserted. axi_awready is
-- de-asserted when reset is low.

process (S_AXI_ACLK)
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      axi_awready <= '0';
    else
      if (axi_awready = '0' and S_AXI_AWVALID = '1' and S_AXI_WVALID = '1')         then
        -- slave is ready to accept write address when
        -- there is a valid write address and write data
        -- on the write address and data bus. This design
        -- expects no outstanding transactions.
        axi_awready <= '1';
      else
        axi_awready <= '0';
      end if;
    end if;
  end if;
end process;

-- Implement axi_awaddr latching
-- This process is used to latch the address when both
-- S_AXI_AWVALID and S_AXI_WVALID are valid.

process (S_AXI_ACLK)
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      axi_awaddr <= (others => '0');
    else
      if (axi_awready = '0' and S_AXI_AWVALID = '1' and S_AXI_WVALID = '1') then
        -- Write Address latching
        axi_awaddr <= S_AXI_AWADDR;
      end if;
    end if;
  end if;
end process;

-- Implement axi_wready generation
-- axi_wready is asserted for one S_AXI_ACLK clock cycle when both
-- S_AXI_AWVALID and S_AXI_WVALID are asserted. axi_wready is
-- de-asserted when reset is low.

process (S_AXI_ACLK)
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      axi_wready <= '0';
    else
      if (axi_wready = '0' and S_AXI_WVALID = '1' and S_AXI_AWVALID = '1') then
          -- slave is ready to accept write data when
          -- there is a valid write address and write data
          -- on the write address and data bus. This design
          -- expects no outstanding transactions.
          axi_wready <= '1';
      else
        axi_wready <= '0';
      end if;
    end if;
  end if;
end process;

-- Implement memory mapped register select and write logic generation
-- The write data is accepted and written to memory mapped registers when
-- axi_awready, S_AXI_WVALID, axi_wready and S_AXI_WVALID are asserted. Write strobes are used to
-- select byte enables of slave registers while writing.
-- These registers are cleared when reset (active low) is applied.
-- Slave register write enable is asserted when valid address and data are available
-- and the slave is ready to accept the write address and write data.
slv_reg_wren <= axi_wready and S_AXI_WVALID and axi_awready and S_AXI_AWVALID ;

process (S_AXI_ACLK)
variable loc_addr :std_logic_vector(OPT_MEM_ADDR_BITS downto 0);
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      slv_reg0 <= (others => '0');
      slv_reg1 <= (others => '0');
      slv_reg2 <= (others => '0');
      slv_reg3 <= (others => '0');
    else
      loc_addr := axi_awaddr(ADDR_LSB + OPT_MEM_ADDR_BITS downto ADDR_LSB);
      if (slv_reg_wren = '1') then
        case loc_addr is
          when b"00" =>
            for byte_index in 0 to (C_S_AXI_DATA_WIDTH/8-1) loop
              if ( S_AXI_WSTRB(byte_index) = '1' ) then
                -- Respective byte enables are asserted as per write strobes
                -- slave registor 0
                slv_reg0(byte_index*8+7 downto byte_index*8) <= S_AXI_WDATA(byte_index*8+7 downto byte_index*8);
              end if;
            end loop;
          when b"01" =>
            for byte_index in 0 to (C_S_AXI_DATA_WIDTH/8-1) loop
              if ( S_AXI_WSTRB(byte_index) = '1' ) then
                -- Respective byte enables are asserted as per write strobes
                -- slave registor 1
                slv_reg1(byte_index*8+7 downto byte_index*8) <= S_AXI_WDATA(byte_index*8+7 downto byte_index*8);
              end if;
            end loop;
          when b"10" =>
            for byte_index in 0 to (C_S_AXI_DATA_WIDTH/8-1) loop
              if ( S_AXI_WSTRB(byte_index) = '1' ) then
                -- Respective byte enables are asserted as per write strobes
                -- slave registor 2
                slv_reg2(byte_index*8+7 downto byte_index*8) <= S_AXI_WDATA(byte_index*8+7 downto byte_index*8);
              end if;
            end loop;
          when b"11" =>
            for byte_index in 0 to (C_S_AXI_DATA_WIDTH/8-1) loop
              if ( S_AXI_WSTRB(byte_index) = '1' ) then
                -- Respective byte enables are asserted as per write strobes
                -- slave registor 3
                slv_reg3(byte_index*8+7 downto byte_index*8) <= S_AXI_WDATA(byte_index*8+7 downto byte_index*8);
              end if;
            end loop;
          when others =>
            slv_reg0 <= slv_reg0;
            slv_reg1 <= slv_reg1;
            slv_reg2 <= slv_reg2;
            slv_reg3 <= slv_reg3;
        end case;
      end if;
    end if;
  end if;
end process;

-- Implement write response logic generation
-- The write response and response valid signals are asserted by the slave
-- when axi_wready, S_AXI_WVALID, axi_wready and S_AXI_WVALID are asserted.
-- This marks the acceptance of address and indicates the status of
-- write transaction.

process (S_AXI_ACLK)
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      axi_bvalid  <= '0';
      axi_bresp   <= "00"; --need to work more on the responses
    else
      if (axi_awready = '1' and S_AXI_AWVALID = '1' and axi_wready = '1' and S_AXI_WVALID = '1' and axi_bvalid = '0'  ) then
        axi_bvalid <= '1';
        axi_bresp  <= "00";
      elsif (S_AXI_BREADY = '1' and axi_bvalid = '1') then   --check if bready is asserted while bvalid is high)
        axi_bvalid <= '0';                                 -- (there is a possibility that bready is always asserted high)
      end if;
    end if;
  end if;
end process;

-- Implement axi_arready generation
-- axi_arready is asserted for one S_AXI_ACLK clock cycle when
-- S_AXI_ARVALID is asserted. axi_awready is
-- de-asserted when reset (active low) is asserted.
-- The read address is also latched when S_AXI_ARVALID is
-- asserted. axi_araddr is reset to zero on reset assertion.

process (S_AXI_ACLK)
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      axi_arready <= '0';
      axi_araddr  <= (others => '1');
    else
      if (axi_arready = '0' and S_AXI_ARVALID = '1') then
        -- indicates that the slave has acceped the valid read address
        axi_arready <= '1';
        -- Read Address latching
        axi_araddr  <= S_AXI_ARADDR;
      else
        axi_arready <= '0';
      end if;
    end if;
  end if;
end process;

-- Implement axi_arvalid generation
-- axi_rvalid is asserted for one S_AXI_ACLK clock cycle when both
-- S_AXI_ARVALID and axi_arready are asserted. The slave registers
-- data are available on the axi_rdata bus at this instance. The
-- assertion of axi_rvalid marks the validity of read data on the
-- bus and axi_rresp indicates the status of read transaction.axi_rvalid
-- is deasserted on reset (active low). axi_rresp and axi_rdata are
-- cleared to zero on reset (active low).
process (S_AXI_ACLK)
begin
  if rising_edge(S_AXI_ACLK) then
    if S_AXI_ARESETN = '0' then
      axi_rvalid <= '0';
      axi_rresp  <= "00";
    else
      if (axi_arready = '1' and S_AXI_ARVALID = '1' and axi_rvalid = '0') then
        -- Valid read data is available at the read data bus
        axi_rvalid <= '1';
        axi_rresp  <= "00"; -- 'OKAY' response
      elsif (axi_rvalid = '1' and S_AXI_RREADY = '1') then
        -- Read data is accepted by the master
        axi_rvalid <= '0';
      end if;
    end if;
  end if;
end process;

-- Implement memory mapped register select and read logic generation
-- Slave register read enable is asserted when valid address is available
-- and the slave is ready to accept the read address.
slv_reg_rden <= axi_arready and S_AXI_ARVALID and (not axi_rvalid) ;

process (slv_reg0, slv_reg1, slv_reg2, slv_reg3, axi_araddr, S_AXI_ARESETN, slv_reg_rden)
variable loc_addr :std_logic_vector(OPT_MEM_ADDR_BITS downto 0);
begin
    -- Address decoding for reading registers
    loc_addr := axi_araddr(ADDR_LSB + OPT_MEM_ADDR_BITS downto ADDR_LSB);
    case loc_addr is
      when b"00" =>
        reg_data_out <= slv_reg0;
      when b"01" =>
        reg_data_out <= slv_reg1;
      when b"10" =>
        reg_data_out <= slv_reg2;
      when b"11" =>
        reg_data_out <= slv_reg3;
      when others =>
        reg_data_out  <= (others => '0');
    end case;
end process;

-- Output register or memory read data
process( S_AXI_ACLK ) is
begin
  if (rising_edge (S_AXI_ACLK)) then
    if ( S_AXI_ARESETN = '0' ) then
      axi_rdata  <= (others => '0');
    else
      if (slv_reg_rden = '1') then
        -- When there is a valid read address (S_AXI_ARVALID) with
        -- acceptance of read address by the slave (axi_arready),
        -- output the read dada
        -- Read address mux
          axi_rdata <= reg_data_out;     -- register read data
      end if;
    end if;
  end if;
end process;

-- Add user logic here

-- User logic ends

end arch_imp;

my_ip_0_v1_0.vhd :
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity my_ip_0_v1_0 is
generic (
    -- Users to add parameters here

    -- User parameters ends
    -- Do not modify the parameters beyond this line

    -- Parameters of Axi Slave Bus Interface S00_AXI
    C_S00_AXI_DATA_WIDTH    : integer   := 32;
    C_S00_AXI_ADDR_WIDTH    : integer   := 4
);
port (
    -- Users to add ports here

    -- User ports ends
    -- Do not modify the ports beyond this line

    -- Ports of Axi Slave Bus Interface S00_AXI
    s00_axi_aclk    : in std_logic;
    s00_axi_aresetn : in std_logic;
    s00_axi_awaddr  : in std_logic_vector(C_S00_AXI_ADDR_WIDTH-1 downto 0);
    s00_axi_awprot  : in std_logic_vector(2 downto 0);
    s00_axi_awvalid : in std_logic;
    s00_axi_awready : out std_logic;
    s00_axi_wdata   : in std_logic_vector(C_S00_AXI_DATA_WIDTH-1 downto 0);
    s00_axi_wstrb   : in std_logic_vector((C_S00_AXI_DATA_WIDTH/8)-1 downto 0);
    s00_axi_wvalid  : in std_logic;
    s00_axi_wready  : out std_logic;
    s00_axi_bresp   : out std_logic_vector(1 downto 0);
    s00_axi_bvalid  : out std_logic;
    s00_axi_bready  : in std_logic;
    s00_axi_araddr  : in std_logic_vector(C_S00_AXI_ADDR_WIDTH-1 downto 0);
    s00_axi_arprot  : in std_logic_vector(2 downto 0);
    s00_axi_arvalid : in std_logic;
    s00_axi_arready : out std_logic;
    s00_axi_rdata   : out std_logic_vector(C_S00_AXI_DATA_WIDTH-1 downto 0);
    s00_axi_rresp   : out std_logic_vector(1 downto 0);
    s00_axi_rvalid  : out std_logic;
    s00_axi_rready  : in std_logic
);
end my_ip_0_v1_0;

architecture arch_imp of my_ip_0_v1_0 is

-- component declaration
component my_ip_0_v1_0_S00_AXI is
    generic (
    C_S_AXI_DATA_WIDTH  : integer   := 32;
    C_S_AXI_ADDR_WIDTH  : integer   := 4
    );
    port (
    S_AXI_ACLK  : in std_logic;
    S_AXI_ARESETN   : in std_logic;
    S_AXI_AWADDR    : in std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0);
    S_AXI_AWPROT    : in std_logic_vector(2 downto 0);
    S_AXI_AWVALID   : in std_logic;
    S_AXI_AWREADY   : out std_logic;
    S_AXI_WDATA : in std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
    S_AXI_WSTRB : in std_logic_vector((C_S_AXI_DATA_WIDTH/8)-1 downto 0);
    S_AXI_WVALID    : in std_logic;
    S_AXI_WREADY    : out std_logic;
    S_AXI_BRESP : out std_logic_vector(1 downto 0);
    S_AXI_BVALID    : out std_logic;
    S_AXI_BREADY    : in std_logic;
    S_AXI_ARADDR    : in std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0);
    S_AXI_ARPROT    : in std_logic_vector(2 downto 0);
    S_AXI_ARVALID   : in std_logic;
    S_AXI_ARREADY   : out std_logic;
    S_AXI_RDATA : out std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0);
    S_AXI_RRESP : out std_logic_vector(1 downto 0);
    S_AXI_RVALID    : out std_logic;
    S_AXI_RREADY    : in std_logic
    );
end component my_ip_0_v1_0_S00_AXI;

begin

-- Instantiation of Axi Bus Interface S00_AXI
my_ip_0_v1_0_S00_AXI_inst : my_ip_0_v1_0_S00_AXI
generic map (
    C_S_AXI_DATA_WIDTH  => C_S00_AXI_DATA_WIDTH,
    C_S_AXI_ADDR_WIDTH  => C_S00_AXI_ADDR_WIDTH
)
port map (
    S_AXI_ACLK  => s00_axi_aclk,
    S_AXI_ARESETN   => s00_axi_aresetn,
    S_AXI_AWADDR    => s00_axi_awaddr,
    S_AXI_AWPROT    => s00_axi_awprot,
    S_AXI_AWVALID   => s00_axi_awvalid,
    S_AXI_AWREADY   => s00_axi_awready,
    S_AXI_WDATA => s00_axi_wdata,
    S_AXI_WSTRB => s00_axi_wstrb,
    S_AXI_WVALID    => s00_axi_wvalid,
    S_AXI_WREADY    => s00_axi_wready,
    S_AXI_BRESP => s00_axi_bresp,
    S_AXI_BVALID    => s00_axi_bvalid,
    S_AXI_BREADY    => s00_axi_bready,
    S_AXI_ARADDR    => s00_axi_araddr,
    S_AXI_ARPROT    => s00_axi_arprot,
    S_AXI_ARVALID   => s00_axi_arvalid,
    S_AXI_ARREADY   => s00_axi_arready,
    S_AXI_RDATA => s00_axi_rdata,
    S_AXI_RRESP => s00_axi_rresp,
    S_AXI_RVALID    => s00_axi_rvalid,
    S_AXI_RREADY    => s00_axi_rready
);

-- Add user logic here

-- User logic ends

end arch_imp;

A: my_ip_0_v1_0.vhd instantiates my_ip_0_v1_0_S00_AXI.vhd so my_ip_0_v1_0.vhd is the top level and you should (as the comments say) put your custom code in my_ip_0_v1_0_S00_AXI.vhd. But things are a bit more complex: in Zynq cores the PS communicates with the PL using the AXI bus protocol. So, if you want to implement your +1 module, the most complex part will be the AXI protocol (5 channels, handshaking...) And the automatically generated wrappers are overcomplicated. You should probably consider having a look at the AXI lite specification and implementing the minimal AXI lite compatible hardware.
Anyway, assuming you want to store your character at address 0 (b"00"), in least significant byte position and you increment upon write, you can add your custom code in the memory mapped register select and write logic generation process:
when b"00" =>
  for byte_index in 0 to (C_S_AXI_DATA_WIDTH/8-1) loop
    if ( S_AXI_WSTRB(byte_index) = '1' ) then
      if byte_index = 0 then
        slv_reg0(7 downto 0) <= std_logic_vector(unsigned(S_AXI_WDATA(7 downto 0)) + 1);
      else
        slv_reg0(byte_index*8+7 downto byte_index*8) <= S_AXI_WDATA(byte_index*8+7 downto byte_index*8);
      end if;
    end if;
  end loop;

Writing any 32 bits value at address 0 of the address space of your peripheral shall store the 24 most significant bits unmodified and the 8 least significant bits incremented (with automatic wrapping around 0xff). Of course, to notice this, you must read back at address 0.


text:
Q: Call javascript function from inserting script tag I have a function that I'm trying to call from a script tag
function foundElement(){
  console.log(' in found element')
}

var ele = document.createElement("script")
ele.textContent = "foundElement()"
document.head.appendChild(ele)

I'm getting an error Uncaught ReferenceError: foundElement is not defined. However, when I use the console the function is defined. Attached is a screenshot.
How can I call foundElement() by inserting a script tag?

A:

function foundElement() {
  console.log(' in found element')
}

var ele = document.createElement("script")
ele.textContent = "foundElement()"
document.head.appendChild(ele)

Works like a charm. Can you describe your actual problem?

A: Content script JS and page JS are running in a different context with different permissions. The only thing they are sharing is DOM. You can found more details here
If you need to share functions between Content-Script and page context - you need to inject function to the page too.
Example:
var fn = function injectedFunction(seed) { console.log(seed,Math.random());}
var ele = document.createElement("script");
ele.textContent = fn+"console.log(injectedFunction(document.location));";
document.body.appendChild(ele);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert records in SQL DB using R I have a text file. It contains simple text.
FileName - 234567.txt

I have build the corpus of the content present in this file.I cleaned the corpus and created string vector to store complete text in a single String vector as
FullTextstring <- "Complete text here"

I have also saved File name in a vector as
FileName <- "234567.txt"

I have a table "TextData "in database. Following are the table fields :-
FileId int primary key , where FileID is the FileName
FileContent nvarchar(Max), where FileContent is text presnt in file

I want to insert file name and its content in a database. So , my query is how do I insert value present in "FileName" and "FullTextstring" vectors into my table "TextData".
I am using windows 8.1. I have installed package "RODBC" . I have also looked various examples but could not find anything useful.

A: I have also found some of the RODBC documentation unhelpful if you are new to R or databases or both. Hopefully this can get you started.
As the comment above suggests, the first thing you need to do is establish an ODBC connection to your database. Since you did not specify, I'll assume you are using some version of MS-SQL Server. Instructions for making a connection to MS-SQL server are available here.
Once you have established a connection on your machine (let's call it textSQL), you are going to want to assign that connection to an object in R. Here, I call the connection con.
require(RODBC)
con <- odbcConnect("textSQL")

If you truly want to insert each value into your TextData from vectors (it seems like combining everything to a dataframe and then updating the db via sqlSave() would be be preferred), then you'll just need to run the SQL to do that. Before you can do that, however, you are going to need to convert your FileName vector into something that can be received by your integer database field. Assuming that all your filesnames all have a three character suffix (plus a period) something like the following should probably work.
# as stated in your question
FileName <- "234567.txt"
FullTextstring <- "Complete text here"

# convert FileName to int
require(stringr)
#filename length
l <- nchar(FileName)
#filename suffix
s <- 4
FileName <- as.numeric(str_sub(FileName,1,l-s))

Now that you have your filename stored as a numeric in R, we can move to populating your table on the database server. For this, we can simply make use of the sqlQuery() function in conjunction with the paste() function as shown below. Note that the first parameter of the function is the connection object (con) specified above.
sqlQuery(con
         ,paste("insert into TextData values ("
                 ,FileName[1]
                 ,",\'"
                 ,FullTextstring[1]
                 ,"\')"))

If you have multiple filenames and strings in a given vector, just update the [1] accordingly.
Also, please be advised that there is an upper limit on field lengths built into RODBC (I think it is at 64k as mentioned here). If you are dealing with a large corpus of text, it's a good bet that you'll run up against this limit. If this happens, you can modify the source code (it's just one line) and recompile from source.
Update per request in comment
In order to make this change, you are going to need to first download the tar ball from CRAN here.
Next, you are going to need to navigate to the C code located in the \RODBC\src directory.
Around line 735 or so, you are going to see a comment and line of code that looks something like this:
    /* sanity check as the reports are sometimes unreliable */
    if (datalen > 65535) datalen = 65535;

You are going to want to change it to something like this (the new value may be bigger or smaller depending on your needs):
    /* sanity check as the reports are sometimes unreliable */
    if (datalen > 10000000) datalen = 10000000;

Save your changes, and then re-install your modified RODBC package using the instructions provided here.
NOTE: This solution worked for me when I was trying to bring information into R from an RODBC connection. I am a novice C programmer at best and do not completely understand all of Ripley's code. This solution will not break RODBC but it may not allow you to pipe extremely large fields from R into your database. The truncation you are experiencing may be a problem with some of your SQL server settings as opposed to the datalen cap in RODBC.


text:
Q: Gitbash Error - rbenv: cannot find readlink - are you missing GNU coreutils? Hello when i open git hub i get an error right at the top.
It literally looks like this:
rbenv: cannot find readlink - are you missing GNU coreutils?
rbenv: cannot find readlink - are you missing GNU coreutils?

Joey@JOEY-PC /c/Sites (master)

$
Everything was working great before i installed rubyinstall 1.9.3.
Then my local server wasn't working when i tried to run a new website im making.
So i reverted back to ruby 2.1.5p273 by running rubyinstaller 2.1.5
Anyone know what the problem is?
Here is what my server looks like when once the above error started to appear on gitbash
http://i57.tinypic.com/b5p7nm.jpg

A: It is coming from here: https://github.com/sstephenson/rbenv/blob/master/libexec/rbenv.  Look in your ~/.rbenv installation, specifically ~/.rbenv/libexec/rbenv.
It happened to me because my Git for Windows installation lacks the readlink command.
Try commenting out the READLINK section and replace resolve_link with this:
resolve_link() { sed -n -e 's/\x00//g'  -e 's/\!<symlink>..//p' $1; }

I still not sure this really works, though.


text:
Q: Will I always get the keys in the same order when I call ConfigurationManager.AppSettings.AllKeys For web.config and app.config, when I call ConfigurationManager.AppSettings.AllKeys, do I get the keys in the same order they appear in the config file all the time?
I couldn't find any mention of that on MSDN.

A: ConfigurationManager.AppSettings is of type NameValueCollection and their order is undetermined. AllKeys returns string array based on the NameValueCollection, thus its order will also be undetermined.
See: NameValueCollection

Collections of this type do not preserve the ordering of element, and
  no particular ordering is guaranteed when enumerating the collection.

If you want a definite order the use
ConfigurationManager.AppSettings.AllKeys.OrderBy(r=> r)

A: Why would it matter? It's a keyed collection: if order is important to you, put it in the order you want it. You should also bear in mind that the data in <appsettings> comes from multiple sources. It is retrieved from some subset of

*

*machine configuration (machine.config)

*application configuration (app.config)

*user-specific configuration

*IIS application host configuration

*root web.config

*any of a number of web.config files in the application path in IIS.

Further, ConfigurationManager.AppSettings is a NameValueCollection. I suspect—but don't know for sure—that its backing store is a hash table. In so, the ordering you'll see is related to

*

*the computed hash value of the keys,

*the hash bucket to which those keys are assigned, and

*insertion order (actually, order of operations — insertion and deletion, since deletion might leave an empty slot in the hash bucket that gets filled by a subsequent insertion).

The same set of keys, inserted in different sequences, would display different orderings on retrieval.


text:
Q: How can i convert 1415071800000 to utc time in jquery or javascript? I am working with full calendar and giving JSON data to calendar. It displays right time on my local system but when I see it online it shows me wrong time. I want to add events by converting the time into UTC time but by using following code I get the UtCTime = NaN. Can anyone please explain how can I convert it.
v.appoint_starttime.match=/Date(1415071800000)/ ;
var newLocalStartDate = new Date(v.appoint_starttime.match(/\d+/)[0] * 1);
var UtCTime = Date.UTC(newLocalStartDate);

A: Try this :
You should have variable v defined already, then remove .match from v.appoint_starttime.match and put double quotes around date value.
v.appoint_starttime="/Date(1415071800000)/" ;
var newLocalStartDate = new Date(v.appoint_starttime.match(/\d+/)[0] * 1);
var UtCTime = Date.UTC(newLocalStartDate);

DEMO

A: You can parse your date.
var newLocalStartDate = new Date(parseInt(v.appoint_starttime.substr(6)));

substr function takes the length as 6 ie it ignores the initial 6 characters which include /Date(
The parseInt () function will parse the date string -> v.appoint_starttime.


text:
Q: Switching from SMTP to OAuth2 This isn't a code specific question, but more of a general question regarding OAuth2.  I maintain a system that for the past 20+ years has been able to easily connect to any SMTP enabled email server, then send an email (only requiring authentication info and a server path).  This email account is always system related, and isn't specific to one user, such as support@.
With GMail and Office365 (and other major email providers) dropping support for SMTP direct sends, I have been learning OAuth2.  With all the reading I've done, OAuth2 is very email server specific (or so it seems).  But from a systems standpoint, I need to be able to send support email regardless of whom is logged into the system, and regardless of what email host, with no authentication popups.
Is a single solution even possible with OAuth2?  Will I need to code for every email provider differently? (GMail, Office365, etc)  (I can currently get an authorization token from Office 365, but it seems very specific to Office 365)  I have yet to figure out how to actually send an email through Office365 with my OAuth2 token, since MailKit doesn't seem to support OAuth.  Is there a single protocol that will allow me to send an OAuth2 token through any email host?
I understand how SMTP direct send has been abused for a long time, but replacing it sucks.


text:
Q: split time series dataframe when value change I'have a Dataframe, that correspond to lat/long of an object in movement.
This object go from one place to another, and I created a column that reference what place he is at every second.
I want to split that dataframe, so when the object go in one place, the leave to another, I'll have two separate dataframe.
'None' mean he is between places
My actual code :
    def cut_df2(df):
        df_copy = df.copy()
#check if change of place
        df_copy['changed'] = df_copy['place'].ne(df_copy['place'].shift().bfill()).astype(int)
        last = 0
        dfs= []
        for num, line in df_copy.iterrows():
            if line.changed:
                dfs.append(df.iloc[last:num,:])
                last = num
        # Check if last line was in a place
        if line.place != 'None':
            dfs.append(df.iloc[last:,:])
            df_outs= []
        # Delete empty dataframes
        for num, dataframe in enumerate(dfs):
            if not dataframe.empty :
                if dataframe.reset_index().place.iloc[0] != 'None':
                    df_outs.append(dataframe)
        return df_outs

It won't work on big dataset, but work on simple examples and I've no idea why, anyone can help me?

A: Try using this instead:
https://www.geeksforgeeks.org/split-pandas-dataframe-by-rows/
iloc can be a good way to split a dataframe
df1 = datasX.iloc[:, :72]
df2 = datasX.iloc[:, 72:]


text:
Q: AttributeError: module 'pysal' has no attribute 'pdio' I'm currently learning how to use PySAL (http://darribas.org/gds_scipy16/ipynb_md/01_data_processing.html) and I've come across some problems when trying to use PySAL functions.
After succesfully loading pysal as ps, I'm trying to use ps.pdio, but when I run
`
ps.pdio.read_files(shp_path)

`
I get:
AttributeError: module 'pysal' has no attribute 'pdio'
I'm using running Python 3.7.15 in Colab and the packages are pysal 2.6.0 and pandas 1.3.5.
Any idea of what is going on?


text:
Q: Php add the coma with duople quetes in json string I tried this code
foreach($comment as $cmd)
    {
        $dids=$cmd['qid'];
        $json = json_encode($dids);
    }   echo($json);

my output like this
"1""2"

how to add the comma between these string
I want my output "1","2"
please help me

A: This should do the trick:
<?php
    $dids = array();
    foreach($comment as $cmd) {
        $dids[]=$cmd['qid'];
    }
    $json = json_encode($dids);
    echo($json);
?>

A: You need to append comma manually
foreach($comment as $cmd) {
    $dids=$cmd['qid'];
    $json = json_encode($dids) . ",";
}

Thanks
Amit

A: use this code instead:
    foreach($comment as $cmd){
    $dids=$cmd['qid'];
    $json = json_encode($dids).",";
}echo substr($json,0,strlen($json)-1);

A: Here it works
  foreach($comment as $cmd) {
        $dids=$cmd['qid'];
        $dids=$dids.",";
        $json = json_encode($dids);
    }


text:
Q: IE9 bug with Html.DropDownListFor Hello I need some help with a bug in Internet Explorer 9. I am currently developing some CRUD screens in ASP.NET 4 MVC 3 Razor. In a multiple screen I use the @Html.DropDowListFor to create easy links for Foreign keys.
But when I few these in IE9 (and only IE9) the DropDownList will be rendered smaller than its usual size, the text will be displayed a few pixels lower than normal, and the if the word that is displayed is larger than a small amount of characters(not sure what number, I think it's about 10) it will not be fully rendered. The weird part is that when I click on the DropDownList it will fix itself.
The View code:
@Html.DropDownListFor(model => model.Asset.FkAssetTypeId, new SelectList(Model.AssetTypes, "AssetTypeId", "Name"))
@Html.ValidationMessageFor(model => model.Asset.FkAssetTypeId)

The Model code:
[Display(ResourceType = typeof(I18N_Asset), Name = "Label_Asset_FkAssetTypeId")]
public int FkAssetTypeId { get; set; }

Anybody have any experience with this issue, and know a way to fix this? thank you for the help.

A: I have found what the problem was, I was using JQuery tabs on the same page. This caused the frontsize of the dropdownlistfor-s to not scale to the css that is set for the whole site. but instead renders the dropdownboxfor with the frontsize of the JQuery tabs and than sets the frontsize to the css.
I have solved this issue by using Javascript to set the font-size in a Document.ready function:
// IE9 causes a bug where the dropdownlists will not be displayed correctly because they won't adapt to their current font-size
// this javascript fixes that by resetting the font-size
if (window.navigator.systemLanguage && (!document.documentMode || document.documentMode === 9)) { //check if IE9 is being used
    var list = document.getElementsByTagName('Select'); // get all dropdownlists
    for (i = 0; i < list.length; i++) {
        list[i].style.fontSize = list[i].style.fontSize; // reset the font-size
    }
}


text:
Q: Tape is required when a tensor loss is passed I have the following loss:
loss = loss(y_train_left_noc[:,:,0], soft_argmin).tolist()

where type(loss) is <class 'float'>
However, upon using this loss in the optimizer like so:
train = tf.keras.optimizers.Adam().minimize(loss, [k1, k2, k3])

where k1, k2 and k3 are convolution kernels, I get the following error:
Traceback (most recent call last):
  File "train.py", line 277, in <module>
    k3
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py", line 385, in minimize
    loss, var_list=var_list, grad_loss=grad_loss, tape=tape)
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py", line 440, in _compute_gradients
    raise ValueError("`tape` is required when a `Tensor` loss is passed.")
ValueError: `tape` is required when a `Tensor` loss is passed.

If the loss is of type float, then why does Tensorflow say that a Tensor loss is passed?

A: Answering the solution from here by @nikitamaia, for the benefit of the community.
The error message you're seeing is here in the source code:
if not callable(loss) and tape is None:
    raise ValueError("`tape` is required when a `Tensor` loss is passed.")

This error message seems only to be in tf-nightly, and if you run the code in TF 2.3 you'll notice a slightly different error message TypeError: 'float' object is not callable which is perhaps a more clear message. Either way, since you're passing a scalar loss value, and not a callable, an error is expected. If you want to use a scalar loss value and not pass the callable, then you should use GradientTape, as noted in the error message.

A: Example code.
If loss is a tensor the following need to be added:
with tf.control_dependencies(gen_updates):
  d_train_opt = tf.optimizers.Adam(
    learning_rate=LR_D,
    beta_1=BETA1
  ).minimize(
      d_loss,
      var_list=d_vars
    )

with tf.control_dependencies(gen_updates):
  d_train_opt = tf.optimizers.Adam(
    learning_rate=LR_D,
    beta_1=BETA1
  ).minimize(
      d_loss,
      var_list=d_vars,
      tape=tf.GradientTape(persistent=False)
    )


text:
Q: FCM (Firebase Cloud Messaging) in Windows Mobile App (Cordova)? I have created mobile App with Cordova 5.0 in Android and iOS. Now, I want to develop the same App in Windows Platform. I am able to use other plug-ins as they provide Windows platform support too. Here is a plug-in I used for FCM.
This plugin does not provide Windows support, so I am planning to go with Windows native programming.
Does FCM provide Native Windows support?

A: There is currently no Windows Phones client for FCM.

A: My recommendation is OneSignal
OneSignal plugin works with iOS, ANDROID and WINDOWS PHONE 8.1.
https://documentation.onesignal.com/docs/cordova-sdk


text:
Q: The case of the insubordinate command button Good day Ladies and Gents.
I lay before you the fruit of many days of frustration, labor and tears, begging for your help.
There are a few moving parts here, so let me introduce them one by one, with nicknames.
TheVisualForcePage - A humble visualforce page, attached to standard controller User, with a custom extension.
TheVFExtensionCtrl - A braggadocious apex class, who wants the world to know how awesome it is(n't).
TheVFComponentOfDoom - A visualforce component with a custom Controller that exposes two very insubordinate Command buttons. In our case, this component exists to provide a re-usable "delete" button, associated logic and general frustration.
TheVFComponentCtrl - An apex class whose sole purpose in life is to delete an F'ing record. Like the fat kid at primary school sports day, it's main issue is that nobody calls on it. (and therein lies our problem)
To set the stage with these moving pieces, we should consider that the Visualforce page displays, depending on mode, a list of either makes, models or years of cars owned by the given user. Because in my fictional world, users may own multiple Ferrari F12 Berlinetta's (different colors of course.) We can safely assume that if one were to navigate to Farrari, and then Berlinetta, we would see at least one record displayed on our VF page. (2013 of course). These records are displayed in a custom list view format created by using an Apex:Repeat tag.
It's here where we discover our first problem. The list view has, as it's last column a series of "actions" like: "Sell", "Delete" (dear god, who would ever delete a Farrari f12???) and edit. Sell and Delete are command buttons exposed via our handy components. To simply this issue, lets pretend we only have a delete button.
Now, to the untrained, unsuspecting eye a visualforce component, with it's own controller invoked on a page during an Apex:Repeat loop doesn't sound all that complicated. Sure there's the issue of passing in an ID to the logic of the component controller, but that's time-tested, mother approved. Indeed, I thought I was, well, done with this until ...
As it turns out, pressing the delete button has a very curious set of consequences in this setup, consequences I can not fully explain, nor fix.
When you click on the delete command button, the page refreshes (yay, i want that!) However:

*

*Detailed logging shows that the master vfpage's associated controller extension's constructor is executed. Without error

*That the component's deleteThisCar method is Never invoked.

*Visually, the page state has been lost. What do I mean? I mean that the page that was displaying years of Ferrari F12 Berlinetta's is now just blank, showing only the headers of the listview.

Not to be outdone by an overgrown java app, I've tried the following approaches:

*

*Updating my code to use apex:ActionRegion tags around the components

*Tried every damn combination of reRender on the command buttons. Curiously, this had the effect of not reloading the page, and not calling my apex method.

*I said, F-IT loudly and refactored the code to not use a component -- invoking an action method directly on the master controller, but this also failed! causing the page to reload, without my action method being invoked

*I have slept on the problem. (no joke, this usually works for me. I wake up with the answer.)

*I have asked Co-workers to look at it. They suggested the actionRegion bit.

*I tried giving up on my trusty commandButtons attempting to use a standard input button with an ActionFunction -- Curiously, this invokes the constructor of my component controller, but not the actual delete function.

Suffice it to say, that overgrown java app is raining on my day.
This feels like somehow the wrong form is being submitted, which is distinctly maddening because i've also rewritten the master vf page such that it had 2 forms (search in header, main page form) and 5 forms (Search in header, 1 form per "mode") Neither has worked.
I realize that it'd be hypocritical in the extreme if I posted this question without some kind of code attached, so here's the component and it's extension. The VF page itself is quite lengthy and I've not finished "sanitizing" it for public consumption.
<apex:component controller="ACE_DeleteCarCmpCtrl" allowDML="true">
<apex:attribute name="tv"
    description="ID of the Car model and year to display controls for."
    type="Id"
    required="false"
    assignTo="{!CarVersionId}"
/>
<apex:attribute name="t"
    description="ID of the Car model to display controls for."
    type="ID"
    required="false"
    assignTo="{!Car}"
/>

    <apex:outputPanel layout="block" id="theoutputpanel">
    <apex:actionRegion >

        <apex:commandButton action="{!deleteCarOrYear}"
            value="Delete Car"
            rendered="{!IF(ISNULL(Car), false , true)}"
            styleClass="btn btn-sm btn-default"
            />

        <apex:commandButton action="{!deleteCarOrYear}"
            value="Delete Car Version"
            styleClass="btn btn-sm btn-default"
            rendered="{!IF(ISNULL(CarVersionId), false , true)}"
            rerender="nothing"
            />
    </apex:actionRegion>
    </apex:outputPanel>

The best controller ever:
public with sharing class ACE_DeleteCarCmpCtrl {

Public ACE_Car_Version__c carVersion {get; set;}
Public Id carVersionId  {get; set { carVersionId = value; }}
Public ACE_Car__c car {get; set;}

public ACE_DeleteCarCmpCtrl() {
    system.debug('$$$$$$$$$$$$$$ : ' + ApexPages.currentPage().getParameters());
}

public PageReference deleteTrackOrVersion() {
    system.debug('************* : ' + ApexPages.currentPage().getParameters());
    try {
        if (car != null && carVersion != null) {
            throw new ACE_contentManagementLib.ContentManagementException('Both car and carVersion cannot be populated when invoking this component');
        } else if (carVersion == null && car == null) {
            throw new ACE_contentManagementLib.ContentManagementException('Both car and carVersion cannot be null when invoking this component');
        } else if (carVersion != null) {
            ACE_ContentManagementLib.deletecarVersion(carVersionId);
        } else if (car != null) {
            ACE_ContentManagementLib.deleteTrack(track);
        }
    } catch (ACE_ContentManagementLib.ContentManagementException e) {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
    }
    //return null;
    //Also tried null above. no joy.
    PageReference pageRef = new PageReference('/AwesomePage?id=' + UserInfo.getUserId() );
    system.debug('$$$$$$$$$$$$$$ : ' + ApexPages.currentPage().getParameters());
    pageRef.setRedirect(true);
    return pageRef;
}

}
Help me Obi-won-stackOverflow, you're my only hope!

A: So ladies and gents. This turned out to be a case of premature optimization.
(If you experience an optimization lasting 4 hours please see a qualified technical architect)
Turns out that if you know you're going to have a big list-o-data, and you just prematurely put the transient word in front of it's definition ... well weird a$$ stuff happens.
Moral of the story, don't mark the collection you're going to apex:repeat over as transient unless you want to scratch your eyeballs out and post humorous stack exchange questions in raw desperation as you download half a gallon of bourbon.

A: That's really long, and I didn't take in all the details but this might help you...
I had a similar situation with wanting to put components inside a repeat, with similar crazy results. I ended up namespacing my component to make all of the ajax calls to the controllers unique. Weird, ugly, but it works.
The component definition was:
<apex:component controller="SortableListController">
<apex:attribute name="uniqueString" assignTo="{!uniqueStringParam}" type="String" description="A string to make action functions inside the component unique. Should be unique for each component used on the same page and valid to go on the end of a JavaScript variable name." required="true"/>

Then my actions functions were like this:
<apex:actionFunction action="{!gotoFirstPage}" name="gotoFirstPageJS{!uniqueString}" reRender="pb" status="pb:sortStatus"/>

So the invocation was:
<<

And to instantiate this component from my VF page, I did this:
<apex:repeat value="{!projects}" var="thisProject" >
  <c:Sortable_List uniqueString="{!thisProject.id}"

Make sense? Helpful?


text:
Q: Using webkit to render html pages I want to render the HTML of a website and execute any synchronous and asynchronous javascript and then access the resulting DOM tree. And this has to be done headlessly.
I am currently trying to bypass the javafx WebEngine and trying to work directly on the webkit wrapper.
I can get the HTML to load just fine, but I can not seem to get it to:

*

*load additional resources (javascript, css,...)

*execute the javascript

I have set up a very simple test html page:
<html>
    <head>
        <script
                  src="https://code.jquery.com/jquery-3.2.1.min.js"
                  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
                  crossorigin="anonymous"></script>
        <script>
            window.addEventListener("load", function () {
                console.log("loaded!");
                document.body.innerHTML = "haha!!";
            });
        </script>
    </head>
    <body>hello!</body>
</html>

The java code looks like this (the web page is com.sun.webkit.WebPage):
WebPage page = new WebPage(
        new WebPageClientImpl(),
        new UIClientImpl(),
        new PolicyClientImpl(),
        new InspectorClientImpl(),
        new ThemeClientImpl(),
        false);

page.addLoadListenerClient(new LoadListenerClientImpl());
page.setJavaScriptEnabled(true);
page.open(page.getMainFrame(), url);

And not entirely sure yet what it does but I send out a tick every second:
Timer.getTimer().notifyTick();

When I access the resulting DOM tree, I see the HTML but the javascript has not been executed.
Does anyone know how to get the page to render fully?
Alternative suggestions to rendering html+javascript headlessly are also welcome. Note that there does not need to be any visualization, I simply need programmatic access to the DOM tree.


text:
Q: What is the most lightweight way to load an unloaded attribute for an object? As an example, say I would want to change the filter navigation for categories to add a title attribute to the links generated. The file
/app/design/frontend/base/default/template/catalog/navigation/left.phtml

contains the category object ($_category). However, the attribute meta_title isn't loaded for that object.
Straight forward, I could load a second category object, but that loads a lot of attributes that $_category already contains.
So I'm looking for the most lightweight way to load additional attributes for a given object, and best would be without loading a new object of the same type.

A: You are right, calling load for each category is a performance killer.
Also loading an attribute for a category separately does not scale, because you will have to do a query for each category.
So you can just add the attribute to the category collection when the collection is loaded.
Here is the stack trace of what happens.
In /template/catalog/navigation/left.phtml this method is called to retrieve the categories. <?php $_categories = $this->getCurrentChildCategories() ?> where $this is an instance of Mage_Catalog_Block_Navigation.
Inside this method at one point $category->getChildrenCategories() is called where $category is the current category object that is an instance of Mage_Catalog_Model_Category.
The method getChildrenCategories is this class is just a wrapper for Mage_Catalog_Model_Resource_Category::getChildrenCategories.
You can rewrite this method and add your attribute in the collection, but this method does the actual loading of the collection, so you better rewrite the method that prepares the collection.
This one is _getChildrenCategoriesBase from the same class.
Make it look like this:
protected function _getChildrenCategoriesBase($category)
{
    $collection = parent::getCollection($category);
    $collection->addAttributeToSelect('meta_title')
    return $collection;
}

Here is a nice explanation on how to rewrite a resource model: https://stackoverflow.com/a/15921599/2047249


text:
Q: Вывод числа (int) в формате ii. ( Число 1, как 01 и тд ) Как число ( int num = 1 ) вывести в формате ii ( 1 -> 01, 5 -> 05, 11 -> 11 и т.д. )
A: #include <iostream>

using namespace std;

int main(){
    cout.width(2);
    cout.fill('0');
    cout << 5 << endl;
    cout << 95 << endl;

    return 0;
}

05
95
Press <RETURN> to close this window...


text:
Q: Get extreme X and Y values in angular highcharts (ng-highcharts) I'm using ng-highcharts to draw a stock chart containing 3 series. I'm using a navigator to zoom. What I want to know is how can I get the extreme y values of each series when

*

*drawing the graph and

*when changing the graph using navigator.

I know to call event on x-axis when navigator event happens. But have no idea how to get the extreme values.
PS: Not using jQuery


text:
Q: Style for Caption in RADGrid How can we set style for caption in radgrid?
Following is how I am trying to set the caption text:
radExport.MasterTableView.Caption = "Reports";

A: I believe you can adjust the styling like this:

Here's some documentation that talks about it:
http://www.telerik.com/help/aspnet/grid/radgrid-telerik.webcontrols.gridtableview-caption.html

A: If you want to add style while only when exporting take a look at this

A: You can also write your own HTML code and bind through RadGrid.MasterTableView.Caption at the Export Button Click. It can be a logo or some statement that you would like to have it at the top of the file.
string firstHeaderLine = "
Company Name: XYZ
";
firstHeaderLine += "
Date Report Generated: " + DateTime.Now.ToShortDateString() + "
";
firstHeaderLine += "
Report Generated by: XYZ
";
RadGrid1.MasterTableView.Caption = firstHeaderLine;

Hope this will give you an idea.


text:
Q: How to write the implicit equation of a surface when given the parametric equations? How can I find the implicit equations of a surface if I have the parametric equations? For example, if the surface $(S)$ is given by:
$$x = u+\sin v$$
$$y=u+\cos v$$
$$z = u+a$$
what are the implicit equations of this surface?

A: Hint.
Essentially you want to cancel out the parameter $u$ and $v$.
The parameter $u$ disappears immediately if you substitute $u=z-a$ into the first and second equations:
$$
x=z-a+\sin v,\quad y=z-a+\cos v\tag{1}
$$
This should remind you of a circle in poloar coordinates.
Now apply the identity $\sin^2 v+\cos^2 v=1$ to combine the two equations in (1).


text:
Q: icCube incremental vs single load performance I'm using flat file data sources with the incremental load functionality and am seeing different performance depending on how I do the load. I have 3 datasets {d1,d2,d3} with d1 and d2 being the same size and d3 being 3 times larger. I am doing the following test on a machine with 16GB memory:

*

*Load d1 - time: 1m07s

*incrementally load d2 - time: 2m53s

*incrementally load d3 - runs out of memory
On the other hand, if I do a single load of d1+d2+d3, the total time is 5m29s and there are no memory issues.
Is this just a matter of memory overhead when doing incremental vs single load or should I be better managing the performance?

A: Incremental load has been implemented for supporting real time and it has not the same logic as a normal load.
Additional data is pre-loaded into memory, that's why it takes more memory. During this pre-load the schema is still available, once the new data is fully preloaded and a first quality check is done, the schema is write locked and the actual load is done. This allows for having the schema locked for a few miliseconds.
The incremental load is suitable for for real-time, 'small' amount of additional data, not really for your scenario.
Slow times are not due to the fact you're running out of memory ( a lot of GC's )
?
Hope that helps.
PS: If you need an additional support please contact support directly.


text:
Q: Is the CLI optimized for throughput? Would the very latest Azure CLI chunk big files and do parallel uploads for max. throughput by default, sending in a signal about all the chunks uploaded before or after downloading like in the test case below described?
https://azure.microsoft.com/en-us/blog/high-throughput-with-azure-blob-storage/
(Context: This relates to the news about high-performance BlobStorage.)

A: Welcome to Stack Overflow! :)
AFAIK this is currently unsupported via CLI.
As per this -> https://github.com/Azure/azure-cli/issues/7616 open GitHub issue, approach of invoking AzCopy through CLI is on-going. Check the same link for further updates.
If you have question of why AzCopy then please refer this -> Azure CLI : bash script to upload files in parallel thread which talks about accomplishing the requirement with AzCopy approach.
Other related references:
https://learn.microsoft.com/en-us/cli/azure/storage/blob?view=azure-cli-latest#az-storage-blob-upload-batch
https://learn.microsoft.com/bs-latn-ba/azure/storage/blobs/storage-blob-scalable-app-upload-files?view=azure-java-stable
Hope this helps!! Cheers!! :)
Note: If you think your question has been answered then please 'accept' it, if just helped then click "This answer is useful" and provide an up vote. This can be beneficial to other community members reading this thread.


text:
Q: Selecting specific Excel inputs with Python and saving them into another Excel file? I would like to try something new with Python. It's about an excel file from which I want to insert certain entries into another excel file. As you can see, I want to insert the entries that contain a colour name into another file in brackets and write the colour name translated in front of it. Do you have any idea how I can do this? I would be grateful for any answer.
import openpyxl
from openpyxl import Workbook, load_workbook
book = openpyxl.load_workbook('datei.xlsx')

valuesK = []

sheet = book.get_sheet_by_name(Sheet1)
vK = sheet['G1': 'G2259']

for row in vK:
    for cell in row:
        if blue in cell:
            valuesK.append('Blau (' + cell.value + ')')
        elif red in cell:
            valuesK.append('Rot (' + cell.value + ')')
        elif grey in cell:
            valuesK.append('Grau (' + cell.value + ')')
        elif black in cell:
            valuesK.append('Schwarz (' + cell.value + ')')
        elif white in cell:
            valuesK.append('Weiß (' + cell.value + ')')
        elif offwhite in cell:
            valuesK.append('Elfenbein (' + cell.value + ')')
        elif brown in cell:
            valuesK.append('Braun (' + cell.value + ')')
        elif beige in cell:
            valuesK.append('Beige (' + cell.value + ')')
        elif pink in cell:
            valuesK.append('Pink (' + cell.value + ')')
        elif yellow in cell:
            valuesK.append('Gelb (' + cell.value + ')')
        elif orange in cell:
            valuesK.append('Orange (' + cell.value + ')')
        elif green in cell:
            valuesK.append('Grün (' + cell.value + ')')
        elif turquoise in cell:
            valuesK.append('Türkis (' + cell.value + ')')
        elif purple in cell:
            valuesK.append('Violett (' + cell.value + ')')
        elif gold in cell:
            valuesK.append('Gold (' + cell.value + ')')
        elif silver in cell:
            valuesK.append('Orange (' + cell.value + ')')
        else:
            valuesK.append('Multicolour (' + cell.value + ')')

i += 1
result +=1

wb = Workbook()
ws = wb.active

filename='dosya'

i = 0
for i in valuesK:
    j += 1
    ws['A' + str(j)] = i
    int(j)

wb.save('datei2.xlsx')

A: Recommend approaching this in the following order:

*

*read your current worksheet into pandas using pd.read_excel(DF) https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html

*condition your inputs to account for capitalization and extra spaces

*use a dictionary as your translator instead of the conditionals https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

*use openpyxl dataframe_to_rows to condition the pandas data frame for export into a workbook.

Here is a simplified working example:
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows

# create a function to deal capitalization and extra spaces
def condition(x):
    x = x.strip().lower()
    return x

# use a dictionary for your translator
color_translator_dict = {
    'red': 'rot',
    'blue': 'blau',
    'white': 'weiss'
}

# read the original excel file using pandas read_excel
colorDF = pd.read_excel('colors.xlsx', header=None)

# condition all cells to deal with upper case and extra spaces
colorDF = colorDF.applymap(condition)

# use dictionary pandas dictionary replace to translate
colorDF = colorDF.replace(color_translator_dict)

# output to workbook using openpyxl
# create new workbook
wb = Workbook()
ws = wb.active

# use openpyxl's dataframe_to_rows to condition pandas DF
rows = dataframe_to_rows(colorDF)

# iterate through the rows and apply to new workbook
for row_id, row in enumerate(rows, 1):
    for column_id, value in enumerate(row, 1):
        if value == 0 or value is None:
            pass
        else:
            if column_id == 1:
                # this is the pandas index
                pass
            else:
                # compensate for the counting difference between dataframes and
                # Excel sheets
                column = column_id - 1
                row = row_id - 2
                print(f'{column_id=}, {row_id=}: {value=}')
                ws.cell(row=row, column=column, value=value)

# save the new workbook
wb.save('output_wb.xlsx')

A: Please check the code below with your file. I did what you are trying to do with the approach you can best understand from my code. I know it is not the most efficient way to do it, but as you need help with your code. So, here it is:
import openpyxl
from openpyxl import Workbook, load_workbook
#add your path to file
book = openpyxl.load_workbook(r'e:/Python Projects/Openpyxl/colordata.xlsx')

valuesK = []

sheet = book.get_sheet_by_name('Sheet1')

vK = sheet['G1': 'G80']
#Increase cells from G80 to how many you want
wb = Workbook()
ws = wb.active
filename = 'translated'

def color_translator():
    for row in vK:
        for cell in row:
            try:
                color_value = (str.lower(cell.value))
                print(cell.value)
                if color_value == 'blue':
                    valuesK.append('Blau (' + cell.value + ')')
                elif color_value == 'red':
                    valuesK.append('Rot (' + cell.value + ')')
                elif color_value == 'grey':
                    valuesK.append('Grau (' + cell.value + ')')
                elif color_value == 'black':
                    valuesK.append('Schwarz (' + cell.value + ')')
                elif color_value == 'white':
                    valuesK.append('Weiß (' + cell.value + ')')
                elif color_value == 'offwhite':
                    valuesK.append('Elfenbein (' + cell.value + ')')
                elif color_value == 'brown':
                    valuesK.append('Braun (' + cell.value + ')')
                elif color_value == 'beige':
                    valuesK.append('Beige (' + cell.value + ')')
                elif color_value == 'pink':
                    valuesK.append('Pink (' + cell.value + ')')
                elif color_value == 'yellow':
                    valuesK.append('Gelb (' + cell.value + ')')
                elif color_value == 'orange':
                    valuesK.append('Orange (' + cell.value + ')')
                elif color_value == 'green':
                    valuesK.append('Grün (' + cell.value + ')')
                elif color_value == 'turquoise':
                    valuesK.append('Türkis (' + cell.value + ')')
                elif color_value == 'purple':
                    valuesK.append('Violett (' + cell.value + ')')
                elif color_value == 'gold':
                    valuesK.append('Gold (' + cell.value + ')')
                elif color_value == 'orange':
                    valuesK.append('Orange (' + cell.value + ')')
                else:
                    valuesK.append('Multicolour (' + str(cell.value) + ')')
            except TypeError as e:
                pass

    print(valuesK)
    j = 1
    for value in valuesK:
        ws['A' + str(j)] = value
        j += 1

#launch Function from HERE#
color_translator()
print('file_Saved')
#Set path where you want your excel file
wb.save(filename = 'E:\Python Projects\Openpyxl\mybook.xlsx')

You can compare them both and see what has been changed. The main mistakes were in the conditionals when you were writing an unknown variable named blue in place of cell.value. Please feel free to contact me if more help is needed. Also, if someone can improve this code please feel free to do that as well.


text:
Q: Pictures fade from BW to color while responsive What I want to do is to create a menu with 3 pictures (side-by-side):

I want each picture to become colored when hovering.
The problem here is that the pictures should resize matching the window size (responsive for Tablets and Phones).
I can't seem to get it to work as the pictures have a space in between and they won't fit the window's size:
https://jsfiddle.net/EgDqy/68/embedded/result/

$(".cell").hover(
  function() {
    $(this).find('.fader').fadeOut("slow");
  },
  function() {
    $(this).find('.fader').fadeIn("slow");
  }
);
.cell {
  height: 100%;
  width: 100%;
  display: inline-block;
  position: relative;
}
.cell img {
  height: 100hv;
  position: absolute;
  top: 0;
  left: 0;
}

A: You don't actually need JS or extra images for that.
CSS can do it all.

img {
  -webkit-filter: grayscale(1);
  -moz-filter: grayscale(1);
  filter: grayscale(1);
  transition: -webkit-filter 1s ease;   /* just for reference - add your owne prefixes */
}
img:hover {
  -webkit-filter: grayscale(0);
  -moz-filter: grayscale(0);
  filter: grayscale(0);
}


text:
Q: Check for database access. Rails + ActiveRecord We are using legacy database that goes down unexpectedly.
This is bad experience for the user and for us.
When doing a simple query, like: User.find(1) and database goes down, it will not throw the exception. Just hangs there until database comes back.
Setting timeout did not seem to do any good either.
Running this:
connected = ActiveRecord::Base.connection_pool.with_connection { |con| con.active? }  rescue false also hangs when connection is lost
Is there any way to check if the database is there before actuall making an ActiveRecord call?
Rails - 4.1.15
Ruby - jruby-9.0.5.0
Database: as400 (db2)


text:
Q: matplotlib bar plot add legend from categories dataframe column I try to add the legend which should, according to my example, output:

*

*a red square with the word fruit and

*a green square with the word
veggie.

I tried several things (the example below is just 1 of the many trials), but I can't get it work.
Can someone tell me how to solve this problem?
import pandas as pd
from matplotlib import pyplot as plt
data = [['apple', 'fruit', 10], ['nanaba', 'fruit', 15], ['salat','veggie', 144]]
data = pd.DataFrame(data, columns = ['Object', 'Type', 'Value'])

colors = {'fruit':'red', 'veggie':'green'}
c = data['Type'].apply(lambda x: colors[x])

bars = plt.bar(data['Object'], data['Value'], color=c, label=colors)
plt.legend()

A: The usual way to create a legend for objects which are not in the axes would be to create proxy artists as shown in the legend guide
Here,
colors = {'fruit':'red', 'veggie':'green'}
labels = list(colors.keys())
handles = [plt.Rectangle((0,0),1,1, color=colors[label]) for label in labels]
plt.legend(handles, labels)

A: So this is a hacky solution and I'm sure there are probably better ways to do this. What you can do is plot individual bar plots that are invisible using width=0 with the original plot colors and specify the labels. You will have to do this in a subplot though.
import pandas as pd
from matplotlib import pyplot as plt

data = [['apple', 'fruit', 10], ['nanaba', 'fruit', 15], ['salat','veggie', 144]]
data = pd.DataFrame(data, columns = ['Object', 'Type', 'Value'])

colors = {'fruit':'red', 'veggie':'green'}
c = data['Type'].apply(lambda x: colors[x])

ax = plt.subplot(111) #specify a subplot

bars = ax.bar(data['Object'], data['Value'], color=c) #Plot data on subplot axis

for i, j in colors.items(): #Loop over color dictionary
    ax.bar(data['Object'], data['Value'],width=0,color=j,label=i) #Plot invisible bar graph but have the legends specified

ax.legend()

plt.show()


text:
Q: Avoid user interaction when we use CLLocationManager Is it possible on a jailbreak iPhone get gps location without user interaction?
In my code
[CLLocationManager authorizationStatus]

always return kCLAuthorizationStatusRestricted.
If I use
[CLLocationManager setDefaultEffectiveBundle:[NSBundle bundleForClass:self.class]]; // privat api

I getting kCLAuthorizationStatusNotDetermined.


text:
Q: Solving differential equation that includes an (extra) unknown function I am trying to find a solution for $C_a(t)$ in the below differential equation:
$$
V \cdot \frac {dC_a(t)} {dt}=R(t)-Q_v \cdot C_a(t) \\
$$
$
\text{Where} \\
\qquad V \text{ is the volume of the test chamber } [m^3] \\
\qquad C_a \text{ is the concentration in test chamber } \Big[\frac{kg}{m^3} \Big] \\
\qquad R \text{ is the non-constant emission rate from test sample } \Big[\frac{kg}{m^2 \cdot s} \Big] \\
\qquad Q_v \text{ is the constant volume flow rate of ventilation air passing through the test chamber } \Big[\frac{m^3}{s} \Big] \\
$
The non-constant emission rate is the "unknown function" mentioned in the question title. Stating that the function that governs emission rate is unknown is somewhat inaccurate as I have a vector containing values for emission for every examined time t.
Besides knowing values for $R$ at given times $t$, we know that $Ca(0) = 0$ and that $R(0) = 0$.
I am in the process of writing a small Matlab script, and therefore I am hoping to find a solution on a form that allows implementation and evaluation at given points in time (corresponding to the values in known vector $R$).
I have already given it my best, and I have arrived at the below expression (that I sincerely hope is correct). However, this expression considers $R(x)$ as a continuous function and will not be implemented easily.
$$
C_a(t) = exp(-Q_v t V^{-1}) \int_{0}^{t}
exp(-Q_v x V^{-1}) R(x) V^{^-1} dx, \quad for \ \ C_a(0)=0
$$
Can anybody help me find a simpler (explicit and fully analytical) solution for $C_a(t,R(t))$ that is easy to implement?

A: The solution with initial value $C_a(0) = C_0$ is
$$C_a(t) = \exp(-Q_v t/V) \left( C_0 + \int_0^t \exp(Q_v s/V) \frac{R(s)}{V}\; ds \right) $$
You can approximate the integral with Riemann sums.

A: Turns out that Matlab does have a function that allows for solving ODEs with time dependent terms.
Thank you all very much for your time and help.


text:
Q: Why can't I use T as a return type for my prefix operator? Simply exploring Swift, in the context of the Observable pattern rite of passage. What I wanted to explore was implementing a prefix operator for the sake of syntactic sugar.
class Observable<T> {
    var value:T
    init(_ v:T) {
        value = v
    }
}

postfix operator &* { }

postfix func &* (arg:Observable<T>) -> T {
    return arg.value
}

However, the compiler informs me that -> T is use of an undeclared type. Can the generic really not be used as the return type? Is there something else going on here?

A: You just need to make the function generic:
postfix func &*<T>(arg:Observable<T>) -> T {...}

As you've written it, T is expected to be a type itself, not a type parameter.


text:
Q: Is it possible to get Websocket Id when receiving the message from MessageEventArgs? I am trying to find websocket connection Id or some unique data that I can use to store connections.
WebSocketServer wss = new WebSocketServer("ws://localhost:8887");
wss.AddWebSocketService<Message>("/Message");
wss.Start();
Console.ReadKey();
wss.Stop();

    protected override void OnMessage(MessageEventArgs message)
    {
         **var connectionID= ??? ;**
        Sessions.Broadcast(e.Data);
        Send(e.Data);
    }


text:
Q: Can we perform DML operations like Delete using Group by clause? Can we perform DML operations like Delete using Group by clause in T-SQL?

A: SELECT statement - http://msdn.microsoft.com/en-us/library/ms189499.aspx
DELETE statement - http://msdn.microsoft.com/en-us/library/ms189835.aspx
As you can see, GROUP BY is in the SELECT, but not DELETE, so you cannot use it directly. Nor is it in the INSERT statement either.
[ WITH <common_table_expression> [ ,...n ] ]
DELETE
    [ TOP ( expression ) [ PERCENT ] ]
    [ FROM ]
    { <object> | rowset_function_limited
      [ WITH ( <table_hint_limited> [ ...n ] ) ]
    }
    [ <OUTPUT Clause> ]
    [ FROM <table_source> [ ,...n ] ]
    [ WHERE { <search_condition>
            | { [ CURRENT OF
                   { { [ GLOBAL ] cursor_name }
                       | cursor_variable_name
                   }
                ]
              }
            }
    ]
    [ OPTION ( <Query Hint> [ ,...n ] ) ]
[; ]

But using the WHERE clause, or the  clause, you can make use of GROUP BY, such as
DELETE tbl
WHERE id NOT IN (select max(id) from tbl GROUP BY date_logged)

or
DELETE a
FROM tbl a
JOIN (select a_id from othertbl group by a_id having count(*) >= 3) b
    ON a.id = b.a_id

A: What you are trying
its not possible.................
you can do something like this
DELETE FROM #Customers
WHERE ID IN
( SELECT    MAX(ID) FROM #Customers
GROUP BY CustName, Pincode
HAVING COUNT(*) > 1)

A: You can't use GROUP BY directly in the target of a DELETE operation but you can use PARTITION BY instead.
This is a useful alternative to using GROUP BY and a sub query for tasks such as deleting duplicates.
Combined with Windowed Aggregate functions this allows you to do many tasks which a hypothetical DELETE ... GROUP BY might allow.
e.g. For the following setup
DECLARE @foo TABLE
(
col1 int,
col2 int
)
INSERT INTO @foo
SELECT 1,100 UNION ALL
SELECT 1,123 UNION ALL
SELECT 2,150 UNION ALL
SELECT 2,200

This is not valid syntax
DELETE FROM @foo
GROUP BY col1
HAVING SUM(col2) > 300

However this is
;WITH cte AS
(
SELECT SUM(col2) OVER (PARTITION BY col1) AS S
FROM @foo
)
DELETE FROM cte
WHERE S > 300


text:
Q: PC Stalls trying to open Downloads location I noticed this a few times... it can take 10-20s for my Win10 PC to open the downloads location from File Explorer. But other folders/drives open instantly as you'd expect.
I don't recall downloads being a special location - it's just a regular folder not a virtual location or anything, right?
What might cause this to occur?

A: This is a known 'issue', a Google research returns a lot of articles explaining how to get rid of this annoying behaviour.
To summarize :
Cause : Your Download folder might be optimized for Pictures items. Therefore, it tries to load thumbnails, which takes some time (rendering or so).
Solution : Configure your Download folder to be optimized for General items.
Source : http://www.istartedsomething.com/20121202/quick-fix-for-very-slow-to-load-downloads-folder-in-windows-7-8/
Excerpt of the source article :

For some reason, the "Downloads" folder likes to be categorized as a
  "Pictures" folder (I'm guessing because people store a lot of JPGs in
  it). The problem with this view is that it tries to generate
  thumbnails for all the files in this folder, even if they're not
  pictures.
The fix is to ensure the folder settings for "Downloads" is optimized
  for "General items". This should have an instant effect (the next time
  you add files to the folder since the thumbnails are otherwise cached
  anyway).


text:
Q: MSAL.js protectedResourceMap - explanation needed for what to set it to I have 2 sites, an angular application and a WebAPI.
When I use MSAL.js from the frontend to call the WebAPI, no token is being attached (because of CORS).
I know I need to set protectedResourceMap but I can't find a clear explanation of how to set it.
I can find plenty of examples, but none giving an explanation that makes sense (to me).
Can anyone please offer any input?

A: I am just learning this but found this information in the doco:
MSAL.js Angular readme:

protectedResourceMap : Mapping of resources to scopes {"https://graph.microsoft.com/v1.0/me", ["user.read", "mail.send"]}. Used internally by the MSAL for automatically attaching tokens in webApi calls. This is required only for CORS calls.

My understanding of the given example is:
export const protectedResourceMap:[string, string[]][]=[
    ['your api endpoint',['scope 1', 'scope 2', 'scope n']] // example
    ['https://buildtodoservice.azurewebsites.net/api/todolist',['api://a88bb933-319c-41b5-9f04-eff36d985612/access_as_user']], // api you host
    ['https://graph.microsoft.com/v1.0/me', ['user.read']] // ms graph api - uses short scope names with no uri prefix
];

So when calling the path 'your api endpoint' include the token associated with the scopes 'scope 1', 'scope 2', 'scope n'.

A: Devin Wright's comment on this answer worked for me:

I had to remove the "api://" portion of the identifier for it to work.


text:
Q: authentication with google in firebase alone users created Angular "How can I do so that the authentication with google by firebase is only for already created users?  Not create user"
I need the already registered user to log in with google. do not create a new user.
that google verify in firebase that the user exists and if it exists, start the session


text:
Q: what should be transition in css3 <html>
   <head>
      <style>
         <!-- Need help in this css for transition of background-image -->
          body{
              -webkit-transition:background-image 5s ease-in-out;
              -moz-transition:background-image 5s ease-in-out;
              -o-transition:background-image 5s ease-in-out;
              -ms-transition:background-image 5s ease-in-out;
               transition:background-image 5s ease-in-out;
            }
      </style>
    </head>
 <body>
</body>
</html>

need a background-image transition like flash
Need  a flash background-image effect
I tried this too
   $('body').
        animate({ opacity: 0 },
                   'slow',
                    function () {
                        $(this).css(
                           { 'background-image':
                             'url(\''+jdata.imageurl+  '\')'    }).animate({ opacity: 1 });
                     });

A: It's not possible to transition a background-image, transitions can only transition those properties which have an implicit, or explicit, numerical scale; for example such properties as width, height, opacity and so on.
This is the same reason that it's not possible to transition to, or from, display: none because there are two states (visible and non-visible) with no possible interim steps between the two.
If you want to transition between one background-image and another, you'd need to stack multiple elements in the same space and then fade the element(s) containing that background-image in/out using either CSS transitions or animations.
You could, alternatively, transition the background-image-position properties to give the impression of a carousel, for example, since this property uses CSS length units, which can – of course – be transitioned smoothly.


text:
Q: How to declare decorator inside a class, to decorate an already decorated, inherited method? I want to create a decorator which is a class member, and that is going to decorate an inherited method, which is decorated.
example code:
class A(object):
    __metaclass__ = ABCMeta
    def __init__(self):
        pass

    @classmethod
    def the_decorator(cls, decorated):  # <-----this is what i want, with or without self/cls as an argument
        def decorator()
            #do stuff before
            decorated()
            print "decorator was called!"
            #do stuff after
        return decorator

    @abstractmethod
    def inherited():
        raise NotImplemented

class B(A):
    def __init__(self):
        super(B,self).__init__()

    #@A.the_decorator <--- this is what I want,
    @overrides
    #@A.the_decorator <--- or this
    def inherited():
        print "B.inherited was invoked"

and
b = B()
b.inherited()

should output

B.inherited was invoked
decorator was called!

Having read this guide on decorators as class members, I still haven't been able to figure out how to decorate inherited methods with decorators defined in the super class.

Note, here @overrides is defined by the overrides package pip install overrides

Also note i am currently using python 2.7, but would love both 2.7 and 3+ answers.
Thanks!

A: You were not that far!
The key is that a decorator will receive one single argument which is the decorated function so it can only be a statmethod. And you also forgot that normal methods should be declared with a self argument.
But this code should work:
class A(object):
    __metaclass__ = ABCMeta
    def __init__(self):
        pass

    @staticmethod
    def the_decorator(decorated):  # <-----this is what i want, with or without self/cls as an argument
        def decorator(self):
            #do stuff before
            decorated(self)
            print "decorator was called!"
            #do stuff after
        return decorator

    @abstractmethod
    def inherited():
        raise NotImplemented

class B(A):
    def __init__(self):
        super(B,self).__init__()

    @A.the_decorator #<--- this is what I want,
    @overrides
    #@A.the_decorator <--- or this
    def inherited(self):
        print "B.inherited was invoked"

I could test it under Python 2.7 except for the @overrides decorator (I commented it in my tests)

A: Using Python 3, your code is just missing a few self arguments to be able to call the function with b.inherited()
class A(object):
    __metaclass__ = ABCMeta
    def __init__(self):
        pass

    @classmethod
    def the_decorator(cls, decorated):
        def decorator(*args, **kwargs):
            #do stuff before
            decorated(*args, **kwargs)
            print("decorator was called!")
            #do stuff after
        return decorator

    @abstractmethod
    def inherited(self):
        raise NotImplemented

class B(A):
    def __init__(self):
        super(B,self).__init__()

    @A.the_decorator
    @overrides
    def inherited(self):
        print("B.inherited was invoked")


text:
Q: Rectangle intersection algorithm Hi I tried a question to check whether two rectangles intersect or not
I have written code if rectangles are parallel to x-axis
struct point
{
 int x;
 int y;
};

struct rect
{
 struct point left;
 struct point right;
};

//1 - intersection
// 0- no intersection
int rectintersectioncheck(struct rect r1,struct rect r2)
{
    int x_check = (r1.left.x > r2.right.x || r2.left.x > r1.right.x);
    int y_check = (r1.right.y > r2.left.y || r2.right.y > r1.left.y);

    if(x_check && y_check )
    {
               return 0;
    }
    return 1;
}

its working fine for this case but i am confused for algo in case of rectangle not parallel to x-axis
as only top left,right bottm points are givenn
please help?

A: A clarification first. If p1 and p2 are the top-left and bottom-right points of a rectangle, then the rectangle must be parallel to x axis (and y axis). So there is only exactly one rectangle satisfying these conditions. If the rectangle is not parallel to x axis, then the bottom cannot become right point simultaneously.
Since we are talking about rectangles that are not exactly parallel to x axis, let us drop that definition. Let us talk about rectangles whose two opposing vertices are p1 and p2 (not necessarily top-left and bottom-right).
Let p1 and p2 define the first rectangle, and p3 and p4 define the second rectangle.
If you take the union of all rectangle whose opposite corners are p1 and p2, you get a circle (with (p1+p2)/2 as center and |p1−p2| as diameter).
There are three cases:

*

*If the p1–p2 line segment intersects the p3–p4 line segment, then the rectangles always intersect.

*If the circle corresponding to p1,p2 intersects the circle corresponding to p3,p4, then those rectangles sometimes intersect.

*Otherwise those rectangles never intersect.

A: @ELKamina: the circle approach you discussed is quite fine, but it can be really hard to distinguish in the cases where cirles intersect but rectangles don't.

I have got his idea in mind, glad to share it.
Why don't we contruct our rectangles in array in the specific cases to find out they intersect or not.
 eg.  rect 1- points (1,3)(3,1)(6,4)(4,6)     rect2 points- (4,0)(5,0)(5,1)(4,1)
array represntation                                      array representation
6 [F F F F # F F F]                                      6 [F F F F F F F F]
5 [F F F # # # F F]                                      5 [F F F F F F F F]
4 [F F # # # # # F]                                      4 [F F F F F F F F]
3 [F # # # # # F F]                                      3 [F F F F F F F F]
2 [F F # # # F F F]                                      2 [F F F F F F F F]
1 [F F F # F F F F]                                      1 [F F F F # # F F]
0 [F F F F F F F F]                                      0 [F F F F # # F F]
   0 1 2 3 4 5 6 7                                          0 1 2 3 4 5 6 7

in the above case circles intersect but rectangles don't.
eg
g. rect 1- points (1,3)(3,1)(6,4)(4,6)     rect2 points- (3,0)(4,0)(3,1)(4,1)
 array represntation                                      array representation
6 [F F F F # F F F]                                      6 [F F F F F F F F]
5 [F F F # # # F F]                                      5 [F F F F F F F F]
4 [F F # # # # # F]                                      4 [F F F F F F F F]
3 [F # # # # # F F]                                      3 [F F F F F F F F]
2 [F F # # # F F F]                                      2 [F F F F F F F F]
1 [F F F # F F F F]                                      1 [F F F # # F F F]
0 [F F F F F F F F]                                      0 [F F F # # F F F]
   0 1 2 3 4 5 6 7                                          0 1 2 3 4 5 6 7

in the above case (3,1) has same value so it can be found that they intersect.
Similar representations can be used to check whether triangles intersect or not.

A: I will sketch out the answer.

*

*Rotate both the rectangles so that one is in line with the x axis

*You can then work out the formula (y=mx+c) for the edges

*You will also know the formula for the sides of the other rectangle

*See if any intersect.

The rotation can be performed using the link previously posed.
EDIT
Forgot translation - shift one rectangle to have 0,0 as one coordinate.


text:
Q: Defining struct in Swift Mac App I am defining a structure in a Mac App using Swift
struct ConfigData {
    var AddressType : UInt8
    var AddressX : UInt32
    var AddressY : UInt32
    var AddressZ : UInt32
}

The struct size is returned as 16 (which is incorrect) but when I change
the order of the structure to
struct ConfigData {
    var AddressX : UInt32
    var AddressY : UInt32
    var AddressZ : UInt32
    var AddressType : UInt8
}

The count is printed correctly as 13. Is there anything I am doing incorrectly

A: This is just a result of the need to keep the variables aligned at 4-byte boundaries. In your first example, three bytes of padding are going to be added so that the addresses of AddressX, AddressY, and AddressZ are properly aligned. In your second example, everything is aligned at a 4-byte boundary already, so no padding is needed.

A: The size 16 is not incorrect because Swift makes no guarantees about the layout and alignment of fields in a native Swift struct. Presumably, in the current version of Swift, it is padding the UInt8 field to 4 bytes so the following UInt32 fields are 4-byte aligned for performance.
There is no guarantee that future versions of Swift will lay out the structure the same way, at least until the Swift ABI is finalized. There are several relevant issues open in the Swift bug tracker:

*

*Determine if the layout algorithm for structs should layout fields in a different order than declared

*Evaluate a fully declaration-order-agnostic layout algorithm for structs

*Determine if struct data members are addressable or bit-packed

*Decide the cap of alignment for struct layout
Also note that if you want an array of ConfigData, you should use MemoryLayout<ConfigData>.stride to measure the size, because Swift may include padding between array elements (again, for performance). You'll probably find that both layouts of ConfigData have a stride of 16.
If you care about the byte layout of your struct, you need to define it in C, probably using compiler extensions to precisely control where the compiler inserts (or doesn't insert) padding.

A: Is there anything I am doing incorrectly
NO, nothing wrong. You just need to know alignment.
Swift compiler aligns UInt32 members to 4-byte boundary, and, as you know, UInt8 takes just one byte. So, your first ConfigData is represented in memory(*) as:
AddressType | |x|x|x|
AddressX    |       |
AddressY    |       |
AddressZ    |       |

where x means padding byte to align following members.
And in your second ConfigData, internal representation would be:
AddressX    |       |
AddressY    |       |
AddressZ    |       |
AddressType | |

In the latter case, MemoryLayout<ConfigData>.size does not count trailing unaligned bytes. As some byte variable can be allocated there.
But if you allocate multiple ConfigData in an array, Swift adds padding bytes at the bottom. So, MemoryLayout<ConfigData>.stride returns the count for this purpose which is 16 for both ConfigData.
(*) Swift does not guarantee the member allocation of structs. And the details may change in the future till ABI stability will be stated.

Seems I am late and my answer is just illustrating some part of rob mayoff's answer. Please read it carefully.


text:
Q: how to populate variable length array of strings So, in javascript(coffeescript), I have some code that looks like this:
"BRIGHT":
  min: 1
  max: 4
  step: 1
  value: 3

bluetooth:
  options: [ 'off', 'on' ]  # SOMETIMES I NEED ARRAY
  callback: ->
    rangeFinder.bluetooth = rangeFinder.getSetting().value

mode:
  options: [ 'basic', 'advanced', 'config' ] # OF DIFFERENT LENGTHS
  callback: ->
    rangeFinder.lastMode = rangeFinder.getSetting().value

How do I do something like this in c++?
I've got an array of 3 objects similar to brightness
#include "setting.cpp"

class GlobalMenu {

  public:

    MenuSetting settings[3];
    int setting;
    GlobalMenu();

};

GlobalMenu::GlobalMenu(void){

  // What is the currently selected setting?
  this -> setting = 0;

  this -> settings[0].name = "BRIGHT";
  this -> settings[0].min = 1;
  this -> settings[0].max = 4;
  this -> settings[0].step = 1;
  this -> settings[0].value = 3;

  this -> settings[1].name = "BLUETOOTH";
  // HOW DO I GET VARIABLE LENGTH ARRAYS HERE?

}

and in setting.cpp
class MenuSetting {

  public:

    char *name;
    int min;
    char options[][5];
    int max;
    int step;
    int value;

};

somewhere else, this code changes the setting (and works)
void RangeFinder::changeSetting(int dir) {

  this -> data.global.settings[this -> data.global.setting].value +=
    (dir ? 1 : -1) *
    this -> data.global.settings[this -> data.global.setting].step;

  this -> enforceMinMax();

  this -> render();
}

also if you can find a way to clean it up that would help
So, I can probably figure out how to detect if options has a length, but I am having problems assigning any number of options into the options array
The solution cannot use the STD.
As far as i know the atmega32 micro-controller can't use std lib.

A: In C++ the canonical way to handle an array of variable size is to use a vector
std::vector<std::string> options;

options.push_back("First option");
options.push_back("Second option");
options.push_back("Third option");

then you can use options.size() to know how many elements are there.
You would also do a favor yourself by reading a good C++ book from cover to cover before starting using the language. C++ is not the right language to learn by experimentation for a few reasons, the most important being:

*

*sometimes C++ is illogical (because of its history) and no matter how smart you are you cannot guess history. You need to study it.

*when you make a mistake you cannot count on the language to help you (there are no runtime error angels, just undefined behavior daemons).

A: The best options for you to avoid the several pitfalls you've fallen into:

*

*Use std::string instead of character pointers and buffers

*Use std::vector instead of compiler-sized arrays

This would make your class look like:
class MenuSetting
{
public:
    std::string name;
    int min;
    std::vector<std::string> options;
    int max;
    int step;
    int value;
};

You can find the details on how the various operations for both std::string and std::vector.

A: its not possible... the answer is to create case statements and hard code more.

A: The simplest way would be to use an array of pointers
and dont forget to delete the pointers ;)
class MenuSetting {

public:

char *name;
int min;
char* options[5];
int max;
int step;
int value;

};

then you may assign it this way
bool MenuSetting::setOption(char *str, unsigned int pos)
{
    if(c && p <5)
    {
        options[pos]=str;
        return true;
    }
    return false;
}

i think it would help you most if you used a smart pointer(a simple one is not that hard to implement)
and i think you can refer this site Implementing a simple smart pointer in C++ for example.
Also i think this answer would work for you https://stackoverflow.com/a/279032/2689696

A: You should really use the standard template library. It will make your life so much more meaningful, and you will have lots of extra free time to document your code!
With the latest std libraries, and c++11, your code can be simplified to look clean like the javascript snippet:
#include <string>
#include <vector>

std::vector<std::string> bluetoothOptions = {"on", "off"};
std::vector<std::string> modeOptions      = {"basic", "advanced", "config"};

// Example usage:
assert (bluetoothOptions[1] == "off");   // exanple to access strings by index
assert (modeOptions.size() == 3);        // example to determine size of vector

If you want to enforce that these strings and vectors cannot change, then use the following (this would be my preference):
const std::vector<const std::string> bluetoothOptions = {"on", "off"};
const std::vector<const std::string> modeOptions      = {"basic", "advanced", "config"};


text:
Q: Calculate distance in miles between two zip codes in BigQuery SQL? Say I have two zip codes in one row in a table. Is there a way to calculate the distance between the two zip codes?

A: Below example is for BigQuery Standard SQL
#standardSQL
WITH `project.dataset.tabel` AS (
  SELECT '91356' home, '90045' work
)
SELECT home, work,
  ST_DISTANCE(home_geo, work_geo) / 1609.34 AS distance,
  home_geo, work_geo,
  ST_MAKELINE(ST_CLOSESTPOINT(home_geo, work_geo), ST_CLOSESTPOINT(work_geo, home_geo)) line
FROM (
  SELECT home, work,
    (
    SELECT ST_GEOGFROMTEXT(zipcode_geom)
    FROM `bigquery-public-data.utility_us.zipcode_area`
    WHERE zipcode = home
    ) home_geo,
     (
    SELECT ST_GEOGFROMTEXT(zipcode_geom)
    FROM `bigquery-public-data.utility_us.zipcode_area`
    WHERE zipcode = work
    ) work_geo
  FROM `project.dataset.tabel`
)

with output
home    work    distance            ...
91356   90045   12.794149725735204  ...

Above result would be visualized as below showing both zips and line representing shortest line in between them

Note: obviously, this is not a driving distance but rather shortest distance on the map - see more details on ST_DISTANCE

A: You can try this:
SELECT
  zip1.zipcode zipcode1,
  zip2.zipcode zipcode2,
  ST_DISTANCE(zip1.geog, zip2.geog) distance
FROM
  `fh-bigquery.gis.zipcodes` zip1,
  `fh-bigquery.gis.zipcodes` zip2
WHERE
  zip1.zipcode != zip2.zipcode;


text:
Q: How can I maximize the amount of energy an antenna is receiving? Bear in mind that I am very new to electrical design and have only a beginners level circuit course under my belt.
I am trying to build an AM radio and although there are a lot of tutorials out there for this, none of them answer this specific question about designing a receiver. The best resource I have found so far is: http://www.antenna-theory.com/basics/gain.php, but it seems to be talking about sending (not receiving) signals.
I would like to know how I can make/modify a receiver so that I can maximize the amount of energy it will get from the carrier wave.
Is there a very good resource on making receivers that will explain the math and theory? Please point me in the right direction so I can gain some understanding and get through this project.

A: By the principle of reciprocity, antennas work the same way in receive and transmit directions. So if you make a directional antenna that's better at transmitting in a particular direction, it's better at receiving in that direction by the same amount.
If your goal is maximizing power received, then a useful concept is effective aperture. This is the size of the metaphorical "net" the antenna uses to capture energy. A bigger net means capturing more energy. If you are familiar at all with the term "aperture" in optics and photography, it is a similar concept.
A somewhat counter-intuitive mathematical fact is that effective aperture (\$A_{eff}\$) and gain (\$G\$) are related:
$$ G = \frac {4 \pi A_{eff} } { \lambda^2 } $$
\$\lambda\$ is the wavelength, and people tend to develop a misconception here: that the physics of energy transmission are somehow different depending on frequency. They aren't. All electromagnetic radiation decreases with distance according to the inverse square law, be it AM broadcasts, visible light, or gamma radiation. See Is free space path loss dependent on frequency? and Why is antenna aperture a function of wavelength?
What this equation is telling you is this: as frequency decreases and gain remains constant, the aperture increases. But a half-wavelength dipole for 750 kHz is also physically much larger than a half-wavelength dipole for 2.4 GHz, so although they each have the same gain, it would make sense that the 750 kHz dipole has a larger aperture.
Another counter-intuitive result is that an ideal dipole which is infinitesimally small has about the same gain (and effective aperture) as a half-wavelength dipole: 1.76 dBi compared to 2.15 dBi, respectively.
If that's true, then why don't we use infinitesimally small dipoles everywhere? We could save a lot of space. The reason is that to efficiently couple energy with this tiny antenna, you need some kind of matching network, and those parts introduce losses, degrading the efficiency of the system.
But this is still insightful: if you want to maximize received power, focus on minimizing losses first. With the tiny powers you will capture from an antenna, you probably need it to be as efficient as possible, so design for simplicity since each component adds loss. And match your load to the antenna impedance to make the transfer of energy as efficient as possible.