text:
Q: Create OpenCL Context from cl_context without taking ownership I'm creating an OpenFX plugin to do some image processing for a VR system.
As both our existing processing code, and the host the plugin is intended for, are based on OpenCL, the host developers have given me an extension to OFX to share the OpenCL environment.
However - our code uses the C++ API (cl::Context), and the extension they've provided gives me a pointer to a C cl_context.
Is there any way for me to create a cl::Context from a cl_context, without taking ownership of the latter? (and the same for the cl::CommandQueue from cl_command_queue). The API docs online suggest that both the copy constructor and assignment operator take ownership.

A: Fortunately you can inspect the OpenCL C++ header to see exactly what it does (at the bottom it just makes C API calls), and you can step into the code to verify it. When working with both C and C++ API, you must be careful about the OpenCL object retain/release counts, in particular if the C++ constructor doesn't retain but the destructor does release, then you have a problem (because you'd be releasing the host's context out from under them). However, it is easily fixed because you can just call retain yourself on the object after constructing to balance things out. I've mixed C API and C++ API in OpenCL and it was the retain/release philosophy of the C++ header that got me too, so I feel your pain. Curious, is the OpenFX host Resolve, Vegas, Catalyst, or something else? There's a unified OpenCL extension on the way for OpenFX.


text:
Q: How can I tell if my hourly cron job has run? I have created a file called ntpdate in /etc/cron.hourly
#!/bin/sh
/usr/sbin/ntpdate-debian
date > /tmp/william_tmp
date > /william_tmp
date > ~/william_tmp
echo test

I also did Chmod 755 to this file.
However, I can't tell if the file has run or not!
The file is not created in any of the 3 directories.
If I manually run cd / && run-parts --report /etc/cron.hourly then the files are created and I get the echo.
Can anyone recommend (ideally step by step!) instructions to test that it is working?

A: You should look in your /var/log/syslog log file. If a cron has run, it would have a line like:
Jun 11 19:09:01 penguin CRON[17376]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Jun 11 19:17:01 penguin CRON[17799]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)

For troubleshooting tips, see https://help.ubuntu.com/community/CronHowto#Troubleshooting_and_Common_Problems

A: One major pitfall to cron is cron runs in an extremely limited shell environment, as a result a lot of variables aren't exported in to the environment, mainly $PATH. Make sure you use all absolute paths to executable, including common functions like echo, uptime, date, etc all need to use full paths (/bin/echo, /bin/date, /usr/bin/uptime). To determine the path to an executable, you can use the which command like so: which echo - this will show you the full path to that tool.

A: Try changing the first line of your script (the interpreter) to:
#!/bin/bash
I've also had problems in the past, with environment variables and PATH issues. After changing the interpreter to bash my issues were gone.

A: Given I've added the clearme.sh script in /etc/cron.hourly/
Just filter CRON tasks in terminal with the powerful egrep and awk:
$ cat /var/log/syslog | egrep clearme | awk "{ print $1 }" > ~/Desktop/cronlog.txt

The output will look like:
Jan 14 15:20:01 markets-dev CRON[10089]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)
Jan 14 15:40:01 markets-dev CRON[18042]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)
Jan 14 16:00:01 markets-dev CRON[22817]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)
Jan 14 16:20:01 markets-dev CRON[28183]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)
Jan 14 16:40:01 markets-dev CRON[411]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)
Jan 14 17:00:01 markets-dev CRON[5442]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)
Jan 14 17:20:01 markets-dev CRON[11935]: (dminca) CMD (root /etc/cron.hourly/clearme.sh)

To explain everything step-by-step:

*

*cat /var/log/syslog - print me the System log

*egrep clearme - but only select rows that contain the text clearme

*awk "{ print $1 }" - print me that row that contains the text clearme

*> ~/Desktop/cronlog.txt - output the results in the file cronlog.txt located on the Desktop directory.

The 4th step is optional. It will just print results in the terminal instead of the file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add cancel and save buttons in ActionBar I want to add save and cancel buttons in the action bar of my application when I am in an activity that allows inserting data to the user, in the same way as for example shows the Trello application:
I need these buttons to be shown only in a specific activity, but not in the other activities of the application. I do not know how to implement this.

A: Here setHomeAsUpIndicator is creating the dismiss btn and menu is creating the done btn.
hope this answers the query.

Set the toolbar

<android.support.design.widget.AppBarLayout
    android:id="@+id/my_appbarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="0dp"
    android:theme="@style/AppTheme.AppBarOverlay"
    app:elevation="0dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_margin="0dp"
        app:layout_scrollFlags="snap"
        app:navigationIcon="@drawable/ic_dismiss_24dp"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

Set the actionbar dismiss btn

toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar supportActionBar = getSupportActionBar();

if (supportActionBar != null) {
    supportActionBar.setDisplayHomeAsUpEnabled(true);
    supportActionBar.setDisplayShowHomeEnabled(true);
}
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_dismiss_24dp);

Set the functions inside your activity for menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_page, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_done:
            // done btn functionalities goes here
            break;
        case android.R.id.home:
            //dismiss btn functionality goes here
            break;
    }
    return super.onOptionsItemSelected(item);
}

Set the menu file(menu_page) inside res/menu

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="____your context____">

    <item
        android:id="@+id/action_done"
        android:icon="@drawable/ic_done_24dp"
        android:orderInCategory="100"
        android:title="@string/done"
        app:showAsAction="always" />

</menu>

A: you can custom your own toolbar and make theme in ManifestFile as no ActionBar
and insert toolbar in every Activity as component


text:
Q: lazy instantiation of the map value Is there a way to instantiate the value of map lazy?
For example
class MapTest {
    @Lazy(soft = true) HashMap<String, List<String>> map
}

Doing like this I can use this call and get null without recieving NullPointerException
new MapTest().map.key1

However attempt to call
map.key1.remove(1)

will lead to NullPointerException due the value being null. (it would be fine if it threw IndexOutOfBounds exception)
Is there a way to instantiate the list value of the map?

A: try map.withDefault :
def map = [:].withDefault { [] }
assert map.key1.isEmpty()

Some explanation :

*

*[:] is the groovy way to instantiate an empty hash map

*withDefault is a groovy method on a map wich take a closure. this closure is call every time a key is requested to initialize the value if it doesn't exist. this closure take one parameter (the key) and should the value

*[] is the groovy way to create an empty list - { [] } is a closure wich return an empty list for every key

see others examples here


text:
Q: How to use setState() inside compoentWillMount ReactJS I'm new to ReactJs. I'm trying to create a firebase app using it. So in componentWillMount I'm checking if the user is logined or not and setting the state boolean value according to that
  componentWillMount() {
    var config = {...};
    Firebase.initializeApp(config)

    Firebase.auth().onAuthStateChanged(function(user){
      if(user){
        console.log("User logined");
        this.setState({
          isLogined : true
        })
      }else{
        console.log("User isn't logined");
        this.setState({
          isLogined : false
        })
      }
    })

  }

But it's showing setState() is not a function.
index.js:2178 TypeError: this.setState is not a function
    at Object.next (App.js:31)
    at index.cjs.js:1353
    at index.cjs.js:1457

Need Help :(

A: Few things:
1) You'll want to move this code to componentDidMount.
componentWillMount is deprecated. Here's some more info as to why you should prefer componentDidMount
2) Change your onAuthStateChanged callback to be an arrow function.
componentDidMount() {
var config = {...};
Firebase.initializeApp(config)

Firebase.auth().onAuthStateChanged((user) => {
  if(user){
    console.log("User logined");
    this.setState({
      isLogined : true
    })
  }else{
    console.log("User isn't logined");
    this.setState({
      isLogined : false
    })
  }
})

}

