text:
Q: Can I add dns name in aws security group I have to connect my dynamic IP(which changes every time) to the AWS EC2 machine.
For this I mapped my public IP to the domain name(xyz.com), now I am trying to add it to security group.
But AWS security group not allowing to add DNS names.
Is it the right process to do it, if not please suggest me.

A: AWS security rules only allow IP ranges, called CIDRs, that you can update with the AWS CLI. However, you can't simply update the CIDR of an existing rule, you need to:

*

*delete the old rule: aws ec2 revoke-security-group-ingress ...

*create a new rule: aws ec2 authorize-security-group-ingress ...
Example
I've found some form of this script useful to encapsulate the steps necessary:
#!/bin/bash

# == Script Config ===================

# The rule description is used to determine the rule that should be updated.
RULE_DESCRIPTION=My-Rule-Description
SECURITY_GROUP_NAME=My-Security-Group-Name

# ====================================

OLD_CIDR_IP=`aws ec2 describe-security-groups --query "SecurityGroups[?GroupName=='"$SECURITY_GROUP_NAME"'].IpPermissions[*].IpRanges[?Description=='"$RULE_DESCRIPTION"'].CidrIp" --output text`
NEW_IP=`curl -s http://checkip.amazonaws.com`
NEW_CIDR_IP=$NEW_IP'/32'

# If IP has changed and the old IP could be obtained, remove the old rule
if [[ $OLD_CIDR_IP != "" ]] && [[ $OLD_CIDR_IP != $NEW_CIDR_IP ]]; then
    aws ec2 revoke-security-group-ingress --group-name $SECURITY_GROUP_NAME --protocol tcp --port 8080 --cidr $OLD_CIDR_IP
fi

# If the IP has changed and the new IP could be obtained, create a new rule
if [[ $NEW_IP != "" ]] && [[ $OLD_CIDR_IP != $NEW_CIDR_IP ]]; then
   aws ec2 authorize-security-group-ingress --group-name $SECURITY_GROUP_NAME --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "IpRanges": [{"CidrIp": "'$NEW_CIDR_IP'", "Description": "'$RULE_DESCRIPTION'"}]}]'
fi

Explanation
This method uses the following 3 AWS CLI commands, taken from the example above with the bash scripting removed.
1) Obtain the CIDR IP of a rule in a specific security group by the rule's description. This command uses JMESPath in the query parameter to return only the data we want:
aws ec2 describe-security-groups --query "SecurityGroups[?GroupName=='MY_SECURITY_GROUP_NAME'].IpPermissions[*].IpRanges[?Description=='MY_RULE_DESCRIPTION'].CidrIp" --output text

2) Remove rule for the old CIDR (succeeds even when rule doesn't exist):
aws ec2 revoke-security-group-ingress --group-name MY_SECURITY_GROUP_NAME --protocol tcp --port 80 --cidr 0.0.0.0/32

3) Add rule for the new CIDR (fails when rule already exists):
aws ec2 authorize-security-group-ingress --group-name MY_SECURITY_GROUP_NAME --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "IpRanges": [{"CidrIp": "1.1.1.1/32", "Description": "MY_RULE_DESCRIPTION"}]}]'

A: I have used this little bash script to poke a hole in the firewall from my current address:
#!/bin/sh
AWS_IP=$(curl http://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress --group-name my-security-group \
         --protocol tcp --port 22 \
         --cidr $AWS_IP/32

However, this results in a security group full of swiss-cheese holes from random IP addresses, so you'll want to subsequently ask the question about how to not have a security group with temporary addresses that are no longer yours. One way to answer that problem is to set up a VPN which has a (relatively) stable IP address endpoint, and then allow that single address only through the security group.

A: I create a security group for dynamic ips and each time i run my script delete the ip stored in a file.
This is my solution for windows.
SETLOCAL
@echo off
SET mypath=%~dp0
set PATH=%PATH%;"C:\Program Files\Amazon\AWSCLI\";"C:\Program Files (x86)\PuTTY\";"C:\MyApps\gnuwin32\bin"
set GROUPID=  PUT YOUR DYNAMIC SECURITY GROUP ID HERE
rem aws ec2 create-security-group --group-name dynamic_ips --vpc-id vpc-81a519e5 --description "Dynamic Ip Address"
set /p MYIP=<%mypath%\MYIP_NODELETE.txt
aws ec2 revoke-security-group-ingress --group-id %GROUPID% --protocol tcp --port 0-65535 --cidr %MYIP%/24
wget -qO %mypath%\MYIP_NODELETE.txt http://ipinfo.io/ip
set /p MYIP=<%mypath%\MYIP_NODELETE.txt
aws ec2 authorize-security-group-ingress --group-id %GROUPID% --protocol tcp --port 0-65535 --cidr %MYIP%/24
rem cat %mypath%\MYIP_NODELETE.txt
pause

A: Why not create a Bastian host on a public IP and then use that as your jump box instead?

A: Security Groups and ACLs are not able to resolve DNS hostnames.
You can use the AWS CLI to script the update of your IP dynamic address:
aws ec2 authorize-security-group-ingress --group-id  --protocol tcp --port 22 --cidr /24
http://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-sg.html

A: You can't connect a dynamic ip in the manner you want; every time your ip changes, if you want to allow it thru your security groups you will need to change the setting to your new IP.
You could write a little script that you make into an icon on your desktop however that uses the AWS API to re-allow your current ip to make it easier when it changes.


text:
Q: A Way Disable SSH for Single Node Hadoop? Where I work is using Centrify for authentication, and for some reason when i SSH into a system its not running the .bashrc / .bash_profile .  This means JAVA_HOME and a bunch of other variables do not get set when it SSHes locally to start the node.  The SAs have been useless in figuring out why and refuse to remove it from my development machine.  As of right now I'm trying to run a Hadoop instance that needs native compression libraries.  So the JAVA_LIBRARY_PATH isn't being set when it SSHes in.  And for some reason setting it in the hadoop-env.sh is not working.
Is there a way at all to run hadoop in single-node mode without using SSH?

A: Removing SSH from the scripts is more painful than adding JAVA_HOME and such into the bin/hadoop script. All deamons are started via this, so this is the main point to change this if env is not working.

A: If .bash_profile and .bashrc are not getting called, its probably because the shell is being called non-interactively by your ssh calls which has nothing to do with Centrify.
Here's an article that describes this further: http://hacktux.com/bash/bashrc/bash_profile
If you want to your .bash_profile and .bashrc to be called, you need to change your ssh calls to use an interactive shell as described below.
Why does an SSH remote command get fewer environment variables then when run manually?
Let me take you through an example.
Here's my .bashrc on a system running Centrify and OpenSSH
$ id
uid=1296041358(simon_schuster) gid=1296041358(simon_schuster) groups=1296040449(domain_u),1296041358(simon_schuster)
[simon_schuster@engcen5 ~]$ cat .bashrc
# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

# User specific aliases and functions
JAVA_HOME=/usr/local/java/
export JAVA_HOME

If I try to connect to the system using a remote ssh connection and execute the env command, this ssh connection will call a non-interactive shell and as you can see below, the JAVA_HOME variable is not shown.  That's because the .bashrc is not sourced if the shell is called non-interactively.
ssh simon_schuster@engcen5.ocean.net env
CentOS release 5.5 (Final)
Kernel 2.6.18-194.el5 on an x86_64

Password:
SHELL=/bin/bash
SSH_CLIENT=192.168.81.26 44524 22
CDC_PREW2KHOST=engcen5
USER=simon_schuster
MAIL=/var/mail/simon_schuster
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/share/centrifydc/bin
PWD=/home/simon_schuster
USER_PRINCIPAL_NAME=Simon.Schuster@OCEAN.NET
KRB5CCNAME=FILE:/tmp/krb5cc_cdc1296041358_TEcxjC
CDC_JOINED_DC=dc.ocean.net
SHLVL=1
HOME=/home/simon_schuster
CDC_JOINED_SITE=Ocean-Demo
DA_DASH_DEPTH=1
LOGNAME=simon_schuster
SSH_CONNECTION=192.168.81.26 44524 192.168.81.25 22
CDC_JOINED_ZONE=CN=Global,CN=Zones,OU=Unix,DC=ocean,DC=net
CDC_LOCALHOST=engcen5.ocean.net
CDC_JOINED_DOMAIN=ocean.net
_=/usr/bin/env

Here's the another session as the same user but this time the user logs in interactively and types the env command.  Notice the JAVA_HOME variable is displayed.  This is is because the .bashrc is sourced when an interactive (login) shell is invoked.
[simon_schuster@engcen5 ~]$ env
HOSTNAME=engcen5.ocean.net
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=192.168.81.11 49519 22
CDC_PREW2KHOST=engcen5
SSH_TTY=/dev/pts/1
USER=simon_schuster
LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
MAIL=/var/spool/mail/simon_schuster
PATH=/usr/kerberos/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/share/centrifydc/bin:/home/simon_schuster/bin
INPUTRC=/etc/inputrc
PWD=/home/simon_schuster
JAVA_HOME=/usr/local/java/
LANG=en_US.UTF-8
USER_PRINCIPAL_NAME=Simon.Schuster@OCEAN.NET
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
KRB5CCNAME=FILE:/tmp/krb5cc_1296041358
CDC_JOINED_DC=dc.ocean.net
SHLVL=1
HOME=/home/simon_schuster
CDC_JOINED_SITE=Ocean-Demo
DA_DASH_DEPTH=1
LOGNAME=simon_schuster
SSH_CONNECTION=192.168.81.11 49519 192.168.81.25 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
CDC_JOINED_ZONE=CN=Global,CN=Zones,OU=Unix,DC=ocean,DC=net
CDC_LOCALHOST=engcen5.ocean.net
G_BROKEN_FILENAMES=1
CDC_JOINED_DOMAIN=ocean.net
_=/usr/bin/env

In order to have ssh source your bash_profile and bashrc, you have to call bash with the --login option as shown below.  As you can see, the JAVA_HOME variable is now visible when executing the env command remotely via ssh.
ssh simon_schuster@engcen5.ocean.net "bash --login -c env"
CentOS release 5.5 (Final)
Kernel 2.6.18-194.el5 on an x86_64

Password:
HOSTNAME=engcen5.ocean.net
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=192.168.81.26 58672 22
CDC_PREW2KHOST=engcen5
USER=simon_schuster
LS_COLORS=
PATH=/usr/kerberos/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/share/centrifydc/bin:/home/simon_schuster/bin
MAIL=/var/spool/mail/simon_schuster
INPUTRC=/etc/inputrc
PWD=/home/simon_schuster
JAVA_HOME=/usr/local/java/
LANG=en_US.UTF-8
USER_PRINCIPAL_NAME=Simon.Schuster@OCEAN.NET
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
KRB5CCNAME=FILE:/tmp/krb5cc_cdc1296041358_qRHqro
CDC_JOINED_DC=dc.ocean.net
HOME=/home/simon_schuster
SHLVL=2
CDC_JOINED_SITE=Ocean-Demo
DA_DASH_DEPTH=2
LOGNAME=simon_schuster
SSH_CONNECTION=192.168.81.26 58672 192.168.81.25 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
CDC_JOINED_ZONE=CN=Global,CN=Zones,OU=Unix,DC=ocean,DC=net
CDC_LOCALHOST=engcen5.ocean.net
G_BROKEN_FILENAMES=1
CDC_JOINED_DOMAIN=ocean.net
_=/usr/bin/env

In summary, the fact that you're not getting your environment variable has nothing to do with Centrify and instead has to do with the fact that your shell is being called non-interactively.
Centrify is only responsible for authentication, access control and policy enforcement, and does not impact the default behavior of OpenSSH or your shells.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qualcomm QCA6174 - Wifi Unstable - Dell XPS 13 9380 - Ubuntu 20.04 Focal I have Ubuntu 20.04 installed on Dell XPS 13 9380 (Service Tag: 8SGZPV2) with Qualcomm QCA6174 wifi chip. Every 2-5 minutes, the wifi signal drops off then comes back online after a few seconds. This is a fresh install of Ubuntu Desktop through the usual methods (ie, not a custom OS/kernel build). The original OS was Windows 10 (no wifi problems), and Ubuntu was installed after a hard drive wipe (ie, not a dual-boot).
Here is my wifi hardware.
$ lspci
02:00.0 Network controller: Qualcomm Atheros QCA6174 802.11ac Wireless Network Adapter (rev 32)
$ dmesg | grep ath
[   23.571480] ath10k_pci 0000:02:00.0: enabling device (0000 -> 0002)
[   23.579850] ath10k_pci 0000:02:00.0: pci irq msi oper_irq_mode 2 irq_mode 0 reset_mode 0
[   23.862206] ath10k_pci 0000:02:00.0: qca6174 hw3.2 target 0x05030000 chip_id 0x00340aff sub 1a56:143a
[   23.862209] ath10k_pci 0000:02:00.0: kconfig debug 0 debugfs 1 tracing 1 dfs 0 testmode 0
[   23.862620] ath10k_pci 0000:02:00.0: firmware ver WLAN.RM.4.4.1-00140-QCARMSWPZ-1 api 6 features wowlan,ignore-otp,mfp crc32 29eb8ca1
[   23.927110] ath10k_pci 0000:02:00.0: board_file api 2 bmi_id N/A crc32 4ac0889b
[   24.000120] ath10k_pci 0000:02:00.0: unsupported HTC service id: 1536
[   24.020001] ath10k_pci 0000:02:00.0: htt-ver 3.60 wmi-op 4 htt-op 3 cal otp max-sta 32 raw 0 hwcrypto 1
[   24.108647] ath: EEPROM regdomain: 0x6c
[   24.108647] ath: EEPROM indicates we should expect a direct regpair map
[   24.108648] ath: Country alpha2 being used: 00
[   24.108649] ath: Regpair used: 0x6c
[   24.115986] ath10k_pci 0000:02:00.0 wlp2s0: renamed from wlan0
[   25.553827] ath10k_pci 0000:02:00.0: unsupported HTC service id: 1536

Here is my OS set up.
$ lsb_release -d
Description:    Ubuntu 20.04 LTS
$ uname -r
5.4.0-39-generic
$ apt list --installed | grep "linux-generic"
linux-generic-hwe-20.04/focal-updates,focal-security,now 5.4.0.39.42 amd64 [installed]

I've done these steps already: More wifi issues - Qualcomm Atheros QCA6174 ath10k_pci
This includes:
sudo apt-get install --reinstall linux-firmware
sudo sed -i 's/wifi.powersave = 3/wifi.powersave = 2/' /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf

There were no errors. I rebooted. And the problem persisted.
Another thread (WiFi DELL XPS 13 9360 keeps disconnecting with QCA6174 802.11ac Wireless Network Adapter) said to install a custom kernel module. I didn't do that, but I did run a few steps to see if it would help.
sudo modprobe -r ath10k_pci ath10k_core
sudo modprobe ath10k_pci
sudo modprobe ath10k_core

The problem of the wifi signal dropping and coming back up persisted.
Another thread (Qualcomm QCA6174 unstable wifi and bluetooth) also mentioned installing a custom firmware (https://github.com/thebitstick/surfacego-wifi).
I fear bricking my laptop if I try something for a different device altogether. And so I haven't installed any custom kernel modules or firmware. Is this really the answer? If so, which one?
Please help.

A: I tried new firmwares and many other different solutions with no avail on Ubuntu 20.10. Firmware crashes and disconnecting still kept happening.
Finally, I wrote following bash script which I run on startup. It will automatically reconnect to AP when connection is lost. Maybe it will help you too.
You might need to install fping utlity
sudo apt install fping

Edit name of your WLAN interface on line 2 and run script as follows:
#!/bin/bash
interface=wlp58s0
ping_interval=5

while /bin/true; do
    connect=`iwconfig $interface | grep ESSID:off`
    if [ "${connect}" ]; then
            echo "Connect to some AP first.";
            sleep 10;
    else
            startdate=`date`;
            ip=`ip route show 0.0.0.0/0 dev $interface | cut -d\  -f3`
            reconnect=0
            essid=`iwgetid $interface -r`

            echo -e "Monitoring WLAN connection \n WLAN interface: $interface \n ESSID: $essid \n Default gateway: $ip \n Ping interval: $ping_interval s"

            while /bin/true; do
            up=`fping -r 1 $ip | grep alive`
            connect=`iwconfig $interface | grep ESSID:off`
            if [ -z "${up}" ] && [ -z "${connect}" ]; then
                    echo "Warning: connection lost at $(date)"
                    ((reconnect=$reconnect+1))
                    echo "Reconnecting..." &&
                    nmcli dev connect $interface &&
                    echo "Done! Connection on at $(date)"
                    echo -e "Reconnected $reconnect times from $startdate. \n"
            fi
            sleep $ping_interval
            done
    fi
done

A: I too had wifi issues with the same laptop on ubuntu 18.04. I did not install 20.04 but the problem was the same as yours. It only occurred with my router at home.
After a lot of mails and phone calls with Dell I understood they could not do anything about it. They should have not sold this device with ubuntu in the first place.
Simple solution for me was to change my router. Problem partly solved as I might have this problem somewhere else at some point. I will search a bit more before buying a notebook with Ubuntu preinstalled next time.


text:
Q: How to select the closest data to the given time for each group I'm using InfluxDB 1.4, and here's my task
1) find the closet value for each IDs.
2) Do 1) for every hour

For example,
select id, value, time from myTable where time = '2018-08-14T00:00:00Z' group by id;
select id, value, time from myTable where time = '2018-08-14T01:00:00Z' group by id;
....
select id, value, time from myTable where time = '2018-08-14T23:00:00Z' group by id;

then, some id have value at each o'clock but others don't. In this case, I want to get the closest row to the give time '2018-08-14T14:00:00Z', like as '2018-08-14T14:00:01Z' or '2018-08-14T13:59:59Z'
and I don't want to query 24 times for each hour. Can I do this task with group by time, id, or something else?

A: Q: I would like to select the point data closest to the hourly boundary. Is there a way I can do this without having to query 24 times for each day? Will group by time be any help on this?
A:

Will group by time be any help on this?

Unfortunately the group by time function will not be much help to you as it  requires the query to have an aggregation function. What the group by time function does is that it groups all data that falls within the interval into one single record by using the aggregation function like sum, mean etc to tabulate the combined row's values.

Is there a way I can do this without having to query 24 times for each
  day?

To the best of my knowledge, I don't think influxdb 1.5 has any way to build a one liner query for this task. Maybe there is something in 1.6, i'm not sure. Haven't tried that.
At the moment I think your best solution today is to  build a query that uses the time filter, order by and limit functions e.g.
select * from uv where time >= '2018-08-18T14:00:00Z' and time < '2018-08-18T15:00:00Z' order by desc limit 1;
The query above means that you are selecting all the points within 2pm to 3pm and then order them by descending order but only return the first row, which is what you want.
If for some reason you can only do 1 HTTP request to influxdb for the hourly data on a particular day. You can bundle up the 24 queries into one big query using the ; seperator and retrieve the data in 1 transaction. E.g.
select * from uv where time >= '2018-08-18T14:00:00Z' and time < '2018-08-18T15:00:00Z' order by desc limit 1; select * from uv where time >= '2018-08-18T15:00:00Z' and time < '2018-08-18T16:00:00Z' order by desc limit 1; select * from uv where time >= '2018-08-18T16:00:00Z' and time < '2018-08-18T17:00:00Z' order by desc limit 1;
Output:
name: uv
time                tag1 id         value
----                -------- --         -----
1534603500000000000 apple  uv 2
1534607100000000000 apple  uv 1
1534610700000000000 apple  uv 3.1


text:
Q: C# Entidad con id Guid no me permite registrar en base de datos he modificado la pregunta a raíz de sus peticiones: primeramente, aclarar que mi base de datos la he generado mediante el wizard que posee Visual Studio (2015 es el que uso) con la vía de ADO.NET Entity Model (ver imagen adjunta), en el cual diseñé mis entidades y luego las generé sobre la base de datos (aquí les pido una valoración de esta vía).

Las propiedades que puse en el diseño sobre la entidad son estas:

Luego de la generación del DDL, este es el código SQL de la tabla Reloj (nombrada por el EF como RelojSet)
CREATE TABLE [dbo].[RelojSet] (
   [Id] uniqueidentifier  NOT NULL,
   [Direccion] nvarchar(max)  NOT NULL,
   [Puerto] nvarchar(max)  NOT NULL,
   [Descripcion] nvarchar(max)  NOT NULL,
   [Activo] bit  NOT NULL,
   [LastUpdate] datetime  NULL
);
GO

El contexto es el siguiente (no he tocado nada, esta autogenerado por EF):
public partial class ZKTDataBaseContainer : DbContext
{
    public ZKTDataBaseContainer()
        : base("name=ZKTDataBaseContainer")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Reloj> RelojSet { get; set; }
    public virtual DbSet<Trabajador> TrabajadorSet { get; set; }
    public virtual DbSet<Marcaje> MarcajeSet { get; set; }
    public virtual DbSet<Settings> SettingsSet { get; set; }
}

El mapeo creado en modelo es el que les referí anteriormente:
public partial class Reloj
{
    public Reloj()
    {
        this.Marcaje = new HashSet<Marcaje>();
    }

    public System.Guid Id { get; set; }
    public string Direccion { get; set; }
    public string Puerto { get; set; }
    public string Descripcion { get; set; }
    public bool Activo { get; set; }
    public Nullable<System.DateTime> LastUpdate { get; set; }

    public virtual ICollection<Marcaje> Marcaje { get; set; }
}