A: The problem comes from:
Firebase.auth().onAuthStateChanged(function(user){

this is not refferring to the react component. Instead, try:
Firebase.auth().onAuthStateChanged((user) => {


text:
Q: lock and unlock sql server tables from .net code without using stored procedures I need to block a table from being accessed by any other process unless my current operation(usually a INSERT or an UPDATE) is completed, Is there a way to lock and unlock sql server tables from .net code without using stored procedures, i need these to avoid business rules based duplicate records from being entered into the table.

A: Better still, don't lock the tables (especially if it takes a long time to update/insert data), but commit changes only after all data is updated/inserted.

A: You an use a hint
insert into table with (tablock) (colx) values ('newValuex');
If valuex is a primary key or has a unique constraint then it will be enforced.
But you don't need a tabloc to enforce that constraint.
If you have multiple statements then you can wrap them in a transaction.


text:
Q: Como verificar se um Arquivo pode ser criado numa Pasta antes de tentar criá-lo nela? Meu programa permite que usuário defina uma Pasta, e posteriormente o programa irá criar um Novo Arquivo nesta Pasta.
Entretanto, o programa não é capaz de criar um Arquivo em qualquer Pasta, por exemplo:

*

*Cria o Novo Arquivo na Pasta normalmente:
new FileOutputStream("C:\\Users\\Public\\Documents\\novoArquivo.txt");

*

*Lança uma Exception: java.io.FileNotFoundException: C:\novoArquivo.txt (Acesso negado):
new FileOutputStream("C:\\novoArquivo.txt");

Eu não estou tentando fazer o programa ter permissão para criar Arquivos em qualquer pasta, apenas preciso saber com antecedência (antes de tentar criar o Arquivo) se o programa será ou não capaz de criar o Arquivo na Pasta escolhida pelo usuário.
Se o usuário escolher uma Pasta na qual o programa não é capaz de criar Arquivos,  o usuário será avisado imediatante e não poderá avançar até escolher outra Pasta.

Eu pensei em usar um try/catch como if/else para saber se o Arquivo pode ser criado ou não, colocando dentro desse try/catch um new FileOutputStream(pathDaPastaEscolhida);, o problema é que, se Não lançar Exception, o Arquivo é imediatamente criado (sem pedir confirmação do usuário e sem dar a ele a oportunidade de escolher outra Pasta antes de efetivamente criar o Arquivo).
O Arquivo só deveria ser criado quando o usuário clicar em "Avançar", e, o botão "Avançar" deve ficar desabilitado até o programa ter certeza de que é capaz de criar o Arquivo na Pasta escolhida pelo usuário.

Criei um código de exemplo compilável para ajudá-los a ter ideia do que preciso:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class CriadorDeArquivo {

    public static void main(String[] args) {
        File novoArquivo1 = new File("C:\\Users\\Public\\Documents\\novoArquivo.txt");
        criarArquivoSeForPossivel(novoArquivo1); //Cria o Arquivo como esperado

        File novoArquivo2 = new File("C:\\novoArquivo.txt");
        criarArquivoSeForPossivel(novoArquivo2); //ERRO: Lança uma Exception ao invés de mostrar a "Mensagem2"
    }

    public static void criarArquivoSeForPossivel(File novoArquivo) {
        if (isPodeSerCriado(novoArquivo)) {
            System.out.println("Com certeza é possível criar o Arquivo neste local, ele será criado..."); //Mensagem0
            criarArquivo(novoArquivo);
            System.out.println("O Arquivo foi Criado!"); //Mensagem1
        } else {
            System.out.println("O Arquivo não pode ser criado nesse local, escolha outro local."); //Mensagem2
        }
    }

    public static void criarArquivo(File novoArquivo) {
        try {
            new FileOutputStream(novoArquivo); //Cria o Novo Arquivo na Pasta
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static boolean isPodeSerCriado(File arquivo) {
        //O que colocar aqui para determinar se esse arquivo pose ser criado ou não?
        return true;
    }
}

A: Tente usar o método isWritable() da classe Files:
public static boolean isPodeSerCriado(File arquivo) {
    return Files.isWritable(arquivo.toPath());
}

Vale mencionar a ressalva da documentação quanto ao uso deste método para este fim:

Observe que o resultado desse método está imediatamente desatualizado, não há garantia de que uma tentativa subsequente de abrir o arquivo para escrita tenha êxito (ou mesmo que ele vá acessar o mesmo arquivo). Deve-se ter cuidado ao usar este método em aplicações sensíveis à segurança.

Fiz um teste com esse método com o código abaixo:
File file = new File("C:\\TESTEJAVA\\test.txt");

System.out.println(Files.isWritable(new File("C:\\TESTEJAVA").toPath()));
file.createNewFile();

As permissões da pasta estavam as seguintes:

O resultado foi:

false
Exception in thread "main" java.io.IOException: Acesso negado
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at othertests.ChecarPermissaoTest.main(ChecarPermissaoTest.java:14)

Até ai o funcionamento do método está correto, sem permissão de gravar ou modificar, a exceção e o retorno false são esperados.
Após editar as permissões para:

O resultado foi true e o arquivo foi criado com sucesso.
Não sei se este método pode garantir em todos os cenários se a pasta permite ou não escrever nela, mas pelo teste acima, é possivel ver que funcionou corretamente.


text:
Q: How to parse string to a data type that willl be considered as time i have a variable that is string time = 7:00:00 AM. how can i convert this to a data type that will be considered as time so that i could use it to compare to other time with if statement. thank you for reading my silly question

A: You should read up on DateTime. It has a Parse method that accepts a string.
string time = "7:00:00 AM";
DateTime dateTime = DateTime.Parse(time);

A: This will work as well since you only need the time portion:
String time = "7:00:00 AM";

DateTime time = Convert.ToDateTime(time);

A: Try the following
String timeString = "7:00:00 AM"
DateTime dateTime = DateTime.ParseExact(timeString, "h:mm:ss tt", CultureInfo.InvariantCulture);

Can also check out http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx for more info.  Did this without testing it so YMMV as I'm not exactly sure how this will behave without a date component.


text:
Q: Problem installing nodejs on Centos (with yum and building from source) I am trying to install lastest nodejs on CentOS:
[root@test-visitele ~]# uname -a
Linux test-visitele 3.10.0-1127.el7.x86_64 #1 SMP Tue Mar 31 23:36:51 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[root@test-visitele ~]# sudo yum install epel-release
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.alpha-labs.net
 * epel: ftp.plusline.net
 * extras: mirror.23media.com
 * updates: mirror.23media.com
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be updated
---> Package epel-release.noarch 0:7-12 will be an update
--> Finished Dependency Resolution

Dependencies Resolved

=========================================================================================
 Package                   Arch                Version           Repository         Size
=========================================================================================
Updating:
 epel-release              noarch              7-12              epel               15 k

Transaction Summary
=========================================================================================
Upgrade  1 Package

Total download size: 15 k
Is this ok [y/d/N]: y
Downloading packages:
Delta RPMs disabled because /usr/bin/applydeltarpm not installed.
epel-release-7-12.noarch.rpm                                      |  15 kB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
  Updating   : epel-release-7-12.noarch                                              1/2
  Cleanup    : epel-release-7-11.noarch                                              2/2
  Verifying  : epel-release-7-12.noarch                                              1/2
  Verifying  : epel-release-7-11.noarch                                              2/2

Updated:
  epel-release.noarch 0:7-12

Complete!
[root@test-visitele ~]# sudo yum install nodejs
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centosmirror.netcup.net
 * epel: ftp.plusline.net
 * extras: mirror.23media.com
 * updates: mirror.23media.com
Resolving Dependencies
--> Running transaction check
---> Package nodejs.x86_64 1:6.17.1-1.el7 will be updated
--> Processing Dependency: nodejs = 1:6.17.1-1.el7 for package: 1:npm-3.10.10-1.6.17.1.1.el7.x86_64
---> Package nodejs.x86_64 2:10.20.1-1nodesource will be an update
--> Finished Dependency Resolution
Error: Package: 1:npm-3.10.10-1.6.17.1.1.el7.x86_64 (@epel)
           Requires: nodejs = 1:6.17.1-1.el7
           Removing: 1:nodejs-6.17.1-1.el7.x86_64 (@epel)
               nodejs = 1:6.17.1-1.el7
           Updated By: 2:nodejs-10.20.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.20.1-1nodesource
           Available: 2:nodejs-10.0.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.0.0-1nodesource
           Available: 2:nodejs-10.1.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.1.0-1nodesource
           Available: 2:nodejs-10.2.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.2.1-1nodesource
           Available: 2:nodejs-10.3.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.3.0-1nodesource
           Available: 2:nodejs-10.4.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.4.0-1nodesource
           Available: 2:nodejs-10.4.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.4.1-1nodesource
           Available: 2:nodejs-10.5.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.5.0-1nodesource
           Available: 2:nodejs-10.6.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.6.0-1nodesource
           Available: 2:nodejs-10.7.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.7.0-1nodesource
           Available: 2:nodejs-10.8.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.8.0-1nodesource
           Available: 2:nodejs-10.9.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.9.0-1nodesource
           Available: 2:nodejs-10.10.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.10.0-1nodesource
           Available: 2:nodejs-10.11.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.11.0-1nodesource
           Available: 2:nodejs-10.12.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.12.0-1nodesource
           Available: 2:nodejs-10.13.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.13.0-1nodesource
           Available: 2:nodejs-10.14.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.14.1-1nodesource
           Available: 2:nodejs-10.14.2-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.14.2-1nodesource
           Available: 2:nodejs-10.15.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.0-1nodesource
           Available: 2:nodejs-10.15.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.1-1nodesource
           Available: 2:nodejs-10.15.2-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.2-1nodesource
           Available: 2:nodejs-10.15.3-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.3-1nodesource
           Available: 2:nodejs-10.16.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.0-1nodesource
           Available: 2:nodejs-10.16.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.1-1nodesource
           Available: 2:nodejs-10.16.2-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.2-1nodesource
           Available: 2:nodejs-10.16.3-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.3-1nodesource
           Available: 2:nodejs-10.17.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.17.0-1nodesource
           Available: 2:nodejs-10.18.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.18.0-1nodesource
           Available: 2:nodejs-10.18.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.18.1-1nodesource
           Available: 2:nodejs-10.19.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.19.0-1nodesource
           Available: 2:nodejs-10.20.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.20.0-1nodesource
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

What am I doing wrong? How can I fix it? (I am trying to follow this instruction enter link description here)
UPDATE: trying to update npm gives nothing
# yum install nodejs npm
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centosmirror.netcup.net
 * epel: ftp.plusline.net
 * extras: mirror.23media.com
 * updates: mirror.23media.com
digitalocean-agent                                                | 3.3 kB  00:00:00
Resolving Dependencies
--> Running transaction check
---> Package nodejs.x86_64 2:10.20.1-1nodesource will be installed
---> Package npm.x86_64 1:3.10.10-1.6.17.1.1.el7 will be installed
--> Processing Dependency: nodejs = 1:6.17.1-1.el7 for package: 1:npm-3.10.10-1.6.17.1.1.el7.x86_64
--> Finished Dependency Resolution
Error: Package: 1:npm-3.10.10-1.6.17.1.1.el7.x86_64 (epel)
           Requires: nodejs = 1:6.17.1-1.el7
           Available: 1:nodejs-6.17.1-1.el7.x86_64 (epel)
               nodejs = 1:6.17.1-1.el7
           Available: 2:nodejs-10.0.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.0.0-1nodesource
           Available: 2:nodejs-10.1.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.1.0-1nodesource
           Available: 2:nodejs-10.2.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.2.1-1nodesource
           Available: 2:nodejs-10.3.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.3.0-1nodesource
           Available: 2:nodejs-10.4.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.4.0-1nodesource
           Available: 2:nodejs-10.4.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.4.1-1nodesource
           Available: 2:nodejs-10.5.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.5.0-1nodesource
           Available: 2:nodejs-10.6.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.6.0-1nodesource
           Available: 2:nodejs-10.7.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.7.0-1nodesource
           Available: 2:nodejs-10.8.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.8.0-1nodesource
           Available: 2:nodejs-10.9.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.9.0-1nodesource
           Available: 2:nodejs-10.10.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.10.0-1nodesource
           Available: 2:nodejs-10.11.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.11.0-1nodesource
           Available: 2:nodejs-10.12.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.12.0-1nodesource
           Available: 2:nodejs-10.13.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.13.0-1nodesource
           Available: 2:nodejs-10.14.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.14.1-1nodesource
           Available: 2:nodejs-10.14.2-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.14.2-1nodesource
           Available: 2:nodejs-10.15.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.0-1nodesource
           Available: 2:nodejs-10.15.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.1-1nodesource
           Available: 2:nodejs-10.15.2-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.2-1nodesource
           Available: 2:nodejs-10.15.3-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.15.3-1nodesource
           Available: 2:nodejs-10.16.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.0-1nodesource
           Available: 2:nodejs-10.16.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.1-1nodesource
           Available: 2:nodejs-10.16.2-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.2-1nodesource
           Available: 2:nodejs-10.16.3-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.16.3-1nodesource
           Available: 2:nodejs-10.17.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.17.0-1nodesource
           Available: 2:nodejs-10.18.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.18.0-1nodesource
           Available: 2:nodejs-10.18.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.18.1-1nodesource
           Available: 2:nodejs-10.19.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.19.0-1nodesource
           Available: 2:nodejs-10.20.0-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.20.0-1nodesource
           Installing: 2:nodejs-10.20.1-1nodesource.x86_64 (nodesource)
               nodejs = 2:10.20.1-1nodesource
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

Tried building from source, but it fails to compile:
[root@test-visitele node-v12.16.3]# make
make -C out BUILDTYPE=Release V=0
...

In file included from ../src/env-inl.h:27:0,
                 from ../src/api/async_resource.cc:2:
../src/aliased_buffer.h:32:22: error: expected type-specifier
           typename = std::enable_if_t<std::is_scalar<NativeT>::value>>
                      ^
../src/aliased_buffer.h:32:22: error: expected '>'
../src/aliased_buffer.h:65:54: error: template argument 3 is invalid
       const AliasedBufferBase<uint8_t, v8::Uint8Array>& backing_buffer)
                                                      ^
../src/aliased_buffer.h:112:45: error: template argument 3 is invalid
     Reference(AliasedBufferBase<NativeT, V8T>* aliased_buffer, size_t index)
                                             ^
../src/aliased_buffer.h:150:35: error: template argument 3 is invalid
     AliasedBufferBase<NativeT, V8T>* aliased_buffer_;
                                   ^
../src/aliased_buffer.h: In constructor 'node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::AliasedBufferBase(v8::Isolate*, size_t, size_t, const int&)':
../src/aliased_buffer.h:69:52: error: request for member 'GetArrayBuffer' in 'backing_buffer', which is of non-class type 'const int'
     v8::Local<v8::ArrayBuffer> ab = backing_buffer.GetArrayBuffer();
                                                    ^
../src/aliased_buffer.h:78:45: error: request for member 'GetNativeBuffer' in 'backing_buffer', which is of non-class type 'const int'
         const_cast<uint8_t*>(backing_buffer.GetNativeBuffer() + byte_offset));
                                             ^
../src/aliased_buffer.h: In member function 'node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference& node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::operator=(const NativeT&)':
../src/aliased_buffer.h:121:24: error: request for member 'SetValue' in '((node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference*)this)->node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::aliased_buffer_->', which is of non-class type 'int'
       aliased_buffer_->SetValue(index_, val);
                        ^
../src/aliased_buffer.h: In member function 'node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::operator NativeT() const':
../src/aliased_buffer.h:130:31: error: request for member 'GetValue' in '((const node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference*)this)->node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::aliased_buffer_->', which is of non-class type 'int'
       return aliased_buffer_->GetValue(index_);
                               ^
../src/aliased_buffer.h: In member function 'node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference& node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::operator+=(const NativeT&)':
../src/aliased_buffer.h:134:48: error: request for member 'GetValue' in '((node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference*)this)->node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::aliased_buffer_->', which is of non-class type 'int'
       const NativeT current = aliased_buffer_->GetValue(index_);
                                                ^
../src/aliased_buffer.h:135:24: error: request for member 'SetValue' in '((node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference*)this)->node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::aliased_buffer_->', which is of non-class type 'int'
       aliased_buffer_->SetValue(index_, current + val);
                        ^
../src/aliased_buffer.h: In member function 'node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference& node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::operator-=(const NativeT&)':
../src/aliased_buffer.h:144:48: error: request for member 'GetValue' in '((node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference*)this)->node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::aliased_buffer_->', which is of non-class type 'int'
       const NativeT current = aliased_buffer_->GetValue(index_);
                                                ^
../src/aliased_buffer.h:145:24: error: request for member 'SetValue' in '((node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference*)this)->node::AliasedBufferBase<NativeT, V8T, <template-parameter-1-3> >::Reference::aliased_buffer_->', which is of non-class type 'int'
       aliased_buffer_->SetValue(index_, current - val);
                        ^
../src/aliased_buffer.h: At global scope:
../src/aliased_buffer.h:254:50: error: template argument 3 is invalid
 typedef AliasedBufferBase<int32_t, v8::Int32Array> AliasedInt32Array;
                                                  ^
...
make[1]: Leaving directory `/root/node-v12.16.3/out'
make: *** [node] Error 2

A: I spent a long time looking at this today, and it appears the solution is 90% encapsulated in the nodesource documentation.  How to install v.14.x (since 15 is a bit too new and 14 is better field-tested)...

Node.js v14.x
As root
curl -fsSL https://rpm.nodesource.com/setup_14.x | bash -
No root privileges
curl -fsSL https://rpm.nodesource.com/setup_14.x | sudo bash -

After installing the version, with curl, though, you must flush your metadata-cache when doing yum update to trigger building with the newest, available dependencies.  Otherwise, yum update will keep preferring the old dependency, which is incompatible with the newer packages.  Clear the metadata cache with yum clean all, so, all together...
yum remove node npm nodesource-release-el7-1
curl -fsSL https://rpm.nodesource.com/setup_14.x | sudo bash -
yum clean all
yum update

A: You already seem to have an old version of npm installed which requires nodejs = 1:6.17.1-1.el7. Try upgrading npm also. It is strange that yum doesn't propose you to. Try this to force him to upgrade npm as well:
yum install nodejs npm


text:
Q: Looking for wordpress like visual editor Does anyone know of a script like the wordpress like visual editor!
So basically I want to give users the option to just write and adjust the font color size ... within a visual editor but also give them the option to see how it looks in the sourcecode!
Thanks for your answers

A: Try out http://ckeditor.com
1.CKEditor is a text editor to be used inside web pages. It's a WYSIWYG editor, which means that the text being edited on it looks as similar as possible to the results users have when publishing it. It brings to the web common editing features found on desktop editing applications like Microsoft Word and OpenOffice.
2.Because CKEditor is licensed under flexible Open Source and commercial licenses, you'll be able to integrate and use it inside any kind of application. This is the ideal editor for developers, created to provide easy and powerful solutions to their users.

A: Take a look at TinyMCE.

TinyMCE is a platform independent web based Javascript HTML WYSIWYG
  editor control released as Open Source under LGPL by Moxiecode Systems
  AB.
TinyMCE has the ability to convert HTML TEXTAREA fields or other HTML
  elements to editor instances. TinyMCE is very easy to integrate into
  other Content Management Systems.

You can also customize it to the functionality you need.


text:
Q: Why does my master row vanish when I set masterDetail as true in agGrid? When I set masterDetail as true,
my master rows vanish and my detail rows are automatically displayed.
I am unsure what properties are triggering this unexpected behavior, though, I am following the fundamental starting steps defined in ag grid documentation.
I set up masterDetail as true, and am getting the correct information as needed for the rowData. I have the columnDefs defined and also have agGroupCellRenderer set too. Would like a hint if this is a rendering issue.


text:
Q: How can I track previous responses? I'm working on a discord bot for a D&D game. I want the bot to be able to recognize when someone has recently used a command. This is what I have so far;
    const barid = require("./tavernarray.json")
    var tavernarray = barid.guests;

    message.channel.send('Tavern Keeper Emotes and replies;')

    if (message.member.roles.cache.has('770678762944725003')){
        if (tavernarray.includes(message.author.id)){
            message.channel.send("Weren't you just here?");
        } else;
            tavernarray.push(message.author.id);
            message.channel.send(` Welcome to the Tavern Guild Master ${message.author}`);
            setInterval (() => {
                tavernarray.pop(message.author.id)
            }, 30000)

    } else {
         message.channel.send("Error no role");
    }

From what I can tell the code works in that on the first command, we get the welcome message expected and the user ID is added to the array. On the second command though, there's a short delay and then we get both messages. Should I be using setTimeout instead of setInterval? Or is it an issue with using a .json array? I tried keeping the array in the program, but it just kept resetting every time I ran it.

A: Yes, you should be using setTimeout(). The reason you might have an issue is because the code is trying to remove the variable from the JSON array every 30 seconds which will cause two issues: higher memory usage and potential errors. The difference between setInterval() and setTimeout() is timeout executes the function once, whilst the other loops continuously until it is told to break. Along with this, the way you're using else is the issue. When you use else; (Take into note the semi colon), you're telling the code that if the ID isn't there, it shouldn't execute any code, as a semi colon indicates the end of a line of code. A snippet is shown below
if (tavernarray.includes(message.author.id)){
    message.channel.send("Weren't you just here?");
} else { // Instead of ; we'll use {}
    tavernarray.push(message.author.id);
    message.channel.send(` Welcome to the Tavern Guild Master ${message.author}`);
    setInterval (() => {
        tavernarray.pop(message.author.id)
    }, 30000)
}


text:
Q: MongoDB: how to find documents of same type with min value and $lt value I have the following docs in collection:
{'type': 1, 'price': 150, 'quantity': 10}
{'type': 1, 'price': 90, 'quantity': 5}

{'type': 2, 'price': 150, 'quantity': 10}
{'type': 2, 'price': 90, 'quantity': 10}
{'type': 2, 'price': 100, 'quantity': 5}

How could i find a doc of each type with min price and quantity lower than 10?
i need to query and get:
{'type': 1, 'price': 90, 'quantity': 5}
{'type': 2, 'price': 100, 'quantity': 5}

thanks

A: You could try this pipeline:

*

*Match document with a quantity lower than 10.

*Group the first document by type.

*Deconstructs the docs array

*Replace its root.

.
db.collection.aggregate([
  {
    "$match": {
      "quantity": {
        "$lt": 10
      }
    }
  },
  {
    "$group": {
      "_id": "$type",
      "docs": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    "$unwind": "$docs"
  },
  {
    "$replaceRoot": {
      "newRoot": "$docs"
    }
  }
])

Output:
[
  {
    "price": 100,
    "quantity": 5,
    "type": 2
  },
  {
    "price": 90,
    "quantity": 5,
    "type": 1
  }
]


text:
Q: whats the difference of type cast in the C language between two code code one is:
int a = 0x42500000;
float *f = (float *)&a;
printf("%f", *f);     //output 52.00000

code two is:
int a = 0x42500000;
float f = (float)a;
printf("%f", f);        //output 0.00000

why code two output 0.00000,who can tell me why?

A: First snippet interprets the contents of the memory location of a as if it were float, without casting. Unless you really know what you are doing, you don't want to do that, it's almost always a mistake.
The second snippet casts the value of a to float, which should give you the same value as the int. It really does do that. Your code gives me 1112539136.000000. What compiler are you using and getting 0 there?

A: The first cast tells the compiler to assume that the location where a is stored is a float and consider it likewise.
The second tells the compiler to assume that a is a float and consider it likewise.


text:
Q: converting string to reference points for canvas drawing I'm toying with the idea of being able to change a simple text diagram into coordinates for drawing in a HTML5 canvas.
Saying that I have the following Text diagram, for hypothetical purposes lets imagine this is stored in a textfield in a django model.
     1
     2
  3  L  4
   5 6 7
     8

What I want, is to be able to draw this as onto a canvas, by figuring out at what point each number (or letter) is in the string. Spaces are also important.
I have no idea where to even start.

A: Given the following string:
raw_str = """\
     1
     2
  3  L  4
   5 6 7
     8"""

You can start by building a character to coordinate mapping:
rows = s.split('\n')
mapping = {}
for y, r in enumerate(rows):
    for x, c in enumerate(r):
        if c != ' ':
           mapping[c] = (x, y)

BTW, the mapping building part can also be written in one line using dict comprehension:
{c: (x, y) for y, r in enumerate(rows) for x, c in enumerate(r) if c != ' '}

Now you should get a mapping like this:
{'1': (5, 0),
 '2': (5, 1),
 '3': (2, 2),
 '4': (8, 2),
 '5': (3, 3),
 '6': (5, 3),
 '7': (7, 3),
 '8': (5, 4),
 'L': (5, 2)}

You can encode it in JSON and pass it to the front end as input for some Javascript canvas drawing function.

A: You will need to create a data model that can be used to build an image with CANVAS. One such model is a two dimensional array.
You can write a function that parses the text area and uses the index of each element to define a relative index with other elements. This can be done by calling split with an empty string and iterating through the returned array. You can keep track of the row number and the column number while iterating. After each newline character ('\n') is found, you can reset the column count to 0.
Please note that if you'd like to have a relatively accurate text area image that contains different characters, you should use a monospace font such as Courier.
For example, given the following html page content:
<textarea id="area" cols="40" rows="10" style="font-family:Courier;">
            0
            0
            0
       0    0    0
         0  0  0
           0 0
            0
</textarea>

<canvas id="canvas" width="400px" height="100px" style="border:1px solid #000000;"></canvas>

This example uses a plain html text area instead of django but it shows you the general approach.
We can compute the two dimensional array assuming that a new line in the text area will be a new row in our CANVAS image:
var area = document.getElementById("area");
var text = area.textContent;

var array = text.split('');

var row = 0;
var col = 0;
var colArray = [];
var rowArray = [];
for(var i=0; i<array.length; i++)
{
    var c = array[i];
    if(c === '\n')
    {
        rowArray[row] = colArray;
        colArray = [];

        row++;
        col = 0;
    }
    else
    {
        colArray[col] = c;

        col++;
    }
}

You can then build your CANVAS image by traversing through the two dimensional array, where x is the x-coordinate and y is the y-coordinate.
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var r = 20;
var xScale = 20;
var yScale = 40;
console.log(rowArray);
for(y=0; y<rowArray.length; y++)
{
    var row = rowArray[y];
    for(var x=0; x<row.length; x++)
    {
        var val = row[x];
        if(val != " ")
        {
            //Draw something at position [x,y] (or some transformation of it)
            var xCoord = x * xScale;
            var yCoord = y * yScale;

            ctx.beginPath();
            ctx.arc(xCoord, yCoord, r, 0, 2 * Math.PI);
            ctx.fillStyle = 'pink';
            ctx.fill();
            ctx.fillStyle = 'black';
            ctx.textAlign = 'center';
            ctx.fillText(val, xCoord, yCoord+5);
            ctx.stroke();

        }
    }
}

You may need to use a different transformation for the x-coordinate than y-coordinate in CANVAS depending on how you'd like to display the image.
You can run this in JSFiddle to play with it.
Edit: added text fill as well. You can play around with the locations.
Edit 2: added center text positioning within the circle.


text:
Q: Android Xamarin C#: Https with ServiceStack and self signed certificates So I am changing all my Http webservices to Https using a self signed certificate for testing (for an android app I am making) and it is all working perfectly server side, I know this because I can add the certificate to my PC's certificate store and access the site perfectly, how ever I am having trouble on the client side when it comes to my android app making calls to it.
my Servicestack calls look like this:
        var client = new JsonServiceClient(stubServicesBaseUrl);

        return client.Get(new GetLastStatusUpdate()).StatusUpdates.Last();

and these used to work when it was only http but since I added code to add the self signed certificate to the android trusted credentials store the calls have stopped working and instead it seems that the request times out.
        byte[] certificate;
        using (var streamReader = new StreamReader(Assets.Open("ScoutTestCert.crt")))
        {
            using (var byteStream = new MemoryStream())
            {
                streamReader.BaseStream.CopyTo(byteStream);
                certificate = byteStream.ToArray();
            }
        }

        var installCertificate = KeyChain.CreateInstallIntent();
        installCertificate.PutExtra(KeyChain.ExtraCertificate, certificate);
        StartActivity(installCertificate);

The above code adds the certificate to the android trusted store in the "user" section and allows me to navigate to the site through the internet app on the androidEmulator without problem, so it seems the problem only appears when trying to make ServiceStack calls in my apps code.
Am I missing something in my code, like extra set up that service stack needs or something like that? I have been struggling with this problem for a few days now and at a real road block!
I am trying to keep the webservice calls as servicestack as I want it to be PCL rather than android specific code.
Thanks.

A: ServiceStack's .NET Service Clients uses .NET's BCL's built-in HttpWebRequest in order to have the self-signed certificates work with .NET HTTP Clients you need to register a custom Certificate Validation Callback, e.g. the callback below would enable all certificates to succeed:
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, certificate, chain, sslPolicyErrors) => true;

But you would want to limit the validation down to work with your self-signed certificate.
An alternative to using ServiceStack's HttpWebRequest based Service Client is to use the PCL HttpClient-based JsonHttpClient instead which has the benefit where it can be configured to use ModernHttpClient with:
JsonHttpClient.GlobalHttpMessageHandlerFactory = () =>
    new NativeMessageHandler()

Which instead of using the .NET HTTP Client stack uses the native HTTP libraries available on the underlying iOS and Android platforms. This should then let you use any certificates registered with Android.
In order to use untrusted self-signed certificates registered in .NET with ModernHttpClient you would need to use the pro version of ModernHttpClient as mentioned on this thread.


text:
Q: Require Password to Open Access Form I have a few forms in my Access database that only a few team members should be using I wrote the following to password-protect those forms, but if you enter the wrong password or hit cancel on the pop-up, it will open the form anyway.
How can I prevent Access from loading the form unless you enter the correct password?
Private Sub Form_Load()
    Dim strInput As String
    Dim strMsg As String

    Beep
    strMsg = "This function requires a password." & vbCrLf & vbLf & "Please see your manager for assistance."
    strInput = InputBox(Prompt:=strMsg, title:="Password:")
    If strInput = "administrator" Then 'password is correct
        DoCmd.OpenForm "AddNewRule"
    Else 'password is incorrect
        MsgBox "Incorrect Password!" & vbCrLf & vbLf & "Please see your manager for assistance", vbCritical, "Invalid Password"
        Exit Sub
    End If
End Sub

A: Instead of Load, use the Open event:
Private Sub Form_Open(Cancel As Integer)

There you can set Cancel = True, then the form won't be opened.
But note that if you open the form from somewhere else with DoCmd.OpenForm, it will raise an error that you need to trap or ignore.

Note that DoCmd.OpenForm "AddNewRule" in the success case is wrong, you are already opening the form.


text:
Q: How to delete files owned by other users windows 7? I have an external hard drive that I used to install programs on, I have since formatted my c drive and use the external drive as a storage only drive. There are however two remnants left over from the previous install on the external hd.
One is a folder full of Windows update files and the other is a Program files folder. I tried to delete the folder but it would give me the "need permissions" dialogue box and would then tell me I need permissions from user "S- ... #####". I did an ownership change on the folder and sub folders/files but that didn't work. Its still says I need permission from the new owner, even though I am the owner ... it does not make any sense. I cannot format the drive either as I have other files on it.
How can I force these folders to deletion?


text:
Q: Counting occurrences across a record in ArcGIS 10.0 I'm a student at Millersville University, PA studying for a BA in Geography with a concentration in GIS. I've stumbled across this site for questions I've had over the past year or so with getting introduced to ArcGIS. So thank you all here for helping a student out :)
I have come across a problem that I can't figure out and my textbook didn't offer any help so I'm hoping one of you can.
I have a table which consists of 3 attribute joins, and I have a text field which has 2 unique values. I want to create a field in which I can summarize the number of times a particular text occurs.
For Example: Jx = Join #
ObjectID 1 |J1: A | J2: A | J3: B | CountFldA: 2
ObjectID 2 |J1: B | J2: B | J3: A | CountFldA: 1

I have a feeling that the answer lies somewhere in python but I have no formal experience in it.

A: You could concatenate multiple fields together into a new combined field and use 'InStr' inside the Field Calculator (VBScript) to count the number of occurrences of a specific character or string.  For example, instr([Combined],"A") would return the number of "A"s in the Combined field.  Or I suppose you could use InStr on each individual joined field and then add them up.  instr([Field1],"A") + instr([Field2,"A") and so on.


text:
Q: Add syntax into if statement in PHP I want to add these code into if statement in php. Can it be done?

<?php if ($wa[custom_132] == "1") { ?>

<?php } ?>

It should be like this
<?php
if($_COOKIE["size"]>800)
  echo "I want to put those code inside here";
else
  echo "Not decide yet";
?>

Can this be done because i want to display different image banner in the slideshow based on the resolution of the device monitor. Thanks

A: Is this what you are after? If not, please clarify your requirements and correct the syntax errors in your question.
<?php if($_COOKIE["size"]>800) {
    echo '';
    if ($wa[custom_132] == "1") {
        echo '

        ';
    }
?>

More info here: http://php.net/manual/en/control-structures.if.php (esp. see comment #1)


text:
Q: Why my Google Playstore IAP application always use Test Card, even when I use real product ID and with any other account I create application with IAP feature for Android with Unity, I have set up everything and tested it and its already works in testing environment with my tester account.
But when I test with real product ID and upload it on Open Testing (Beta), and login with any other account that is not include as tester, the app still offers pay with test card, I want to test it with real cards or any store option.
for case above, I use android 10, and when I use my other phone that is on android 7, it never use test card, even with my tester account O_o
anybody knows about this or experience the same thing?
or it will only get out the test card if I publish it to production?
(right now its on Open Testing on google dev console)
https://i.stack.imgur.com/i6vXg.jpg


text:
Q: Blank string in c++ #include <iostream>
#include <string>

using namespace std;

int main()
{
    int userInput;
    string numberType;
    cout << "Enter a number and I will Check to see if it is odd or even" << endl;
    cin >> userInput;
    if (userInput % 2 == 0)
    {
        string numberType = "Even";
    }
    else
    {
        string numberType = "Odd";
    }
    cout << "The number you input is " << numberType << endl;
    return 0;
}

I'm trying to output the manipulated string value but the string that's output in the last line comes out blank?

A: In your if and else blocks, you are actually creating new variables with the name of numberType, and that those new variables hide the original numberType you had previously declared. Any changes you make on those variables will NOT reflect to the original numberType, as they do not refer to it.
To solve that problem, remove the string parts (the types, as having these denotes that you are defining new variables) as you don't want to define those new variables, and want use the previously defined numberType.
if (userInput % 2 == 0)
{
    numberType = "Even";   // Look ma, no string!
}
else
{
    numberType = "Odd";   // Also here ma!
}

With the modified and fixed code, you are now referring to the numberType where you intend to put the values "Even" or "Odd".
...
int userInput;
string numberType;   // This is now where the values be put in
cout << "Enter a number and I will Check to see if it is odd or even" << endl;
...

This should now give you the correct and desired output.

A: The problem is that you're redeclaring numberType. This actually declares a new numberType, since it is in a different scope.
What you want to do is this
if (userInput % 2 == 0)
{
    numberType = "Even";
}
else
{
    numberType = "Odd";
}

A: Beacuse you re declared numberType this will become local to if-else block,In this case the variable local to if-else will get modified.So simply use,
int main()
{
    int userInput;
    string numberType;
    cout << "Enter a number and I will Check to see if it is odd or even" << endl;
    cin >> userInput;
    string numberType;        //variable local to function .You can modify this variable anywhere inside this function

    if (userInput % 2 == 0) {
       numberType = "Even";     //here you will refer already declared  variable local function. So no need to declare it here again as that will be local to this block.
    } else {
       numberType = "Odd";
    }
    cout << "The number you input is " << numberType << endl; // Print modified value of string.

    return 0;
}

A: numberType the one whose value is updated is local in if and else block.
remove string
if (userInput % 2 == 0)
{
    numberType = "Even";
}
else
{
    numberType = "Odd";
}

A: Firstly, you're redeclaring numberType, meaning it only exists in the inner scope it is declared in; effectively, numberType exists only within either the if or else block. You then print out the original outer scoped numberType which was simply default constructed. To fix this, don't redeclare it, but assign it a different value:
string numberType;
...
if(userInput % 2 == 0) {
    numberType = "Even";
} else {
    numberType = "Odd";
}


text:
Q: MFC localization not working with MUI install of Windows 7 OK, so we're writing our MFC application to make use of the built-in localization support with satellite DLL's since MFC 7. Everything seem to be working fine, except that my Windows 7 Enterprise Edition install with MUI support and using a Swedish UI instead of an English UI still displays the English UI in our application.
The application uses Swedish as its default language, with an English localization DLL in the form AppNameENU.dll, so MFC is actually intentionally switching to English language under these circumstances, as if it's not caring for the user choice in the MUI-enabled Windows OS, and only the default shipping language of the Windows install?
From the MSDN page on this (the link above), I read it as MFC should actually take these settings into account though, but I'm not 100% sure. Can someone please clarify?

A: It's because the MFC support for language selection has a design bug: It will decide to load resources from the exe only if no DLL match user OR system language.
In your case: It sets up its (ordered) list of languages as such:

*

*Swedish (User language)

*English (System language)

Then it looks up your DLLs (Bug: only the dlls, not the exe!): No match for Swedish. But there's a match for English!
Solution: Use my CLanguageSupport class. It works fine even in your use case.
Feel free to use it. You'll need only a couple of minutes to incorporate it into your app and it uses the exact same DLL scheme as the one you already implemented. (Hint: Don't forget the step where you must get rid of the CWinApp::InitInstance() call!)
In addition, if you are interested (this is optional), you can get an automatic languages menu to let user pick his own preference in case the default is not what he wants.
And if you're looking for a great tool to help you manage your translations, think appTranslator ;-)
HTH,


text:
Q: Connect to SQL Database 2008R2 via a subdomain I actually have a remote database acess via TCP/IP
I've searched the web, but I only get results regarding remote SQL by IP.
So, is there a way to make my IP acessible from a sub-domain (e.q. bd.domain.com) ?
Thanks

A: Agreed, this is a DNS resolution issue, you need to make sure that your client can resolve the server.bd.domain.com name to the correct IP.  You need an A record in the bd domain's DNS in order for this to work properly.


text:
Q: Simple cross-tabulation in pandas I stumbled across pandas and it looks ideal for simple calculations that I'd like to do. I have a SAS background and was thinking it'd replace proc freq -- it looks like it'll scale to what I may want to do in the future. However, I just can't seem to get my head around a simple task (I'm not sure if I'm supposed to look at pivot/crosstab/indexing - whether I should have a Panel or DataFrames etc...). Could someone give me some pointers on how to do the following:
I have two CSV files (one for year 2010, one for year 2011 - simple transactional data) - The columns are category and amount
2010:
AB,100.00
AB,200.00
AC,150.00
AD,500.00

2011:
AB,500.00
AC,250.00
AX,900.00

These are loaded into separate DataFrame objects.
What I'd like to do is get the category, the sum of the category, and the frequency of the category, eg:
2010:
AB,300.00,2
AC,150.00,1
AD,500.00,1

2011:
AB,500.00,1
AC,250.00,1
AX,900.00,1

I can't work out whether I should be using pivot/crosstab/groupby/an index
etc... I can get either the sum or the frequency - I can't seem to get both... It gets a bit more complex because I would like to do it on a month by month basis, but I think if someone would be so kind to point me to the right technique/direction I'll be able to go from there.

A:
v0.21 answer

Use pivot_table with the index parameter:
df.pivot_table(index='category', aggfunc=[len, sum])

           len   sum
         value value
category
AB           2   300
AC           1   150
AD           1   500

<= v0.12

It is possible to do this using pivot_table for those interested:
In [8]: df
Out[8]:
  category  value
0       AB    100
1       AB    200
2       AC    150
3       AD    500

In [9]: df.pivot_table(rows='category', aggfunc=[len, np.sum])
Out[9]:
            len    sum
          value  value
category
AB            2    300
AC            1    150
AD            1    500

Note that the result's columns are hierarchically indexed. If you had multiple data columns, you would get a result like this:
In [12]: df
Out[12]:
  category  value  value2
0       AB    100       5
1       AB    200       5
2       AC    150       5
3       AD    500       5

In [13]: df.pivot_table(rows='category', aggfunc=[len, np.sum])
Out[13]:
            len            sum
          value  value2  value  value2
category
AB            2       2    300      10
AC            1       1    150       5
AD            1       1    500       5

The main reason to use __builtin__.sum vs. np.sum is that you get NA-handling from the latter. Probably could intercept the Python built-in, will make a note about that now.

A: Assuming that you have a file called 2010.csv with contents
category,value
AB,100.00
AB,200.00
AC,150.00
AD,500.00

Then, using the ability to apply multiple aggregation functions following a groupby, you can say:
import pandas
data_2010 = pandas.read_csv("/path/to/2010.csv")
data_2010.groupby("category").agg([len, sum])

You should get a result that looks something like
          value
            len  sum
category
AB            2  300
AC            1  150
AD            1  500

Note that Wes will likely come by to point out that sum is optimized and that you should probably use np.sum.


text:
Q: htaccess help for directory parsing I am a newbie to .htaccess / mod_rewrite and have run into a problem..
I have just updated my website to a new Wordpress install, but have my old site running on a separate server.. On the old server, I have 4 names sites running.. I was successful in using multiple rewrite rules above the WordPress rewrite code, until some provides a URL not in my list which then just goes to the new Wordpress site with an item not found post, instead of redirecting..
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule   "^ONE(.*)$"  "http://old.site.com/ONE/$1"  [R,L,NC]
RewriteRule   "^TWO(.*)$"  "http://old.site.com/TWO/$1"  [R,L,NC]
RewriteRule   "^THREE(.*)$"  "http://old.site.com/THREE/$1"  [R,L,NC]
</IfModule>

# BEGIN WordPress
# www.newsite.com
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

How do I make fix this so that the old sites in the list are redirected, ELSE if the URL such as http://www.oldsite.com/FOUR is redirected to either an Static error page or just to the www.newsite.com..
Thanks in Advance
k.

A: In the first block you can create another catch-all redirect rule:
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule ^ONE(.*)$ http://old.site.com/ONE/$1 [R,L,NC]
RewriteRule ^TWO(.*)$ http://old.site.com/TWO/$1 [R,L,NC]
RewriteRule ^THREE(.*)$ http://old.site.com/THREE/$1 [R,L,NC]

# catch-all rule
RewriteRule ^ http://newsite.com/ [R,L]
</IfModule>

You can now even remove all WP rules as those rules will not be even used at this point.


text:
Q: Define a servicemix xml for a websocket server I try to develop a websocket server using just XML in servicemix, but I can't get it working. Not even close.
I have a rest based example that I would like to turn into a websocket server.
I already tried a few things but the result is always that i get a 404 back of no connection at all. I assume that i have to register a websocket service as I did with the http service, but I cannot find any documentation how to do that in a similar way as in my example.
Any suggestions would be greatly appreciated.
Here is the example:
<?xml version="1.0" encoding="UTF-8"?>
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:camel="http://camel.apache.org/schema/spring"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:osgi="http://www.springframework.org/schema/osgi"
  xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://camel.apache.org/schema/spring
     http://camel.apache.org/schema/spring/camel-spring.xsd
     http://www.springframework.org/schema/util
     http://www.springframework.org/schema/util/spring-util.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/osgi
     http://www.springframework.org/schema/osgi/spring-osgi.xsd">

  <osgi:reference id="httpService" interface="org.osgi.service.http.HttpService"/>

  <bean id="SelectCamelServlet"
    class="org.apache.camel.component.servlet.CamelHttpTransportServlet">
  </bean>

  <bean class="org.apache.camel.component.servlet.osgi.OsgiServletRegisterer"
    init-method="register"
    destroy-method="unregister">
    <property name="alias" value="/cmsa"/>
    <property name="httpService" ref="httpService"/>
    <property name="servlet" ref="SelectCamelServlet"/>
    <property name="servletName" value="SelectCamelServlet"/>
  </bean>
<bean id="datasource"
    class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="org.postgresql.Driver"/>
    <property name="url" value="jdbc:postgresql://localhost/postgres"/>
    <property name="username" value="postgres"/>
    <property name="password" value="postgres"/>
  </bean>

  <!-- Configure the Camel SqlComponent to use the JDBC datasource. -->
  <bean id="sqlcomponent"
    class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="datasource"/>
  </bean>

  <!-- Configure a camelContext with logic. -->
  <camelContext useMDCLogging="true" xmlns="http://camel.apache.org/schema/spring">

    <restConfiguration bindingMode="json" component="servlet">
      <endpointProperty key="servletName" value="SelectCamelServlet" />
      <dataFormatProperty key="prettyPrint" value="false"/>
    </restConfiguration>

    <rest path="/density">
      <get uri="">
        <to pattern="InOut" uri="direct:get" />
      </get>
    </rest>

    <!-- Configure a route that reads an argument from http (GET),
         uses that in a query and returns the dataset in JSON format. -->
    <route id="oefenen_route">

      <from uri="direct:get"/>

      <!-- Specify content-type to control the body's character encoding.
           If this is omitted, the body's data is base64 encoded. -->
     <setHeader headerName="Content-Type">
        <simple>application/json; charset=utf-8</simple>
      </setHeader>

      <!-- Run the query. -->
      <to uri="sqlcomponent:select sensor, aantal as density from cmsa order by sensor?
               outputType=SelectList&
               greedy=true&
               useIterator=false"/>

    </route>
  </camelContext>
</beans>

I solved my own question as follows:
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:camel="http://camel.apache.org/schema/spring"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:osgi="http://www.springframework.org/schema/osgi"
  xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://camel.apache.org/schema/spring
     http://camel.apache.org/schema/spring/camel-spring.xsd
     http://www.springframework.org/schema/util
     http://www.springframework.org/schema/util/spring-util.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/osgi
     http://www.springframework.org/schema/osgi/spring-osgi.xsd">

  <osgi:reference id="wsService" interface="org.osgi.service.http.HttpService"/>

  <bean id="CamelWsServlet"
    class="org.apache.camel.component.atmosphere.websocket.CamelWebSocketServlet">
  </bean>

  <bean class="org.apache.camel.component.servlet.osgi.OsgiServletRegisterer"
    init-method="register"
    destroy-method="unregister">
    <property name="alias" value="/websocket"/>
    <property name="httpService" ref="wsService"/>
    <property name="servlet" ref="CamelWsServlet"/>
    <property name="servletName" value="CamelWsServlet"/>
  </bean>

  <camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="atmosphere-websocket:///hola"/>
        <to uri="atmosphere-websocket:///hola?sendToAll=true"/>
    </route>
  </camelContext>
</beans>

A: The second listing answers my question. I did almost the same as in the first listing, except the the used class is different. This works fine if I put this in the servicemix deploy directory as an xml file.


text:
Q: Update Row By Row number I am having a table with one column only
id
--
1
2
3
5
5
I want to update the value of 4 th row  to "4"
so required output is :
id
--
1
2
3
4
5
how can i achieve this

A: WITH CTE AS
(
    SELECT ID, RN = ROW_NUMBER() OVER (ORDER BY ID ASC)
    FROM dbo.TableName
)
UPDATE CTE SET ID = RN
WHERE ID <> RN

Demo
That will update all "incorrect" ID's according to their row number that is determined by the order.


text:
Q: Custom exception handler for NoHandlerFoundException is not working without @EnableWebMvc I want to override html error page for 404 responses as an JSON response. When i use @ControllerAdvice without @EnableWebMvc it is not working.
@EnableWebMvc   // if i remove this, it is not working
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<ZeusErrorDTO> noHandlerFoundException(
                    HttpServletRequest request,
                    NoHandlerFoundException exception) {

        ErrorDTO errorDTO = new ErrorDTO();
        return new ResponseEntity<>(errorDTO, HttpStatus.NOT_FOUND);
    }
}

Is there an option for custom exception handling without @EnableWebMvc, because it overrides Spring configurations which are declared inside application.yml.

A: This is happening because, using @EnableWebMvc disables MVC autoconfiguration and asks you to provide exactly what You want. Have a look at this link
You can either use other means to customize your configuration, such as a @Configuration
See Boot's WebMvcAutoConfiguration to find out what the defaults are, and copy over the pieces that you need.
This Link might help You as well -> LINK

What should you do when you want to customize your beans? As usual, extend WebMvcConfigurerAdapter (annotate the new class with @Component) and do your customizations.
  So, bottom line of the particular problem: Don't use @EnableWebMvc in
  Spring Boot, just include spring-web as a maven/gradle dependency and
  it will be autoconfigured.

This answer on stackoverflow shows how to do this .. check this LINK3

A: Normally @utkusonmez answer works fine but not in my case, as I am using swagger. So all I did is add following properties in my application.properties file
spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern=/swagger*

Now both NoHandlerFoundException and swagger-ui works fine.

A: I easily resolved problem by adding one of configurations in application.yml.
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

or
spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern: /static

If you don't restrict Spring and no handler matches with your request, then spring tries to look for static content.


text:
Q: Probability that station select a different radio frequencies Question: Two synchronous stations use frequency-hopping to select at random (with probability 1/n one of n frequencies. What is the probability that the stations select a different frequency?
My approach to solving this would be that the probability to select same frequency would be 1/n, so it for the probability of selecting a different frequency would be 1 - 1/n
Is my understanding correct? Or would it be n/(nC2) for same frequency?

A: Yes, correct.
The probability that the 2 Stations select the same station is
$$n\frac{1}{n}\frac{1}{n}=\frac{1}{n}$$
thus the probability that the two stations select a different frequency is the complementary:
$$1-\frac{1}{n}$$


text:
Q: i want to convert records in a table into xml in sql server as shown below I want to convert records in a table into XML in sql server as shown below.
Table
countryid   stateid siteid  value
1   1   1   11
1   1   2   22
1   2   1   55
1   2   2   66
2   1   1   111
2   1   2   222
2   2   1   555
2   2   2   666
3   1   1   100
3   1   2   200
3   2   1   500
3   2   2   600

I want to convert this data into XML as shown below.
<data>
    <countrydata>
        <countryid> 1 </countryid>
        <stateid> 1 </stateid>
        <siteid> 1 </siteid>
        <value> 11 </value>
    </countrydata>
    <countrydata>
        <countryid> 1 </countryid>
        <stateid> 1 </stateid>
        <siteid> 2 </siteid>
        <value> 22 </value>
    </countrydata>
    <countrydata>
        <countryid> 1 </countryid>
        <stateid> 2 </stateid>
        <siteid> 1 </siteid>
        <value> 55 </value>
    </countrydata>
    <countrydata>
        <countryid> 1 </countryid>
        <stateid> 2 </stateid>
        <siteid> 2 </siteid>
        <value> 66 </value>
    </countrydata>
</data>

This XML is what I expect from records with countryid = 1..
Similarly I need different XML records with different countryids.

A: Have a look at FOR XML (SQL Server)

A SELECT query returns results as a rowset. You can optionally
  retrieve formal results of a SQL query as XML by specifying the FOR
  XML clause in the query.

Also, look through the examples found at Use RAW Mode with FOR XML and more specifically at

*

*Example: Retrieving Product Model Information as XML

*Example: Renaming the  Element

*Example: Specifying a Root Element for the XML Generated by FOR
XML
How about something like
SELECT [countryid], [stateid], [siteid], [value]
FROM Table1
FOR XML RAW ('countrydata'), ELEMENTS, ROOT ('data')

SQL Fiddle DEMO

A: If you want the XML per countryid, You should GROUP your data based on countryid and then use a co-related sub-query to get the xml for that group using something like this.
;WITH yourtable as (
select 1 as countryid,1 as stateid,1 as siteid,1 as value
UNION ALL
select 2 as countryid,1 as stateid,1 as siteid,1 as value
)
SELECT countryid, (SELECT countryid,stateid,siteid,value
FROM yourtable t2
WHERE t2.countryid = t1.countryid
FOR XML PATH('countrydata'),ROOT('data'),ELEMENTS,TYPE) as xmlval
FROM yourtable t1
GROUP BY countryid


text:
Q: Image breaking its parent grid using Tkinter I am creating some GUI using Tkinter and now after loading the image my child 'self.panel' grid which has image in it is increasing the parent grid which is 'self.top_left_frame_left_img_container'. Additionally, the image is adding some gray area which is not the part of the image. Could anyone help me with adjusting the image size according to its parent size excluding the gray space as well. The image should take the available space of its parent without breaking it.
def setImage(self):

    self.img = PIL.ImageTk.PhotoImage(PIL.Image.open(self.image_path))
    self.panel = tk.Label(self.top_left_frame_left_img_container, image= self.img)
    #self.panel.pack(side='top')
    self.panel.grid(row=0, column=0, rowspan=1, sticky='nsew', padx=2, pady=2)
    self.top_left_frame_left_img_container.grid_columnconfigure(0, weight=1)
    self.top_left_frame_left_img_container.grid_rowconfigure(0, weight='1')

GUI Before

GUI After


text:
Q: How to programatically copy 'Master Page Gallery' I have 2 site collections with matching "Master Page Gallery" lists and one has corrupted values. To fix this I wish to overwrite all files and folders with the data found in the good list.
I have disabled moderation & versioning.
I skip the "Forms" folder & the "v4.master"
I use
  private void start(SPList good, SPList bad){
      SPFolder badRoot = bad.RootFolder;

      foreach(SPFolder f in good.RootFolders.SubFolders){
          If(f.name != "Forms") badRoot= MyRecursive(f, badRoot);
      }

      foreach(SpFile file in good.files)
           badRoot = CopyFiles(file, badRoot);
  }

  Private SPFolder MyRecursive(SPFolder f, SPFolder badRoot){
       foreach(SPFolder sub in f.subfolders)
             badRoot = MyRecursive(sub,badRoot.SubFolders[f.url])

       foreach(SPFile file in f.Files)
              badRoot = CopyFile(file,badRoot);

       return badRoot;
  }

  private void CopyFile(SPFile file, SPFolder folder){
      Try{
         folder.Files.Add(file.url , file.OpenBinaryStream(), file.Properties, true);
         folder.update()
      }catch{}
      return folder;
  }

I get all the files & all the metadata correct except Existing 'Forwardlinks' become "00000000-0000-0000-0000-000000000000" and exisiting 'Backwardlinks' become null.
Does anybody know how to correct this? Or a better method?


text:
Q: VNH5019A Flyback issue on custom PCB I have a custom high power PCB I recently designed and am currently testing. It is designed to use 2 linear actuators link. I am using a VNH6019A H-bridge to control them. They operate simply as -12v goes up, 12v goes down (wrt each terminal).
My schematic for the bridge is:

I am using the suggested capacitor size for the driver:
"Note:
The value of the blocking capacitor (C) depends on the application conditions and defines voltage and current ripple onto supply line at PWM
operation. Stored energy of the motor inductance may flyback into the blocking capacitor, if the bridge driver goes into 3-state. This causes a
hazardous overvoltage if the capacitor is not big enough. As basic orientation, 500 μF per 10 A load current is recommended."
I am using one 12V power supply, which is used for the main power to the actuators, as well as using an "all in one" switching 5v regulated power supply for my logic level components.
I am using an intelligent LCD display by 4DSystems to control the board, so it has internal decoupling and is powered from the 5v line.
Power regulator schematic:

LCD connector schematic:

Since my actuators can draw a maximum of 10A, I am using a 500uF electrolytic capacitor.
When I hook up one (or two) actuators, they work fine with no noticeable issues. However, if I use one (same issue with two) actuators, and hook up a scope to the 5v output of my regulator when the actuator stops moving, I get a nasty voltage spike on the 5v line up to 16v.
I have sufficient decoupling, as there is a small (<20mA) sag when the actuators turn on. Since it is when the actuators stop, it must(?) be flyback from the inductive load.
My questions:

*

*Why is this occurring when I am using significantly higher flyback caps than required (my single actuator with no load draws only ~800mA).

*Since there is such a large spike, why is my LCD or anything else powered by the 5v line getting damaged?

*What is the solution?

Thanks
EDIT: I assume the easiest is just to throw a flyback diode across the actuator terminals. Assuming that works, I would still like to know number 1 and 2
EDIT2: Nevermind, I can't do that from an h-bridge, since the polarity switches. Back to square one.

A:
I'm not experienced with using scopes. I have a single probe connected
  to channel one. This probe has a ground alligator clip. This I clipped
  to a ground standoff on the pcb.

That forms a small loop antenna suitable for picking up magnetic field impulses and it is highly likely that what you are seeing is a phantom. The currents in your circuit are around 10 amps (and with quite fast edges) and this type of scope probing problem is commonplace to find on switching converters. You do need to use a ground plane and proper probing on a circuit like this or you'll be fighting an uphill battle.
Here's something you can try. Connect the alligator clip to the scope probe end to form a short. Now connect the scope probe (with intact alligator clip) to the grounding post on your circuit. What would you expect to see and what do you actually see?


text:
Q: Undefined Index error while uploading a file using php
Warning: move_uploaded_file(../uploads/IMG_23052014_111633.png): failed to open stream: No such file or directory in C:\wamp\www\test.co\getfile.php on line 8
  Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\php9EF8.tmp' to '../uploads/IMG_23052014_111633.png' in C:\wamp\www\test.co\getfile.php on line 8

how to get rid of it?
HTML code:
<form action="getfile.php" method="post" enctype="multipart/form-data" ><br>
Type (or select) Filename: <input type="file" name="uploadFile">
<input type="submit" value="Upload File">
</form>

PHP code:
<html>
<head>
<title>Process Uploaded File</title>
</head>
<body>
<?php
move_uploaded_file ($_FILES['uploadFile'] ['tmp_name'],
"../uploads/{$_FILES['uploadFile'] ['name']}")
?>
</body>
</html>


text:
Q: In hiveql, what is the most elegant/performatic way of calculating an average value if some of the data is implicitly not present? In Hiveql, what is the most elegant and performatic way of calculating an average value when there are 'gaps' in the data, with implicit repeated values between them? i.e. Considering a table with the following data:
+----------+----------+----------+
| Employee |   Date   |  Balance |
+----------+----------+----------+
| John     | 20181029 |   1800.2 |
| John     | 20181105 |  2937.74 |
| John     | 20181106 |     3000 |
| John     | 20181110 |     1500 |
| John     | 20181119 |   -755.5 |
| John     | 20181120 |     -800 |
| John     | 20181121 |     1200 |
| John     | 20181122 |     -400 |
| John     | 20181123 |     -900 |
| John     | 20181202 |    -1300 |
+----------+----------+----------+

If I try to calculate a simple average of the november rows, it will return ~722.78, but the average should take into account the days that are not shown have the same balance as the previous register. In the above data, John had 1800.2 between 20181101 and 20181104, for example.
Assuming that the table always have exactly one row for each date/balance and given that I cannot change how this data is stored (and probably shouldn't since it would be a waste of storage to write rows for days with unchanged balances), I've been tinkering with getting the average from a select with subqueries for all the days in the queried month, returning a NULL for the absent days, and then using case to get the balance from the previous available date in reverse order. All of this just to avoid writing temporary tables.

A: Step 1: Original Data
The 1st step is to recreate a table with the original data. Let's say the original table is called daily_employee_balance.
daily_employee_balance
use default;
drop table if exists daily_employee_balance;
create table if not exists daily_employee_balance (
    employee_id string,
    employee string,
    iso_date date,
    balance double
);

Insert Sample Data in original table daily_employee_balance
insert into table daily_employee_balance values
('103','John','2018-10-25',1800.2),
('103','John','2018-10-29',1125.7),
('103','John','2018-11-05',2937.74),
('103','John','2018-11-06',3000),
('103','John','2018-11-10',1500),
('103','John','2018-11-19',-755.5),
('103','John','2018-11-20',-800),
('103','John','2018-11-21',1200),
('103','John','2018-11-22',-400),
('103','John','2018-11-23',-900),
('103','John','2018-12-02',-1300);

Step 2: Dimension Table
You will need a dimension table where you will have a calendar (table with all the possible dates), call it dimension_date. This is a normal industry standard to have a calendar table, you could probably download this sample data over the internet.
use default;
drop table if exists dimension_date;
create external table dimension_date(
    date_id                 int,
    iso_date                string,
    year                    string,
    month                   string,
    month_desc              string,
    end_of_month_flg        string
);

Insert some sample data for entire month of Nov 2018:
insert into table dimension_date values
(6880,'2018-11-01','2018','2018-11','November','N'),
(6881,'2018-11-02','2018','2018-11','November','N'),
(6882,'2018-11-03','2018','2018-11','November','N'),
(6883,'2018-11-04','2018','2018-11','November','N'),
(6884,'2018-11-05','2018','2018-11','November','N'),
(6885,'2018-11-06','2018','2018-11','November','N'),
(6886,'2018-11-07','2018','2018-11','November','N'),
(6887,'2018-11-08','2018','2018-11','November','N'),
(6888,'2018-11-09','2018','2018-11','November','N'),
(6889,'2018-11-10','2018','2018-11','November','N'),
(6890,'2018-11-11','2018','2018-11','November','N'),
(6891,'2018-11-12','2018','2018-11','November','N'),
(6892,'2018-11-13','2018','2018-11','November','N'),
(6893,'2018-11-14','2018','2018-11','November','N'),
(6894,'2018-11-15','2018','2018-11','November','N'),
(6895,'2018-11-16','2018','2018-11','November','N'),
(6896,'2018-11-17','2018','2018-11','November','N'),
(6897,'2018-11-18','2018','2018-11','November','N'),
(6898,'2018-11-19','2018','2018-11','November','N'),
(6899,'2018-11-20','2018','2018-11','November','N'),
(6900,'2018-11-21','2018','2018-11','November','N'),
(6901,'2018-11-22','2018','2018-11','November','N'),
(6902,'2018-11-23','2018','2018-11','November','N'),
(6903,'2018-11-24','2018','2018-11','November','N'),
(6904,'2018-11-25','2018','2018-11','November','N'),
(6905,'2018-11-26','2018','2018-11','November','N'),
(6906,'2018-11-27','2018','2018-11','November','N'),
(6907,'2018-11-28','2018','2018-11','November','N'),
(6908,'2018-11-29','2018','2018-11','November','N'),
(6909,'2018-11-30','2018','2018-11','November','Y');

Step 3: Fact Table
Create a fact table from the original table. In normal practice, you ingest the data to hdfs/hive then process the raw data and create a table with historical data where you keep inserting in increment manner. You can look more into data warehousing to get the proper definition but I call this a fact table - f_employee_balance.
This will re-create the original table with missing dates and populate the missing balance with earlier known balance.
--inner query to get all the possible dates
--outer self join query will populate the missing dates and balance
drop table if exists f_employee_balance;
create table f_employee_balance
stored as orc tblproperties ("orc.compress"="SNAPPY") as
select q1.employee_id, q1.iso_date,
nvl(last_value(r.balance, true) --initial dates to be populated with 0 balance
over (partition by q1.employee_id order by q1.iso_date rows between unbounded preceding and current row),0) as balance,
month, year from (
  select distinct
  r.employee_id,
  d.iso_date as iso_date,
  d.month, d.year
from daily_employee_balance r, dimension_date d )q1
  left outer join daily_employee_balance r on
  (q1.employee_id = r.employee_id) and (q1.iso_date = r.iso_date);

Step 4: Analytics
The query below will give you the true average for by month:
select employee_id, monthly_avg, month, year from (
    select employee_id,
           row_number() over (partition by employee_id,year,month) as row_num,
           avg(balance) over (partition by employee_id,year,month) as monthly_avg, month, year from
           f_employee_balance)q1
    where row_num = 1
    order by year, month;

Step 5: Conclusion
You could have just combined step 3 and 4 together; this would save you from creating extra table. When you are in the big data world, you don't worry much about wasting extra disk space or development time. You can easily add another disk or node and automate the process using workflows. For more information, please look into data warehousing concept and hive analytical queries.


text:
Q: Docker: Issue creating a Portainer container I'm trying to create a Portainer container in Windows 10 (and Docker ToolBox), but I'm getting an error using this docker run command:
docker run --name portainer --restart unless-stopped -p 9090:9000 -e TZ=America/Chicago -it --mount src=/var/run/docker.sock,dst=/var/run/docker.sock,type=volume --mount src="/c/Users/My Cloud/AppData/Roaming/DockerConfigs/Portainer/Data",dst=/data,type=bind portainer/portainer

Is giving me this error:
docker: Error response from daemon: create /var/run/docker.sock: "/var/run/docker.sock" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path.

If I follow the Windows example on the Portainer page replace the --mount version of the docker.sock path with the -v version instead, like this:
-v /var/run/docker.sock:/var/run/docker.sock

I get this error instead:
2019/02/13 19:47:49 invalid argument

But the container does get created; however, it ignored the specified ports in the command-line, and when I try to manually re-add them using Kitematic, it starts a bootloop on that container, and the container is unusable, I end up having to scrap it.
Anyone know what I'm missing? I'm just now learning my way around Docker.


text:
Q: Z3 Prover (Python bindings) can't determine negated Modus Ponens when proof=True I'm trying to understand why the Z3 Solver returns "unknown" when trying to satisfy the following inconsistent set of expressions.
In [1]: from z3 import *

In [2]: set_param(proof=True)

In [3]: s = Solver()

In [4]: p,q = Bools("p q")

In [5]: s.add(p)

In [6]: s.add(Not(q))

In [7]: s.add(Implies(p,q))

In [8]: s.check()
Out[8]: unknown

Note that we do not get "unknown" when do not set the proof param to True
In [1]: from z3 import *

In [2]: s = Solver()

In [3]: p,q = Bools("p q")

In [4]: s.add(p)

In [5]: s.add(Not(q))

In [6]: s.add(Implies(p,q))

In [7]: s.check()
Out[7]: unsat

Furthermore, we do not get "unknown" when we use a different inconsistent set of expressions even when setting proof=True:
In [1]: from z3 import *

In [2]: set_param(proof=True)

In [3]: s = Solver()

In [4]: x = Int('x')

In [5]: s.add(x==0)

In [6]: s.add(x>0)

In [7]: s.check()
Out[7]: unsat

What is problematic about setting up this inconsistent set of expressions in sentential logic while the proof param is set to True?


text:
Q: Why is Planck's constant the same for all particles? This question came to me while reading Where does de Broglie wavelength $\lambda=h/p$ for massive particles come from? This question has a nice answer that explains that wave number has be proportional to momentum because of Lorentz symmetry. The proportionality constant is Planck's constant $h$.
As I understand it $h$ can be thought of as the charge under translation transformation,
$$U(d) \, f(x) \equiv f(x+d) \cong 1 + \frac{df}{dx} d \, .$$
$U(d)$ is the time translation operator which is defined as $U(d) = \text{e}^{i P/\hbar}$. This definition leads to
$$ P = -i \hbar \frac{\text{d}}{\text{d}x} \, ,$$
from which $\lambda p = h$ can be deduced.
My question is the following: How come there is only one proportionality constant for all particles? Why is is not like with the relation in between spin and magnetic moment where there is a particle dependent gyromagnetic ratio?

A: We know from translation symmetry that the expectation value of the wavevector operator is constant -- that is,
$$
\langle \mathbf{k} \rangle = \langle \mathbf{k}_1 + \mathbf{k}_2 + \ldots \rangle = \text{const.}
$$
In other words, wavevector is a conserved quantity. If the constant of proportionality between $\mathbf{k}$ and momentum were different for different particles, then momentum would not be conserved.
Here's how I think of these things: the wavevector of a particle is the really fundamental quantity. Momentum is simply defined to be proportional to the wavevector because it can be shown using Schrodinger's equation that if a particle of mass $m$ is moving as a wavepacket with an average wavevector $\mathbf{k}$, then $m\mathbf{v} = \hbar\mathbf{k}$, where $\mathbf{v}$ is the particle's group velocity.

A: I discussed this with a colleague yesterday and I think that I get it.
It has to do with the normalisation of the group generators (momentum operators). Within each representation of the translation symmetry we are free to normalise the momentum operator as we like. Then it is natural to choose this normalisation such that all representations have the same pre-factor.
The momentum operator is chosen in each representation in such a way that $h$ is always the same.
It would be nice if someone could comment on this. Especially if I am wrong.

A: I think a much more natural way to come to $\hbar$ is the one used by Dirac in his principles of quantum mechanics. In it you start by stating that you want a Poisson Bracket which has the same algebraic structure as that of classical mechanics. Then, since quantum operators don't commute (unlike what happens in classical physics) you quickly find out that if $A$ and $B$ are operators, and we denote the Poisson Brackets with {}, we have
$$\{A,B\}=i\hbar[A,B]$$where $[A,B]=AB-BA$. In it $\hbar$ is just a constant (to be determined experimentally) but it is quite obvious that is independent of the particle under study since it is only a relationship of operators.


text:
Q: Determine complexity of algorithm Assume  algo(p) is an algorithm that take Theta(p) time to execute and does not change p. Determine the running time complexity of the following algorithm:
Algo2(n)
begin
p=1;
while p <= n
    begin
    algo(p)
    p=2*p
    end;
end;

Really have no idea where to begin, I was thinking O(logn) maybe since p=p*2 but then there is an algo(p) in the while loop and I don't know how that would effect things.

A: It's Big Theta(n):
It calls algo(p) O(logn) times with p = 1, 2, 4, ..., 2^(floor(logn)).
This is Theta(1 + 2 + ... + 2^(floor(logn)) = Theta(2^(floor(logn+1)-1) = Theta(n).

A: To get an easier problem, you can set it like this :
Algo(n)
  begin
  p=1, i=1
  while p<= n
    begin
    algo(p)
    p=2*p
    i++
    end
  end

which you can rewrite like that :
Algo(n)
  begin
  i=1
  while 2^(i-1)<=n
    begin
    algo(2^(i-1))
    i++
    end
  end

Then, as Henrik said :

It calls algo(p) O(logn) times with p = 1, 2, 4, ..., 2^(floor(logn)).
  This is Theta(1 + 2 + ... + 2^(floor(logn)) =
  Theta(2^(floor(logn+1)-1) = Theta(n).


text:
Q: Unable to use the http package in Flutter I keep getting the following error when trying to use the http package.

I already added the package in pubspec.yaml:
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  http: ^0.12.0+2

A: in the terminal run flutter pub get


text:
Q: CRM 4 codename field on Campaign entity - can't update value I am trying to update value of codename field on Campaign entity but it wont let me do.
In C# code if I debug, I can see it goes through without any error and saves everything else except codename value.
On CRM form it is read only field and if I try to amend it and change value from 12345 to 12345678 for example it does not save.
Any idea what might be preventing it? When I create a new record I can add any value I like.

A: Your observations are correct: codename on Campaign can be set when creating a record but cannot be updated.
This information can be seen in the CRM SDK.
See campaign.codename in the CRM 4.0 SDK:

*

*Valid for create:    Yes

*Valid for retrieve:   Yes

*Valid for update:    No


text:
Q: Numpy.putmask with images I have an image converted to a ndarray with RGBA values. Suppose it's 50 x 50 x 4.
I want to replace all the pixels with values array([255, 255, 255, 255]) for array([0, 0, 0, 0]). So:
from numpy import *
from PIL import Image
def test(mask):
        mask = array(mask)
        find = array([255, 255, 255, 255])
        replace = array([0, 0, 0, 0])
        return putmask(mask, mask != find, replace)

mask = Image.open('test.png')
test(mask)

What am I doing wrong? That gives me a ValueError: putmask: mask and data must be the same size. Yet if I change the arrays to numbers (find = 255, replace = 0) it works.

A: A more concise way to do this is
img = Image.open('test.png')
a = numpy.array(img)
a[(a == 255).all(axis=-1)] = 0
img2 = Image.fromarray(a, mode='RGBA')

More generally, if the items of find and repl are not all the same, you can also do
find = [1, 2, 3, 4]
repl = [5, 6, 7, 8]
a[(a == find).all(axis=-1)] = repl

A: One way to do this kind of channel masking is to split the array into r,g,b,a channels, then define the index using numpy logical bit operations:
import numpy as np
import Image

def blackout(img):
    arr = np.array(img)
    r,g,b,a=arr.T
    idx = ((r==255) & (g==255) & (b==255) & (a==255)).T
    arr[idx]=0
    return arr

img = Image.open('test.png')
mask=blackout(img)
img2=Image.fromarray(mask,mode='RGBA')
img2.show()

A: This solution uses putmask and I think is the closest to the OPs code.  There are two errors in the original code that the OP should know about:  1) putmask is an in-place operation.  It returns None.  2) putmask also requires equal-sized arrays.  It (too bad) doesn't have an axis keyword argument.
import numpy as np
from PIL import Image

img1 = Image.open('test.png')
arry = np.array(img1)
find = np.array([255, 255, 255, 255])
repl = np.array([  0,   0,   0,   0])
# this is the closest to the OPs code I could come up with that
# compares each pixel array with the 'find' array
mask = np.all(arry==find, axis=2)
# I iterate here just in case repl is not always the same value
for i,rep in enumerate(repl):
    # putmask works in-place - returns None
    np.putmask(arry[:,:,i], mask, rep)

img2 = Image.fromarray(arry, mode='RGBA')
img2.save('testx.png')


text:
Q: KeyBoard Shortcut for opening terminal from existing directory I need to open terminal using shortcut in any directory as I can in the file browser like this:

A: Not sure if it still works on Ubuntu, but right clicking in the directory (must be opened on Nautilus) and selecting Open Terminal Here...