En mi controlador, instancio un objeto de tipo Reloj, y trato de persistirlo:
public ActionResult Create(FormCollection collection)
    var reloj = new Reloj
    {
        Activo = collection.Get("Activo").Equals("on"),
        Descripcion = collection.Get("Descripcion"),
        Direccion = collection.Get("Direccion"),
        Puerto = collection.Get("Puerto"),
        LastUpdate = DateTime.Now,
        Id = Guid.newGuid(),   // => No funciona
        // Id = new Guid() => No Funciona
        // Id = Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301") => Tampoco
        // Id = Guid.TryParse("3F2504E0-4F89-11D3-9A0C-0305E82C3301") => Menos
    };

    try{
        using (var db = new ZKTDataBaseContainer())
        {
            db.RelojSet.Add(reloj);
            db.SaveChanges();
        }
    }catch (Exception ex){

    }
//....
}

El error generado esta relacionado con el identificador Guid de la entidad Reloj:
"No se puede insertar el valor NULL en la columna 'Id', tabla 'ZKTDB.dbo.RelojSet'. La columna no admite valores NULL. Error de INSERT.\r\nSe terminó la instrucción."
Que estoy olvidando aqui?

A: Como recomendación el GUID lo puedes generar automaticamente desde tu base de datos utilizando la instrucción NEWID() por ejemplo:
CREATE TABLE [dbo].[RelojSet]
(
    [Id] UNIQUEIDENTIFIER PRIMARY KEY DEFAULT (NEWID()),
    [Activo] BIT NULL,
    [Descripcion] NVARCHAR(100) NOT NULL,
    [Direccion] NVARCHAR(100) NOT NULL,
    [Puerto] NVARCHAR(MAX) NOT NULL,
    [LastUpdate] DATETIME NULL DEFAULT GETDATE()
)

Asi ya no es necesario asignar la propiedad Id dentro de tu modelo ya que esta la genera directamente la base de datos.

A: Recomendacion: Utilizar NEWSEQUENTIALID() en vez de NEWID() cuando es columna clave (primary key), por cuestiones de velocidad (temas de paginamiento de indeces y creacion * verificacion de la existencia, ya que estara ORDENADO por creacion del Id, con NEWID() son todos alteatorios) O sea es un tema mas fisico y de organiaciond de DB, igualmente sigure creando identificadores GUID
Textual de docs/ayuda:

Cuando una columna de GUID se utiliza como identificador de fila, el uso de NEWSEQUENTIALID puede ser más rápido que el uso de la función NEWID. La razón es que la función NEWID causa actividad aleatoria y utiliza menos páginas de datos en caché. El uso de NEWSEQUENTIALID también ayuda a rellenar por completo las páginas de datos y de índices

En tu ejemplo seria la columna Id de la siguiente manera
[Id] UNIQUEIDENTIFIER PRIMARY KEY DEFAULT (NEWSEQUENTIALID()),

Enlaces que te pueden ayudar

*

*NEWSEQUENTIALID (Transact-SQL)


text:
Q: FaceletContext is Null I have a JSF 2.0 project that I am unable to obtain a FaceletContext from.
Here is the setup from my web.xml:
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>

<context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>true</param-value>
</context-param>

<context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
</context-param>

<context-param>
    <param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
    <param-value>false</param-value>
</context-param>

<context-param>
    <param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
    <param-value>/index.xhtml</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
</context-param>

<context-param>
    <param-name>javax.faces.application.CONFIG_FILES</param-name>
    <param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

I can obtain the FacesContext, but not the FaceletContext. The following lines of code are where the issue lies:
            FacesContext fctx = FacesContext.getCurrentInstance(); //works
    //FaceletContext f2ctx = (FaceletContext) fctx.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
    FaceletContext f2ctx = (FaceletContext) fctx.getELContext().getContext(FaceletContext.class);

Can anyone assist?
Update:
The above was a snippet from my overall goal: loading a facelet file containing a dialog on demand, then add it to a parent to display. The code below is incomplete, but should explain what I'm getting at. Note that the app uses the Primefaces library, hence the RequestContext object.
public void launch() {

    form.getChildren().clear();

    FacesContext fctx = FacesContext.getCurrentInstance();
    for (Object o: fctx.getAttributes().keySet()) {
        System.out.println(o.toString());
    }

    FaceletContext f2ctx = (FaceletContext) fctx.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
    //FaceletContext f2ctx = (FaceletContext) fctx.getELContext().getContext(FaceletContext.class);
    dialog = new Dialog();

    try {
        f2ctx.includeFacelet(dialog, "/WEB-INF/facelets/dialog/manager.xhtml");
        form.getChildren().add(dialog);
    } catch (IOException ex) {
        log.debug(ex.toString());
    }

    RequestContext.getCurrentInstance().update("mainPageCenterForm");
}

A: It will be null when you try to access it before the view is ever been built. For example, during the beforePhase of RESTORE_VIEW phase. Rearrange your code logic. It's not clear what's the functional requirement is and where exactly you're trying to access it, so I can't give a more suited answer.

Unrelated to the concrete problem, the javax.faces.FULL_STATE_SAVING_VIEW_IDS context param is ignored when the partial state saving is disabled. Perhaps that was not your intent? See also this related answer Should PARTIAL_STATE_SAVING be set to false?


text:
Q: Lost notifications after installing XFCE Today I noticed that I don't see any notifications. Is there a way to reset notification settings. It happend after I installed xfce on my Ubuntu 12.04.

A: Do you have Ubuntu's default notify-osd daemon installed? Maybe it is in conflict with XFCE's native notification daemon..
Apparently, when it comes to notification daemons, there can be only one.. unfortunately, the right one does not get run, and the packages aren't marked to conflict. XFCE developers closed the bug report, so I assume that according to XFCE developers, you are not supposed to have Gnome and XFCE installed on the same system.
Why not just remove one? XFCE's notification daemon isn't tied to XFCE AFAIK (though I haven't actually used it under any DE other than XFCE), although it does rely on xfconf. Both NotifyOSD and xfce4-notifyosd are both implementations of the FreeDesktop Notification Standard so notifications would work equally well under any of them (although I prefer xfce4-notifyosd as it provides an 'X' button on notifications without patching and it has support for buttons on notifications).
Since NotifyOSD is totally unconfigurable (and it's meant to be "just there" hence why you can't close its notifications manually and why it doesn't support buttons on notifications), XFCE can't change its settings. To do what you want, you can either get rid of NotifyOSD and use XFCE's notification daemon (which will start once NotifyOSD goes) or get rid of xfce4-notifyosd and use leolik's patched NotifyOSD which does let you set the position of its notifications.
If you're running Precise (which is what I suspect as xfce4-notifyosd in Natty would actually conflict because they share a file), however, leolik's PPA does not have a Precise build.
Long-story-short...remove one of the notify applications.
source


text:
Q: Finding the biggest centered square from a landscape or a portrait UIImage and scale it to a size I need to find the biggest centered square from a portrait or a landscape image scaled to a size.
E.g. if I get an image of size 1200x800 and I need to get the centered square down to size 300x300.

A: I found an answer on this question on stackoverflow which has been widely copied. However that answer is incorrect, so want to post the correct answer which is as follows:
+ (UIImage*) cropBiggestCenteredSquareImageFromImage:(UIImage*)image withSide:(CGFloat)side
{
  // Get size of current image
  CGSize size = [image size];
  if( size.width == size.height && size.width == side){
    return image;
  }

  CGSize newSize = CGSizeMake(side, side);
  double ratio;
  double delta;
  CGPoint offset;

  //make a new square size, that is the resized imaged width
  CGSize sz = CGSizeMake(newSize.width, newSize.width);

  //figure out if the picture is landscape or portrait, then
  //calculate scale factor and offset
  if (image.size.width > image.size.height) {
    ratio = newSize.height / image.size.height;
    delta = ratio*(image.size.width - image.size.height);
    offset = CGPointMake(delta/2, 0);
  } else {
    ratio = newSize.width / image.size.width;
    delta = ratio*(image.size.height - image.size.width);
    offset = CGPointMake(0, delta/2);
  }

  //make the final clipping rect based on the calculated values
  CGRect clipRect = CGRectMake(-offset.x, -offset.y,
                               (ratio * image.size.width),
                               (ratio * image.size.height));

  //start a new context, with scale factor 0.0 so retina displays get
  //high quality image
  if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
  } else {
    UIGraphicsBeginImageContext(sz);
  }
  UIRectClip(clipRect);
  [image drawInRect:clipRect];
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return newImage;
}

Incorrect answer which I found earlier is as follows:
+ (UIImage*) cropBiggestCenteredSquareImageFromImage:(UIImage*)image withSide:(CGFloat)side
{
  // Get size of current image
  CGSize size = [image size];
  if( size.width == size.height && size.width == side){
    return image;
  }

  CGSize newSize = CGSizeMake(side, side);
  double ratio;
  double delta;
  CGPoint offset;

  //make a new square size, that is the resized imaged width
  CGSize sz = CGSizeMake(newSize.width, newSize.width);

  //figure out if the picture is landscape or portrait, then
  //calculate scale factor and offset
  if (image.size.width > image.size.height) {
    ratio = newSize.width / image.size.width;
    delta = (ratio*image.size.width - ratio*image.size.height);
    offset = CGPointMake(delta/2, 0);
  } else {
    ratio = newSize.width / image.size.height;
    delta = (ratio*image.size.height - ratio*image.size.width);
    offset = CGPointMake(0, delta/2);
  }

  //make the final clipping rect based on the calculated values
  CGRect clipRect = CGRectMake(-offset.x, -offset.y,
                               (ratio * image.size.width) + delta,
                               (ratio * image.size.height) + delta);

  //start a new context, with scale factor 0.0 so retina displays get
  //high quality image
  if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
  } else {
    UIGraphicsBeginImageContext(sz);
  }
  UIRectClip(clipRect);
  [image drawInRect:clipRect];
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return newImage;
}

The problem with this code is that it does not crop correctly.
Both the codes can be tried on following image:
https://s3.amazonaws.com/anandprakash/ImageWithPixelGrid.jpg
Correct Algo generates following image on the above base url:
https://s3.amazonaws.com/anandprakash/ScreenshotCorrectAlgo.png
Wrong Algo generates following image on the above base url - notice the extra 50px on the width on each side.
https://s3.amazonaws.com/anandprakash/ScreenshotWrongAlgo.png

A: Same answer above as a Swift extension on UIImage:
private extension UIImage {
    func cropBiggestCenteredSquareImage(withSide side: CGFloat) -> UIImage {
        if self.size.height == side && self.size.width == side {
            return self
        }
        let newSize = CGSizeMake(side, side)
        let ratio: CGFloat
        let delta: CGFloat
        let offset: CGPoint
        if self.size.width > self.size.height {
            ratio = newSize.height / self.size.height
            delta = ratio * (self.size.width - self.size.height)
            offset = CGPointMake(delta / 2, 0)
        }
        else {
            ratio = newSize.width / self.size.width
            delta = ratio * (self.size.height - self.size.width)
            offset = CGPointMake(0, delta / 2)
        }
        let clipRect = CGRectMake(-offset.x, -offset.y, ratio * self.size.width, ratio * self.size.height)
        if UIScreen.mainScreen().respondsToSelector(#selector(NSDecimalNumberBehaviors.scale)) {
            UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
        } else {
            UIGraphicsBeginImageContext(newSize);
        }
        UIRectClip(clipRect)
        self.drawInRect(clipRect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}


text:
Q: Getting error trying to display string split on new lines - Ruby on Rails I have the following code:
<% @recipe.instructions.each do |instruction| %>

<%= instruction %>

<% end %>

I get the following error: undefined method 'each' for #<String:0xa354eb8>
@recipe.instructions is defined as text
Please help!
Reese

A: Use each_line instead of each. String#each has been removed in ruby 1.9, each_line works with all ruby versions.

A: What about String#each_line? It should work with both Ruby 1.8 and 1.9.


text:
Q: Laravel Dompdf attachment coming Unable to JSON encode payload. Error code: 5 I have written below code in Mail/Mails.php file build function.
return $this->from(config('app.FROM_EMAIL'),config('app.MAIL_FROM_NAME'))
                    ->subject($this->subject)
                    ->view('emails.generalmail')
                    ->attachData($this->attach,'file_pdf.pdf');

Error

Unable to JSON encode payload. Error code: 5

I used Dompdf email send with attachment.

A: You can do it without saving the file to disk using the function
->attachData($this->attach,'file_pdf.pdf'). The error is thrown because php doesnt know how to serialize the binary pdf file data to json. What you need to do is generate the data $this->attach in your mail files handle function, not the constructor. That way php doesnt have to serialize it:
```
public function handle() {
    $pdf = PDF::loadView('pdf_view', $data);
    return $this->from(config('app.FROM_EMAIL'),config('app.MAIL_FROM_NAME'))
        ->subject($this->subject)
        ->view('emails.generalmail')
        ->attachData($pdf->output(),'file_pdf.pdf');
}```

A: I'm not sure what version of Laravel you are on so it could be slightly different but you need to use the attach function rather than attachData
return $this->from(config('app.FROM_EMAIL'),config('app.MAIL_FROM_NAME'))
                    ->subject($this->subject)
                    ->view('emails.generalmail')
                    ->attach('[PATH TO FILE]');

See more here: Laravel Mail Docs
Change the version at the top.


text:
Q: Two folders with weird names with huge size. What are those? What should I do with them? I have two folders in my WinDrive (i.e. the C drive. There details are:
Name of Folder1 - 7bf7d36518538dd519e14b5f
  3.85 GB (4,14,42,50,880 bytes) :: 50,287 Files, 6,782 Folders
Name of Folder2 - c077d2de493f37d8df
4.62 GB (4,97,01,76,512 bytes) :: 31,856 Files, 15,990 Folders
I don't know what to do with them. Is this encryption? If yes, then how can I know their real names? Can I delete them? What are they here for?
On Google search, I found that these may contain some Windows7-SP1 files.
I tried renaming/removing those, showed that the process was in use. Tried all the hashes to decode the string, google searched with names of all the major subfolders/files inside the folders.
Also tried uploading few files and applications to VirusTotal Nothing popped up.. I'm using Windows 7 Home Premium

A: There's no need to download an antivirus-antimalware. Folders with long random file names are temp folders made by installers. You can delete them anytime.

A: First of all, I would suggest you run an antivirus and/or an anti-malware check on your computer first. I haven't had stumbled upon something like that and chances are that they're some kind of the result of the presence of malware. Here are some useful resources:
Anti-malware:

*

*Adwcleaner

*Malwarebytes
If they don't trow any alerts on those directories or the files within them, they're probably some files some application you have installed generated. Here are some steps to know whether they're harmful or necessary:

*

*Change their names or locations, adding a .bak at the end of the filename usually works. Try to do this from secure mode if they're blocked or in use.

*Check if your applications still work fine without them. If you notice an important or a trusted application broke, just rename them to their original names and leave them there. They're necessary.

If everything works fine but they can't be deleted or regenerated, it may be some malware that slipped through your previous tests. In that case:

*

*Look for suspicious processes and startup applications and services on your machine. Disable or uninstall them. If that doesn't work, find the executables involved and delete them from another machine or even from a Linux Live Distro (to avoid access or permissions issues).


text:
Q: In Google BigQuery what is the benefit of ARRAY of STRUCT vs STRUCT of ARRAY? I'm just getting to grips with ARRAYS and STRUCT in BigQuery
I'm wondering why one would choose this formatting
SELECT [STRUCT('Alice' AS col_1, 'Bob' AS col_2),STRUCT('Charlie' AS col_1, 'David' AS col_2)] AS names;

over formatting like this
SELECT STRUCT(['Alice','Charlie'] AS col_1, ['Bob','David'] AS col_2) AS names;

output 1
for both the output looks the same. What would be an example of why you would use one over the other? To me the first example makes more sense because I'd want Alice and Bob to be on the same record and it's more clear in the first example. However I've seen in Google's Vertex AI prediction output they use the second example. I.e. when outputting binary predictions they output as
SELECT STRUCT([0,1] AS class, [0.8,0.2] AS col_2) AS prediction;

instead of
SELECT [STRUCT(0 AS class, 0.8 AS prediction),STRUCT(1 AS class, 0.2 AS prediction)] AS names;

output 2
When is the right time to use each?

A: It should be based on what a row/entity represents.
In your first example, each element of the array could be a pair/team and you can add as many as you want.  Alice and Bob are pair 1, Charlie and David are pair 2...
The schema would be:
names (repeated field - struct)
 - col_1 (string)
 - col_2 (string)

In your second example, you have an entity with two types of names. An example here would be a list of names you like and names that you don't like. So Alice and Charlie would be liked (col_1) and you can add as many as you want to this list, on the other side Bob and David would be names that you don't like (and you can add as many here as well).
Schema.
names.col_1  (repeated field - string)
names.col_2  (repeated field - string)

In JSON format:
Example 1: [{"col_1":"Alice", "col_2":"Bob"}, {"col_1":"Charlie", "col_2":"David"}]
Example 2: {"col_1":['Alice', 'Charlie'], "col_2":["Bob", "David"]}


text:
Q: Linux Delete Files Older Than and the Same Time Smaller Than I use this command to delete MP3 files older than 90 days.
find MP3/ -type f -name "*.mp3" -mtime +90 -delete

I want to make it delete those older than 3 days but with file size less than 100KB.
How to write the arguments for < 100KB and is -size good to go or should I use something else as as far as I know the file size itself is different that the size on the disk...
find MP3/ -type f -name "*.mp3" -mtime +3 -size xxx -delete

Thanks a lot!

A: Simply using -size should be fine for your use case. The whole command would look like this:
find MP3/ -type f -name "*.mp3" -mtime +3 -size -100k -delete


text:
Q: Train EAST text detector on custom data How can I train the EAST text detector on my custom data. There aren't any blogs online that shows step by step procedure to do the same. What I have currently.
I have a folder that contains all the images and corresponding xml file for each of our images that tells where our text are located.
Example :
<annotation>
    <folder>Dataset</folder>
    <filename>FFDDAPMDD1.png</filename>
    <path>C:\Users\HPO2KOR\Desktop\Work\venv\Patent\Dataset\Dataset\FFDDAPMDD1.png</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>839</width>
        <height>1000</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>522</xmin>
            <ymin>29</ymin>
            <xmax>536</xmax>
            <ymax>52</ymax>
        </bndbox>
    </object>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>510</xmin>
            <ymin>258</ymin>
            <xmax>521</xmax>
            <ymax>281</ymax>
        </bndbox>
    </object>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>546</xmin>
            <ymin>528</ymin>
            <xmax>581</xmax>
            <ymax>555</ymax>
        </bndbox>
    </object>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>523</xmin>
            <ymin>646</ymin>
            <xmax>555</xmax>
            <ymax>674</ymax>
        </bndbox>
    </object>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>410</xmin>
            <ymin>748</ymin>
            <xmax>447</xmax>
            <ymax>776</ymax>
        </bndbox>
    </object>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>536</xmin>
            <ymin>826</ymin>
            <xmax>567</xmax>
            <ymax>851</ymax>
        </bndbox>
    </object>
    <object>
        <name>text</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>792</xmin>
            <ymin>918</ymin>
            <xmax>838</xmax>
            <ymax>945</ymax>
        </bndbox>
    </object>
</annotation>

Also I have the parsed xml file for each one of my images in the format which is used to train YOLO models.
Example
C:\Users\HPO2KOR\...\text\FFDDAPMDD1.png 522,29,536,52,0 510,258,521,281,0 546,528,581,555,0 523,646,555,674,0 410,748,447,776,0 536,826,567,851,0 792,918,838,945,0 660,918,706,943,0 63,1,108,24,0 65,51,110,77,0 65,101,109,126,0 63,151,110,175,0 63,202,109,228,0 63,252,110,276,0 63,303,110,330,0 62,353,110,381,0 65,405,109,434,0 90,457,110,482,0 59,505,101,534,0 64,565,107,590,0 61,616,107,644,0 62,670,103,694,0 62,725,104,753,0 63,778,104,804,0 62,831,100,857,0 87,887,106,912,0 98,919,144,943,0 240,916,284,943,0 378,915,420,943,0 520,918,565,942,0
C:\Users\HPO2KOR\...\text\FFDDAPMDD2.png 91,145,109,171,0 68,192,106,218,0 92,239,111,265,0 69,286,108,311,0 92,333,107,357,0 66,379,110,405,0 90,424,111,451,0 69,472,107,497,0 91,518,109,545,0 66,564,109,590,0 90,613,110,637,0 121,644,140,670,0 279,643,322,671,0 446,645,490,668,0 615,642,661,669,0 786,643,831,667,0 954,643,997,672,0 820,22,866,50,0 823,73,866,103,0
C:\Users\HPO2KOR\...\text\FFDDAPMDD3.png 648,1,698,30,0 68,64,129,91,0 55,144,128,168,0 70,218,129,247,0 56,300,127,326,0 71,377,125,404,0 58,459,127,482,0 109,535,130,560,0 140,568,160,594,0 344,568,382,594,0 563,566,581,591,0 760,568,800,593,0 982,569,1000,591,0

What is the procedure to train this EAST text detector for my custom dataset.
I am on windows.

A: According to the documentation in the readme file, custom training the keras implementation of EAST requires a folder of images with an accompanying text file for each image named gt_IMAGENAME.txt. (Replace IMAGENAME with the name of the image it maps to.)
In each text file, "the ground truth is given as separate text files (one per image) where each line specifies the coordinates of one word's bounding box and its transcription in a comma separated format." This quotation is from https://rrc.cvc.uab.es/?ch=4&com=tasks, which is linked in the read me to the tensorflow implementation of EAST at https://github.com/argman/EAST. The bounding box is expressed as coordinates for the four corners.
You seem to have all the information you need to construct training data in the right format. There could be a tool out there to convert everything, but a quick python script will work just fine as well. Something like ...

*

*Loop all xml files

*For each xml file, create a text file named as the documentation requires

*Use BeautifulSoup to parse xml

*Use find_all to get all object tags

*Use the xmin, xmax, ymin, and ymax values to express the x,y coordinates of all corners. (upper-left is xmin, ymax; upper-right is xmax, ymax; etc.) The order, based on https://github.com/argman/EAST/blob/master/training_samples/img_1.txt, appears to be lower-left, lower-right, upper-right, upper-left

*For each object tag, write a new line in the text file with the following format:
x1, y1, x2, y2, x3, y3, x4, y4, transcription or x1, y1, x2, y2, x3, y3, x4, y4, ### (followed by a \n for newline)

*run python train.py with all the command line arguments set the way the "execution example" is setup, but change the value after --training_data_path= to your path


text:
Q: Is there any way to loop through range with for/in in delphi? type
  TRange = MIN_VALUE..MAX_VALUE;

Is there any way to loop through this range using for/in loop?
for rangeValue in TRange do
  smth

Or should i loop through it like that:
for rangeValue := Low(TRange) to High(TRange) do
  smth

A: It is not possible to use for/in loops with subrange types. You will have to use the traditional for loop syntax.

A: As of 2022 ... This works in at least 10.2 onwards ...
program Project1;
{$APPTYPE CONSOLE}

type
  TRange = 0..9;

begin
  for var rangeValue in [low(TRange)..high(TRange)] do write('*');

  readln;
end.

but what you asked for works right now in FPC ... ( https://godbolt.org/z/9zrYb9xY7 )
program output;

type
  TRange = 0..9;
var
  rangeValue : integer;

begin
  for rangeValue in TRange do write('*');
end.


text:
Q: FTP Client with directory monitoring? Are there any FTP clients that can monitor a directory and upload any files placed in it?

A: I think WinSCP had some functionality for that. Can't say how well it works becuase I've never used it, but it's worth a look.
EDIT: I think this is the feature: Keep remote directory up to date

A: WinSCP does not always work and is slow on detecting changes.
If found a faster alternative, not open source, but freeware.
http://beanland.net.au/autover/
Uploads the changed file within seconds after it has changed.


text:
Q: move form fields up or down dynamically Lets say I have a form field. Also I can dynamically add more fields, can I swap them by clicking on a link or button (up and down) using JS or jQuery?

A: The following functions that can help in adding elements: .append() to add after an element, .prepend() to add before an element.
For swapping elements there's already a post here.

A: Here's an old-school approach (JS):
http://www.nuff-respec.com/external/javascriptgui.html


text:
Q: "Error debug" in the moment when I set a new formula I'm trying to insert a formula in a cell but Appear an error when I set my own function. Anyone can explain me which it's the reason.
Thank
Sheets("market").Select
Range("M2").Select
ActiveCell.Formula ="=IF(DatoInformado(Bread!H9);0;1)"


text:
Q: jQuery: Record element changes in Array and check how it was by its index Every click is one step and will add a child div in .test, I keep all the element changes in step array
I wanted it to look like this:
Array step [0]        = before click,
Array step [0,01]     = after one click,
Array step [0,01,012] = aftert two click

but it works like this:
Array step [0]        = before click,
Array step [0,11]     = after one click,
Array step [0,11,222] = aftert two click

fiddle example
HTML:

<button type="button" onclick="change()">Count Child Element</button>

javascript:
var step =[];               // step is a record of changes in #test.
step.push($('.test'))        //step[0] is status of .test at very beginning.
$('#result').append(step[0][0].childElementCount+"
") // #result showing how many child element in #test
        var change = function (){
        $('.test').append('
t
')       //every click will a append
 in #test
        step.push($('.test'))                    // record this move in step[]
        console.log('step length',step.length)   // total moves
        for ( var i = 0; i < step.length; i++ ) {
        $('#result').append(step[i][0].childElementCount)
        }
        $('#result').append("
")}

Thank you very much for your help in advance.

A: Your loop iterations (i) should be based on childElementCount instead of the step array length.
I changed your code to get the last element in the array with step[step.length-1], and changed the for loop to stop when it hits last childElementCount. I also called change() explicitly to let it do the work of creating and rendering the first element for you to avoid duplicating code.
Fixed Fiddle: http://fiddle.jshell.net/8sbq0y0k/
Fixed code:

var step = []; // step is a record of changes in #test.
function change() {
    $('#test').append('
t
') //every click will a append
 in #test
    step.push($('#test')) // record this move in step[]
    console.log('step length', step.length) // total moves
    for (var i = 0; i < step[step.length-1][0].childElementCount; i++) {
        $('#result').append(i.toString())
    }
    $('#result').append("
")
}
change(); // let change do the work for you

<button type="button" class="btn btn-warning pull-right" onclick="change()">Count Child Element</button>


text:
Q: Resize a picturebox by mouse I'm developing a WPF app and I'm trying to resize a picturebox by mouse like that
http://i54.tinypic.com/vkf0z.jpg
how can I do that?

A: There are several ways to achieve that, one of it would be to use adorners like described in this post.


text:
Q: JMeter - Assert based on percentile I know JMeter have some custom properties that store 90, 95 and 99 percentile (if I'm not wrong, aggregate_rpt_pct1, 2 and 3 respectively).
My question is: Is there any assertion where I can retrieve this property to validate against a expected value? Currently I'm running locally, but will have it running on Azure Devops eventually.

A: I don't think it's achievable with vanilla JMeter, you can consider using Taurus tool as a wrapper for your JMeter test.
Taurus provides flexible and powerful Pass/Fail Criteria subsystem where you can define the percentiles either for separate sampler/transaction labels or for the overall tests and if it exceeds the defined threshold - Taurus will return non-zero exit status code so Azure Devops pipeline will fail automatically.


text:
Q: how to audioread mp3 files one after the other from the same folder in Matlab? Is using "for" loop helpful? If I have mp3 files in one folder in Matlab , and I want to use the command audioread in a way that will make the mp3s play one after the other.
I used the following:
[y,fs]=audioread('001.mp3')
sound(y,fs)

This plays the sound for a signal mp3 what function or thing I can do to make the next mp3 to play after each other?

A: There are two possibilities. Assuming you have multiple audio files with the same sampling rate, you can simply append them:
sound([y1;y2],fs1)

Another alternative is to use pause to wait until the first sound has finished:
sound(y1,fs1);
pause(size(y1,1)/fs);
sound(y2,fs2);


text:
Q: Why no code insight for Grails and Groovy on Eclipse STS? We are experimenting with Grails development on Eclipse STS, and one of the most annoying problems is that, unlike Java code, there does not appear to be any code insight features for Grails and Groovy classes and methods. Only after compiling and running a Grails web app do we find out that a method or field name does not exist.
Seriously, there has to be something out there for minimal code insight (hoping).

A: I am sure that STS can in fact do this for you, it is basically what its Grails support is all about. Are you sure you have installed the right plugins? Documentation on this subject is right here: [1]: http://www.grails.org/STS+Integration
Side note: while STS does a decent job, I have been a happy user of IntelliJ IDEA Ultimate edition and have never looked back to eclipse once i switched :)


text:
Q: AngularJS fetch the data from WebApi - errors not showing I have encountered a similar issue for my all example programs with angularJS fetch data from the WebApi. I think there is nothing to do with my code, but some settings that may be I ignored, please help me check it:
here is my web api:
URL:http://localhost:1883/api/Subcriber
and return the data:

Html body:

            ID
            Email ID ( Double click to update)
            Subscribed Date

                {{sub.SubscriberID}}
                {{sub.MailID}}
                {{sub.SubscribedDate}}

                    <input type="button" id="Delete" value="Delete" data-ng-click="dltSubscriber(sub.SubscriberID)" />

        Sbscribe here
        <input type="email" class="form-control" id="email" placeholder="Enter email" [required="string" ] data-ng-model="mailid" />

    <button type="button" class="btn btn-default" data-ng-click="saveSubs();">Submit</button>

AngularJS Module:
    var app;
(function () {
app=angular.module('APIModule', []);
})();

AngularJS Service:
app.service("APIService", function ($http) {
this.getSubs = function () {
    var url = 'api/Subscriber';
    return $http.get(url).then(function (response) {
        return response.data;
    });
}

AngularJS Controller:
        app.controller('APIController', function ($scope, APIService) {
getAll();
function getAll() {
    var servCall = APIService.getSubs();
    servCall.then(function (d) {
        $scope.subscriber = d.data;
    }, function (error) {
        $log.error('Oops! Something went wrong while fetching the data.')
    })
}
})

After running, there is no error information from browser debug window. It is too strange, whether I need to publish my webapi to IIS and then call it?
Update:
Index.cshtml:
@{
    ViewBag.Title = "Welcome";
}

Welcome to Sibeesh Passion's Email List

                ID
                Email ID ( Double click to update)
                Subscribed Date

                    {{sub.SubscriberID}}
                    {{sub.MailID}}
                    {{sub.SubscribedDate}}

                        <input type="button" id="Delete" value="Delete" data-ng-click="dltSubscriber(sub.SubscriberID)" />

            Sbscribe here
            <input type="email" class="form-control" id="email" placeholder="Enter email" [required="string" ] data-ng-model="mailid" />

        <button type="button" class="btn btn-default" data-ng-click="saveSubs();">Submit</button>

_Layout.cshtml:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

        @RenderBody()

© @DateTime.Now.Year - Sibeesh Passion

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

.cshtml could fetch the data from the webapi, but I just copy the html code to a .html file that I could not access the data. Hope someone could help it. There is nothing wrong with the code, may be I ignored some includes.

A: Be sure to throw the error to see it in the console window:
function getAll() {
    var servCall = APIService.getSubs();
    servCall.then(function (d) {
        $scope.subscriber = d.data;
    }, function (error) {
        $log.error('Oops! Something went wrong while fetching the data.')
        //THROW error
        throw error;
    })
}

When a promise .then method rejection handler omits a throw statement, the handling function returns a value of undefined. This will convert a rejected promise to a fulfilled promise.

$q:
Due to e13eea, an error thrown from a promise's onFulfilled or onRejection handlers is treated exactly the same as a regular rejection. Previously, it would also be passed to the $exceptionHandler() (in addition to rejecting the promise with the error as reason).
-- AngularJS Developer Guide - Migrating from V1.5 to V1.6.

A: It is working, I need to import some necessary libraries, such as jquery and bootstrap.js. But I found another question that:
At first, I think my code do not work, may be I was wrong, the speed of fetching data from the webapi is too delay, so I do not see it any more. Just 2s later, the data are all displayed successfully.
So the speed of .cshtml file is faster than .html file, what reason caused this issue. Does some one have the same issue as mine.


text:
Q: Boundedness of a double real sequence Let $\{a_{n,m}\}_{n,m \in \Bbb N} \in \Bbb R_+$ a double real positive sequence such that
$$b_m=\sum_{n=1}^\infty a_{n,m}<\infty$$
and such that
$$\lim_{m \to \infty} a_{n,m}=0$$
My question is if the following relation is true:
$$\sup_{m \in \Bbb N}(b_m)<\infty$$
Thanks for any suggestion.

A: No.
Write $1[\phi]$ for the indicator function, whose value is $1$ if $\phi$ is true, and $0$ otherwise.
Let $$a_{n,1} = 1[n=0]$$ $$a_{n,2} = 1[1 \leq n \leq 2]$$ $$a_{n,3} = 1[3 \leq n \leq 6]$$ $$a_{n,4} = 1[7 \leq n \leq 10]$$ and so on, taking $a_{n,m}$ to be $1$ if $n$ is between the $m-1$th and $m$th triangular number, and $0$ otherwise.
Then $b_m = m$, which is finite but tends to $\infty$ as $m \to \infty$; but $$\lim_{m \to \infty} a_{n,m} = 0$$ because for fixed $n$, $a_{n,m}$ is eventually $0$.


text:
Q: FileStorage for OpenCV Python API I'm currently using FileStorage class for storing matrices XML/YAML using OpenCV C++ API.
However, I have to write a Python Script that reads those XML/YAML files.
I'm looking for existing OpenCV Python API that can read the XML/YAML files generated by OpenCV C++ API

A: Using the FileStorage functions available in OpenCV 3.2, I've used this with success:
import cv2
fs = cv2.FileStorage("calibration.xml", cv2.FILE_STORAGE_READ)
fn = fs.getNode("Camera_Matrix")
print (fn.mat())

A: In addition to @misha's response, OpenCV YAML's are somewhat incompatible with Python.
Few reasons for incompatibility are:

*

*Yaml created by OpenCV doesn't have a space after ":". Whereas Python requires it. [Ex: It should be a: 2, and not a:2 for Python]

*First line of YAML file created by OpenCV is wrong. Either convert "%YAML:1.0" to "%YAML 1.0". Or skip the first line while reading.

The following function takes care of providing that:
import yaml
import re
def readYAMLFile(fileName):
    ret = {}
    skip_lines=1    # Skip the first line which says "%YAML:1.0". Or replace it with "%YAML 1.0"
    with open(scoreFileName) as fin:
        for i in range(skip_lines):
            fin.readline()
        yamlFileOut = fin.read()
        myRe = re.compile(r":([^ ])")   # Add space after ":", if it doesn't exist. Python yaml requirement
        yamlFileOut = myRe.sub(r': \1', yamlFileOut)
        ret = yaml.load(yamlFileOut)
    return ret

outDict = readYAMLFile("file.yaml")

NOTE: Above response is applicable only for yaml's. XML's have their own share of problems, something I haven't explored completely.

A: I wrote a small snippet to read and write FileStorage-compatible YAMLs in Python:
# A yaml constructor is for loading from a yaml node.
# This is taken from @misha 's answer: http://stackoverflow.com/a/15942429
def opencv_matrix_constructor(loader, node):
    mapping = loader.construct_mapping(node, deep=True)
    mat = np.array(mapping["data"])
    mat.resize(mapping["rows"], mapping["cols"])
    return mat
yaml.add_constructor(u"tag:yaml.org,2002:opencv-matrix", opencv_matrix_constructor)

# A yaml representer is for dumping structs into a yaml node.
# So for an opencv_matrix type (to be compatible with c++'s FileStorage) we save the rows, cols, type and flattened-data
def opencv_matrix_representer(dumper, mat):
    mapping = {'rows': mat.shape[0], 'cols': mat.shape[1], 'dt': 'd', 'data': mat.reshape(-1).tolist()}
    return dumper.represent_mapping(u"tag:yaml.org,2002:opencv-matrix", mapping)
yaml.add_representer(np.ndarray, opencv_matrix_representer)

#examples

with open('output.yaml', 'w') as f:
    yaml.dump({"a matrix": np.zeros((10,10)), "another_one": np.zeros((2,4))}, f)

with open('output.yaml', 'r') as f:
    print yaml.load(f)

A: You can use PyYAML to parse the YAML file.
Since PyYAML doesn't understand OpenCV data types, you need to specify a constructor for each OpenCV data type that you are trying to load.  For example:
import yaml
def opencv_matrix(loader, node):
    mapping = loader.construct_mapping(node, deep=True)
    mat = np.array(mapping["data"])
    mat.resize(mapping["rows"], mapping["cols"])
    return mat
yaml.add_constructor(u"tag:yaml.org,2002:opencv-matrix", opencv_matrix)

Once you've done that, loading the yaml file is simple:
with open(file_name) as fin:
    result = yaml.load(fin.read())

Result will be a dict, where the keys are the names of whatever you saved in the YAML.

A: To improve on the previous answer by @Roy_Shilkrot I added support for numpy vectors as well as matrices:
# A yaml constructor is for loading from a yaml node.
# This is taken from @misha 's answer: http://stackoverflow.com/a/15942429
def opencv_matrix_constructor(loader, node):
    mapping = loader.construct_mapping(node, deep=True)
    mat = np.array(mapping["data"])
    if mapping["cols"] > 1:
        mat.resize(mapping["rows"], mapping["cols"])
    else:
        mat.resize(mapping["rows"], )
    return mat
yaml.add_constructor(u"tag:yaml.org,2002:opencv-matrix", opencv_matrix_constructor)

# A yaml representer is for dumping structs into a yaml node.
# So for an opencv_matrix type (to be compatible with c++'s FileStorage) we save the rows, cols, type and flattened-data
def opencv_matrix_representer(dumper, mat):
    if mat.ndim > 1:
        mapping = {'rows': mat.shape[0], 'cols': mat.shape[1], 'dt': 'd', 'data': mat.reshape(-1).tolist()}
    else:
        mapping = {'rows': mat.shape[0], 'cols': 1, 'dt': 'd', 'data': mat.tolist()}
    return dumper.represent_mapping(u"tag:yaml.org,2002:opencv-matrix", mapping)
yaml.add_representer(np.ndarray, opencv_matrix_representer)

Example:
with open('output.yaml', 'w') as f:
    yaml.dump({"a matrix": np.zeros((10,10)), "another_one": np.zeros((5,))}, f)

with open('output.yaml', 'r') as f:
    print yaml.load(f)

Output:
a matrix: !!opencv-matrix
  cols: 10
  data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0]
  dt: d
  rows: 10
another_one: !!opencv-matrix
  cols: 1
  data: [0.0, 0.0, 0.0, 0.0, 0.0]
  dt: d
  rows: 5

Though I could not control the order of rows, cols, dt, data.

A: pip install opencv-contrib-python for video support to install specific version use pip install opencv-contrib-python


text:
Q: Angular/TypeScript Map using last index on every object I'm trying to create an array of 120 objects (hex's for a map) and then add info to each one.
When I use map the id is supposed to be the index of the current object and I can console log the correct, current index as expected but for some reason EVERY object has an id of 119. I've looked at some of the other map examples on here and with Mozilla and I'm not understanding where I'm going wrong.
export class MapComponent implements OnInit {

  arrayOfObjects = Array(120).fill({})
  hexTiles = this.arrayOfObjects.map( (hex, index) => this.createHex(hex, index))

  constructor() { }

  ngOnInit() {
  }

  createHex(hex, index){
    console.log('Current Index', index)
    hex['id'] = index
    hex['x-coordinate'] = null
    hex['y-coordinate'] = null
    hex['mapped'] = false
    hex['terrain'] = ''
    hex['details'] = ''

    return hex
  }

}

UPDATE
I have tried a suggested solution but am now getting an array of 120 empty objects.
Here is the updated code:
HTML: This displays nothing.

      {{hex}}

TS: This will console log "Hexs (120) [empty × 120]"
export class MapComponent implements OnInit {

  hexTiles = [...Array(120)].map((_, i) => this.createHex({}, i));

  constructor() { }

  ngOnInit() {
    console.log('Hexs', this.hexTiles);
  }

  createHex(hex, index) {
    hex['id'] = index;
    hex['x-coordinate'] = null;
    hex['y-coordinate'] = null;
    hex['mapped'] = false;
    hex['terrain'] = '';
    hex['details'] = '';
    return hex;
  }

}

A: Change
arrayOfObjects = Array(120).fill({})
hexTiles = this.arrayOfObjects.map( (hex, index) => this.createHex(hex, index))

for this
hexTiles = [...Array(120)].map((_, i) => this.createHex({}, i));

Here is a working snippet:

function createHex(hex, index) {
    hex['id'] = index;
    hex['x-coordinate'] = null;
    hex['y-coordinate'] = null;
    hex['mapped'] = false;
    hex['terrain'] = '';
    hex['details'] = '';
    return hex;
}

const hexTiles = [...Array(120)].map((_, i) => createHex({}, i));

console.log(hexTiles);

Here is an explanation of your problem.

function createHex(hex, index) {
    hex['id'] = index;
    hex['x-coordinate'] = null;
    hex['y-coordinate'] = null;
    hex['mapped'] = false;
    hex['terrain'] = '';
    hex['details'] = '';
    return hex;
}
const obj = { };
const arrayOfObjects = Array(120).fill(obj);
const hexTilesBad = arrayOfObjects.map((hex, index) => createHex(hex, index));
console.log(obj)

When filling the array with {}, you are actually filling it with copies of the reference to the same object. This is because, by default, in Javascript/Typescript, when you assign an object, you assign its reference.
In the above example, instead of filling the array with {}, we fill it with obj, which is just {}. When we console.log(obj) at the end, we see that it indeed has the value of the last iteration.
Its reference has been copied 120 times in the array, and those references got passed to the map, then to your createHex function. So ultimately, you are just modifying 120 times the same object.
However, when you pass {} directly to createHex from the map arrow function, a new object is created for each iteration in the function scope, so nothing is shared.
EDIT:
[...Array(120)] does not seem to work in TypeScript. As pointed out by @AJT_82 in the comments below, this is due to a TypeScript bug which causes this spread operator trick to incorrectly translate to JavaScript.
To circumvent the problem, you can try the following:
Array.from({ length: 120 })

or stick with your method
Array(120).fill({})

What is important is to not use the content of this array, since they are just references to the same object.


text:
Q: C# - ContextMenuStrip.close() problem I have some map control and when I clicked on it, I open contextMenuStrip and then clicked for the snapshot of my map.
Problem is that when I click for the snapshot, it's snapshot map including contextMenuStrip.
I try with, "contextMenuStrip.Close()" but not work.
//on map click event
private void map1_Click(MouseEventArgs e)
{
   System.Drawing.Point point = new System.Drawing.Point(e.X, e.Y + 160);
   contextMenu.Show(this.contextMenu, point);
}

//item of contextMenu
private void contextMenuConvert_Click(object sender, EventArgs e)
{
   contextMenu.Close();
   map.CreateImage(ImageFormat.Jpeg);
}

Picture of example.

A: That just sends a message which is queued.  If you want to make sure it is actually done use Application.DoEvents() between the Close call and the CreateImage call.

A: Instead of trying to take a snapshot of the screen (which I'm assuming you're doing), can you add code to your map object that allows it to render itself to an off-screen Image?  That way, the caller can save that Image to a file or do whatever else it wants to with it.  You'll be able to reuse nearly all the current rendering code with some slight tweaks to support the idea of off-screen rendering.


text:
Q: Choosing between a Web App Bot and a Function Bot When creating a bot in Azure Bot Service you have two hosting options according to this article: https://learn.microsoft.com/en-us/bot-framework/bot-service-overview-introduction
App Service Plan (Standard Azure web app, Web App Bot)
Consumption Plan (Azure Functions, Functions Bot)
I'm trying to understand the strengths and weaknesses of each. The billing model of a Function Bot would work best for my use case, but I seem to be finding limitations. It also seems that Microsoft's documentation is biased towards Web App Bots being the standard.
Here is what I know so far:

*

*The billing model is different. App Services plans are billed more like an always running VM vs. Functions are pay-per-run.

*App Service uses the standard ASP.NET MVC model. Functions use C# scripts

*Visual Studio seems to have better support for debugging and publishing App Service plan bots
One thing I think is related to #2 is Global Message handling. The examples Microsoft gives for implementing a global message handler seems to require the use of global.asax.cs to register the global handler, this file isn't present in a Function Bot.
Are Web App bots the preferred option from Microsoft?
Is .NET Core better supported in either option?
Is there a way to implement global handlers in Function Bots?
Are there other specific weaknesses of Function Bots?
Is one option more "modern" than the other?


text:
Q: How to make inline form elements responsive Introduction
Hi, i am working with the search form, having 5 inputs and a search button. Each input field have its label.
Code

            <form action="/users" id="Search-form" method="POST" role="form">

                            Name:
                            <input type="text" class="form-control" placeholder="first name" name="name" id="srch-term" value="$data.name">

                            Ph#:
                            <input type="text" class="form-control" placeholder="923325540106" name="phoneNumber" id="srch-term" value="$data.phoneNumber" pattern="[0-9]{12}">

                            From:
                            <input type="text" class="form-control pickdate" name="fromdate" id="fromdate"
                                   value="$data.from" />

                            To:
                            <input type="text" class="form-control pickdate" name="todate" id="todate"
                                   value="$data.to" />

                            Filter
                            <select name="ddlFilterBy" id="ddlFilterBy" class="form-control">
                                <option value="all">All</option>
                                <option value="driver">Active Drivers</option>
                            </select>

                            <button type="submit" class="btn btn-info">Search</button>

            </form>

Display LG

Display MD

Problem
Here, clearly i have problem with medium screens or less but works perfect with larger screens.
On medium or small screens, other elements break the line.
If someone have idea about this kind of problem or any reference, then please do help. Thanks for your time.

A: Do it in this way-- All your inputs must be wrapped within responsive grid column classes.
Working example

@media(max-width:767px){
#srch {
margin-top: 22px;
margin-left: 10px;
}
}

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

          <form action="/users" id="Search-form" method="POST" role="form">

                          Name:
                          <input type="text" class="form-control" placeholder="first name" name="name" id="srch-term" value="$data.name">

                          Ph#:
                          <input type="text" class="form-control" placeholder="923325540106" name="phoneNumber" id="srch-term" value="$data.phoneNumber" pattern="[0-9]{12}">

                          From:
                          <input type="text" class="form-control pickdate" name="fromdate" id="fromdate"
                                 value="$data.from" />

                          To:
                          <input type="text" class="form-control pickdate" name="todate" id="todate"
                                 value="$data.to" />

                          Filter
                          <select name="ddlFilterBy" id="ddlFilterBy" class="form-control">
                              <option value="all">All</option>
                              <option value="driver">Active Drivers</option>
                          </select>

                          <button id="srch" type="submit" class="btn btn-info">Search</button>

          </form>

A: Use col-*-* class for all your inputs and labels.

     <input class="input-lg">


text:
Q: NuxtJS/apollo how to set custom header How to set custom header on @nuxtjs/apollo?
on my nuxt.config.js

I have something like this
apollo: {
  "x-token": "hash",
  "x-auth-token": "hash",
  "x-refresh-token":  "hash",
  headers: {
  },
  clientConfigs: {
    default: {
      // required
      httpEndpoint: "localhost:4000"
    }
  }
}

Thanks

A: Like this:
nuxt.conifg.js
apollo: {
  clientConfigs: {
    default: {
      httpEndpoint: 'localhost:4000',
      httpLinkOptions: {
        headers: {
           'x-token': 'hash',
           'x-auth-token': 'hash',
           'x-refresh-token':  'hash'
        }
      }
    }
  }
},


text:
Q: Vuelidate - Do not mutate vuex store state outside mutation handlers I am validating a vue form with Vuelidate and I am getting the following error when trying to edit it:
Error: [vuex] do not mutate vuex store state outside mutation handlers.

This is my form input structure:
<hp-text-input
  id="company-name"
  v-model.trim="$v.formData.companyName.$model"
  :code="$v.formData.companyName.$model"
  :v="$v.formData.companyName"
  :disabled="formData.loading"
  :labeltext="$t('components.add_address_modal.company')"
  name="company-name"
></hp-text-input>

This is my state:
data() {
  return {
    formData: {
      country: 'Ireland',
      address: '',
      addressAdditional: '',
      addressType: '',
      city: '',
      companyName: '',
      firstName: '',
      lastName: '',
      zipCode: '',
    },
  }
},

These are my Vuelidate validations:
validations() {
  return {
    formData: {
      country: {},
      address: { required, max: maxLength(32) },
      addressAdditional: { max: maxLength(32) },
      addressType: { required },
      city: { required },
      companyName: {},
      firstName: { required },
      lastName: { required },
      zipCode: { required, max: maxLength(10), zipValidate },
    },
  }
},

I do use a vuex store in this component but it is not even related to the form data itself.
The only thing that worked to get rid of the error for now was creating a copy of the formData and passing it to the form, which for me doesn't make any sense to do.
Do you have any suggestions?


text:
Q: Multer file address to upload folder is not well formatted in MySQL database I used Multer Node.js modules to upload image to upload folder and the image uploaded fine and the correct path was passed to the MySQL database but the file path of the file(image) is not well formatted as i expected.
I mean there is no slash (/) between the main folder, subfolder and the file(image) actual name though the extension is correct.

const storage = multer.diskStorage({
    destination: "./public/upload/",
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() +
            file.originalname)
    }
})

const upload = multer({
    storage: storage
})

but this is the kind of data gotten from database when i make a request

[
    {
        "id": 3,
        "name": "samsung galax s8",
        "brand": "samsung",
        "image": "publicuploadfile-1547151173379tecno-spak-2.jpg",
        "category": "phone",
        "qty": "6",
        "price": "50000",
        "created_at": "1/10/2019",
        "updated_at": "1/10/2019"
    }
]

This is the image file.path I got "publicuploadfile-1547151173379tecno-spak-2.jpg",
Instead of something like "public/upload/file-1547151173379tecno-spak-2.jpg", which I was expecting.
Please how can I save the path to the database as the correct file address?

A: Update this .
var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './uploads')
  },
  filename: function(req, file, callback) {
    console.log(file)
    callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
  }
})

A: Had a similar issue, i saw that when i used a raw sql query to save req.file.path mysql engine would strip off my backslash '\' but when i used bulk insert to insert multiple file urls at once it did not strip off the backslash.
Example,
  temp[i] = {'recordedWebinarVideo': req.files[i].path}
  con.query('UPDATE `courses` SET `Recorded_URL` = "'+temp[i].recordedWebinarVideo+'"
   WHERE `CourseID`="'+req.params.id+'" ', (err,data)=>{
    if(err)
    console.log(err)
    else{
      console.log(data)

    }
  })

RESULT : BACKSLASH removed
However,
with
con.query('INSERT INTO course_extra_resources (file_path, course_id) VALUES ?',
      [temp.map( i => [i.files, req.params.id])], (err,data)=>
       {
          if(err)
          console.log(err);
          else{
            console.log(data)
            res.status(200).json(data)
          }
       })
The backslash was pertained and mysql saved the url in correct format.


text:
Q: Is there a solution for Cannot find module 'yallist' error npm create-react-app login-and-register-app
node:internal/modules/cjs/loader:995
const err = new Error(message);
Error: Cannot find module 'yallist'
Require stack:

*

*C:\Users\Lenovo\AppData\Roaming\npm\node_modules\npm\node_modules\semver\node_modules\lru-cache\index.js


text:
Q: Cardinality of cartesian product and axiom of choice My textbook says that we need the axiom of choice to prove that for every infinite cardinal $\lambda$, $\lambda \times \lambda$ is equipotent with $\lambda$. However, I don't see where AC is used in the proof, which goes as follows:

We prove by transfinite induction. Assume that for every $\mu<\lambda$, $\mu\times\mu$ is equipotent to $\mu$. Define an order relation $\leq_R$ on $\lambda\times \lambda$ as follows:
$$(\beta,\gamma)\leq_R (\beta_1,\gamma_1)$$
if and only if
$\sup(\beta,\gamma)<\sup(\beta_1,\gamma_1)$, or $\sup(\beta,\gamma)=\sup(\beta_1,\gamma_1)$ and $\beta<\beta_1$, or $\sup(\beta,\gamma)=\sup(\beta_1,\gamma_1)$ and $\beta=\beta_1$ and $\gamma\leq \gamma_1$.
This order is then a well-ordering on $\lambda\times\lambda$. Therefore there exists an ordinal $\alpha$ and an isomorphism $f$ from $(\alpha, \in)$ into $(\lambda\times\lambda, \leq_R)$. We will show that $\alpha \leq \lambda$. If we assume the contrary, then $f(\lambda)=(\beta_0, \gamma_0)$ for some $\beta_0, \gamma_0$ in $\lambda$, and the restriction of $f$ on $\lambda$ is a bijection from
$\lambda$ onto the set $Y=\{(\beta,\gamma) \mid (\beta, \gamma)<_R (\beta_0, \gamma_0)\}$. Let $\delta_0=\sup(\beta_0, \gamma_0)$, then $\delta_0 <\lambda$, and the cardinality of $\delta_0$ is strictly less than $\lambda$, and therefore, by the induction hypothesis, ${\tt card}(\delta_0 \times \delta_0)={\tt card} (\delta_0)< {\tt card}\lambda$. As $Y$ is included in $\delta_0\times\delta_0$, ${\tt card} (Y) < {\tt card} (\lambda)$, contradiction.

A: The issue here is with the term "cardinal". If you interpret that as "initial ordinal", then choice is not needed here, and instead choice is used to show that every set is equipotent with a cardinal.
If, however, you correctly understand "cardinal" in the general sense, then the axiom of choice is needed, and indeed is equivalent to this statement. But of course, once you assume choice, you may assume that cardinal refers to initial ordinals again...


text:
Q: Screen Size and Image Aren't Functioning Correctly As I final for my Computer Sciences class we could either teach a lesson in Java or some sort of big project.  I used an existing pokemon java engine and am building my game around that. The problem that I am running into is that it isn't the correct size (160,144) and the image won't show up unless you re-size the frame. If anyone has any ideas why that'd be great. Also the paths for the pictures are correct it just won't let me post them for some reason.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AnotherIdea {

public static class Engine extends JPanel implements KeyListener, ActionListener {

    public static JFrame jf;
    public Toolkit tk = jf.getToolkit();
    private Image titlescreen = tk.createImage("F:\\Votech Final\\Welcome to Nightvale\\anotherIdea\\src\\Resources\\Tittle.png");
    private Image start_symbol = tk.createImage("F:\\Votech Final\\Welcome to                                                              Nightvale\\anotherIdea\\src\\Resources\\Start.png");
    private boolean atTitle = true;
    private boolean atContinueScreen = false;
    private boolean start_visible = true;
    private boolean gamestarted = false;
    private int offsetX = 0, offsetY = 0;
private int TILE_WIDTH_PIXELS = 32;
private int TILE_HEIGHT_PIXELS = 32;
private int concurrentMenuItem = 0;
public long seconds = 0;
public long oldTime;
public long minutes = 0;
public long hours = 0;

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    AffineTransform at = new AffineTransform();
    g2.setTransform(at);
    if (atTitle == true) {
        g.drawImage(titlescreen,0,0,null);
        if (start_visible == true) {
            g.drawImage(start_symbol,0,260,null);
        }
}
}
         public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    if (atTitle == true) {
        if (keyCode == KeyEvent.VK_ENTER) {
            atTitle = false;
}
}
}
public static void main(String [] Args) {
     //Create the window
     jf = new JFrame("T.I.N.");
     jf.setSize(160,144);
     //Create an instance of Pokemon and insert into the window
     Engine engine = new Engine();
     jf.add(engine);
     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     jf.setResizable(true);
     jf.pack();
     //Center the Game on the Screen
     Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
     int w = jf.getSize().width;
     int h = jf.getSize().height;
     int x = (dim.width-w)/2;
             int y = (dim.height-h)/2;
     jf.setLocation(x,y);
     //Set focus to the Panel
     jf.setVisible(true);
     engine.requestFocus(true);

 }

    @Override
    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of     generated methods, choose Tools | Templates.
    }

    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
}

`


text:
Q: What is difference between Windows 8 Mobiles app and Windows 8 metro style app I am newbie to windows platform.
I have few questions mentioned below.

*

*What's diff between Windows 8 metro style app and the Windows 8 mobile app?

*What diff languages I can use to develop windows mobile app?

The answers to above questions will quickstart my windows mobile development.
Waiting for your responses.

A: *

*They are basically the same except for some API that are available for phone only
Windows Phone 8 now shares a common core with Windows 8. This means you can expect to write apps for one and easily port it to the other, with UI retooling of course. Developers targeting both should use C#/VB + XAML  and JS for apps, and C++/D3D for games.

*VB/C# + XAML, C++ + DirectX (for complex graphics), JS can be used Windows 8 surface but not with phone (got this from jump start to windows 8)


text:
Q: Cordova app local storage remains after app re-installed My cordova app has a login (username/password) that once authenticated creates a file called stk.db within the root of the app's file system.
When I uninstall the app & re-install it, I am automatically logged in with the previous account I logged in with (due to the stk.db file being read & pulling a 'token' that correlates to a user account).
Obviously I want to have the user be forced to enter a new user account if they re-install the app, what is the best way to approach this based on the code below?
define([
"jquery",
"backbone",
"config",
"stk/controllers/errorController",
"stk/controllers/accountController",
"stk/controllers/onboardController",
"stk/controllers/stkController"
],

function(
$,
Backbone,
Config,
ErrorController,
AccountController,
OnboardController,
stkController)
{

"use strict";

// --------------------------------------------------------------------------------------------
// Controller
// --------------------------------------------------------------------------------------------

var app = function(router) {

    var self = this;
    self.router = router;
    self.views = {};
    self.ctors = {};

    self.stack = [
        { id: 0, name : "Account", selected: true, direction: null },
        { id: 1, name : "Achievements", selected: false, direction: null },
        { id: 2, name : "Prizes", selected: false, direction: null },
        { id: 3, name : "Shop", selected: false, direction: null },
        { id: 4, name : "Leaderboard", selected: false, direction: null },
        { id: 5, name : "Stats", selected: false, direction: null },
        { id: 6, name : "Contactus", selected: false, direction: null }
    ];

    // --------------------------------------------------------------------------------------------
    // register events
    // --------------------------------------------------------------------------------------------

    _.extend(this, Backbone.Events);

    this.on("error", function (args) { this.error(args); }, this);
    this.on("start", function (args) { this.db(args); }, this);
    this.on("login:complete", function (args) { this.loginComplete(args); }, this);
    this.on("onboard:complete", function (args) { this.onboardComplete(args); }, this);

    // --------------------------------------------------------------------------------------------
    // event handlers
    // --------------------------------------------------------------------------------------------

    this.db = function() {

        var self = this;

        var loadDB = function(callback) {
            self.storage(callback);
        }

        loadDB(function(db) {

            var check = {};

            $.each(db.split("|"), function() {
                var entry = this.split(":");
                check[entry[0]] = entry[1];
            })

            self.start(check);

        })

    };

    this.start = function(db) {

        if (db.loggedin != "true") {
            this.login();
        } else {
            this.token = db.token;
            if (db.boarded === "true") {
                this.launch();
            } else {
                this.onboard();
            }
        }

    };

    this.isCarUser = function (usercb) {

        var self = this;
        var check = {};

        self.storage(function (db) {

            $.each(db.split("|"), function () {
                var entry = this.split(":");
                check[entry[0]] = entry[1];
            })

            usercb(check.Car_user);
        });
    };

    this.error = function(message) {
        var handle = "errorCtor";
        (this.ctors[handle] === undefined)
                ? new ErrorController().setup(handle).events().init(message)
                : this.ctors[handle].init(message);
    };

    this.login = function(args) {
        var handle = "accountCtor";
        (this.ctors[handle] === undefined)
                ? new AccountController().setup(handle).events().init(args)
                : this.ctors[handle].init(args);
    };

    this.loginComplete = function(args) {

        var self = this;
        self.token = args;

        var store = function(callback) {
            self.setLoggedIn(callback, self.token);
        }

        store(function(db) {
            self.onboard();
        });

    };

    this.onboard = function(args) {
        var handle = "onboardCtor";
        (this.ctors[handle] === undefined)
                ? new OnboardController().setup(handle).events().init(args)
                : this.ctors[handle].init(args);
    };

    this.onboardComplete = function(args) {

        var self = this;

        var store = function(callback) {
            self.setBoarded(callback, self.token);
        }

        store(function() {
            self.launch();
        });

    };

    this.launch = function(args) {
        var handle = "stkCtor";
        (this.ctors[handle] === undefined)
                ? new stkController().setup(handle).events().init(args)
                : this.ctors[handle].init(args);
    };

    // --------------------------------------------------------------------------------------------
    // FS
    // --------------------------------------------------------------------------------------------

    this.setBoarded = function(callback, token) {

        var self = this;

        var fc = 'opened:true|loggedin:true|boarded:true||Car_user:false|token:' + token;

        var errorHandler = function(e) {
            self.error(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.createWriter(function(fileWriter) {

                    fileWriter.onwriteend = function(e) {
                        callback(fc);
                    };

                    fileWriter.onerror = function(e) {
                        self.error(e.toString());
                    };

                    var boarded = new Blob([fc], {type: 'text/plain'});

                    fileWriter.write(boarded);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }

    };

    this.setLoggedIn = function(callback, token) {

        var self = this;

        var fc = 'opened:true|loggedin:true|boarded:false|Car_user:false|token:' + token;

        var errorHandler = function(e) {
            self.error(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.createWriter(function(fileWriter) {

                    fileWriter.onwriteend = function(e) {
                        callback(fc);
                    };

                    fileWriter.onerror = function(e) {
                        self.error(e.toString());
                    };

                    var loggedIn = new Blob([fc], {type: 'text/plain'});

                    fileWriter.write(loggedIn);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }

    };

    this.setCarUser =  function(callback, CarUser){

        var self = this;

        var fc = 'opened:true|loggedin:true|boarded:true|token:' + this.token + "|Car_user:"+ CarUser;

        var errorHandler = function(e) {
            self.error(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.createWriter(function(fileWriter) {

                    fileWriter.onwriteend = function(e) {
                        callback(fc);
                    };

                    fileWriter.onerror = function(e) {
                        self.error(e.toString());
                    };

                    var loggedIn = new Blob([fc], {type: 'text/plain'});

                    fileWriter.write(loggedIn);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }
    }

    this.storage = function(callback) {

        var self = this;

        var fc = 'opened:true|loggedin:false|boarded:false|token:null|Car_user:false';

        var errorHandler = function(e) {
            console.log(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.file(function(file) {

                    var reader = new FileReader();

                    reader.onloadend = function(e) {
                        callback(this.result);
                    };

                    reader.readAsText(file);

                }, errorHandler);

            }, function() {

                fs.root.getFile('stk.db', {create: true, exclusive: true}, function(fileEntry) {

                    fileEntry.createWriter(function(fileWriter) {

                        fileWriter.onwriteend = function(e) {
                            callback(fc);
                        };

                        fileWriter.onerror = function(e) {
                            self.error(e.toString());
                        };

                        var opened = new Blob([fc], {type: 'text/plain'});

                        fileWriter.write(opened);

                    }, errorHandler);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }

    };

};

return app;

}

);

A: If you really need to use local file for some reasons, you can store a version number in the local file, and compare it with the version number stored inside the index.html, if these two version numbers are different, erase the login info. in the local file and update the version no. in the local file.
by the way, would like to tell you that the local file Api does not work as expected in all phones.  e.g. sometimes it hangs in Samsung Note 2, i.e. neither success nor fail fires, but the same codes work well in other phones.


text:
Q: Mozilla Thunderbird - Multiple Addresses for 1 Individual I use Mozilla Thunderbird as my default Email client. In my address books I have a few entries of individuals with multiple email addresses. I now address emails to each of their addresses as a separate entry when sending an email. How can I enter more than 1 address in my Thunderbird address book, so that when I enter that individual in the address field of an email all three addresses appear as a single entry? Can this be done? I would sincerely be grateful for any help that any of you could provide.

A: Create a Mailing List for recipients with multiple email addresses.

*

*Press CtrlShiftB to show the Address Book dialog.

*Right-click on the preferred location for the entry -- Personal Address Book or Collected Address Book.

*Select New List.

*Add each address for that individual -- Thunderbird helps auto-complete the entry if the individual address exists.

*Give the list a unique, easily-remembered name.

Now, when you add that single address to a To:, Bcc: or Cc: line, all the addresses in the list are included.

A: When you create a contact, there is a space for "Additional email" - simply enter a comma separated list.  When you compose a message and type their name, you can pick to send either to just the primary email in the "Email" field, or all of the "Additional Email" entries.
(just tested on Linux Mint 19x Thunderbird 60.6.1)