text:
Q: get items from checkboxlist and insert comma between its items I have a checkboxlist and want to when I select some items ,insert ',' between items,e.g select IDs 123 and will become 1,2,3.
 protected string addcomma(string[] stuff)
    {
        string s;
        foreach (string  i in stuff)
        {
            s += Items;
            s += ',';
        }
        return s;
    }

and:
string limit = addcomma( (CheckBoxList1.SelectedValue));

I am not sure . What should I do?

A: string[] selectedItems = myCheckboxList.Items.Cast<ListItem>()
                                       .Where(o => o.Selected)
                                       .Select(o => o.Value)
                                       .ToArray();
string limit = string.Join(",", selectedItems);

A: Your approach is partially correct.
CheckBoxList1.SelectedValue returns the first selected value and not all the selected values of the CheckBoxList1 object.
Your addcomma method should be like:
protected string addcomma(List<string> stuff)
{
    string s="";
    foreach (string i in stuff)
    {
        s += i;
        s += ',';
    }
    return s;
}

Note that your last character of the s string will always be a comma.
You should use it like:
    List<string> selectedValues = new List<string>();

    foreach (ListItem li in CheckBoxList1.Items)
    {
        if (li.Selected)
        {
            selectedValues.Add(li.Value);
        }
    }
    string limit = addcomma(selectedValues);

PS. I am using a list because we don't know how many items are selected.


text:
Q: How to access psycopg2 error wrapped in sqlalchemy error I'm uploading a pandas data frame to a table in Postgres using SQLalchemy and psycopg2. How do I access the psycopg2 error that is within the SQLalchemy error?
I want to write an exception into my code only when it raises an error because of a null value in a column that violates not-null constraint. I know how to test for this exact pSQL error with psycopg2, but when I run my code it returns a SQLalchemy error.
Here's the error:

SQLalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column...

Here's the necessary exception:
from sqlalchemy import exc

try:
    df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.IntegrityError:

Here's what I want to do:
from sqlalchemy import exc
import psycopg2

try:
    df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.IntegrityError as ex:
    ex = ex.psycopg2error
    if ex.pgcode == '23502'
        print('Data not uploaded: null value in a column violates non-null constraint')
    else:
        raise

I know I can test sqlalchemy.exc.IntegrityEror.orig, but that is not as clean or fine-grained as using the pgcode member.

A: Here is my final code for reference:
try:
    df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.DBAPIError as ex:
    if ex.orig.pgcode == '23502':
        print("Data could not be uploaded to sql_table: " + ex.orig.diag.message_primary)
    else:
        raise

A: As you've pointed out in your question, you can access the underlying exception raised by the dbapi through the .orig attribute of the SQLAlchemy exception.
Any exception that is raised by the driver and propagated through SQLAlchemy is wrapped by a subclass of DBAPIError, where it's docs state:

The wrapped exception object is available in the orig attribute. Its
  type and properties are DB-API implementation specific.

(emphasis mine)
Looking at the psycopg docs for their base Error one of the attributes they name is pgcode:

String representing the error code returned by the backend, None if
  not available. The errorcodes module contains symbolic constants
  representing PostgreSQL error codes.

So, <sqla_exc>.orig.pgcode looks like it should get what you are after, but if for whatever reason psycopg doesn't make their code available in their exception state, its not really something that sqlalchemy can address as it just wraps their exception and passes it on to you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to make SharePoint lists accessible cross domain using REST API? Is it possible to make SharePoint 2013 resources accessible via internet using REST API? Say I want to do CURD with a list from outside of SharePoint. How we can manage credentials for this situation? I've seen some sites (yammer) uses SSO by redirecting users to their company website and get credentials from there. Can we use the same approach with REST API for credentials? If yes, please explain how? (Just the credentials part)

A: Assuming you have SharePoint on-premise and not 365.
Making a client-side only solution is easy if you use apps (SharePoint hosted), but you would have to deploy the app to SharePoint to be able to do cross-domain request.
Microsoft introduced two main solutions for querying cross-domain, SP.RequestExecutor.js for JSOM and /_api/SP.AppContextSite for REST, but as far as I know both of these require that you have an app hosted in a SharePoint environment. Here you don't need to think about authentication, as long as the app deploys that is handled for you.
If you have a stand-alone web site and you want client-side only communication with SharePoint I'm afraid that OOTB this is not possible. I can think of some solutions, as you can enable cross-domain, get access token for OAuth (might be 365 only) server-side or make your own service on SharePoint which supports CORS or JSONP - but this would be far from OOTB.
If you instead do the communication server-side everything will be much easier. I suggest you try making a Provider-hosted app, you will find this option in Visual Studio when creating apps for SharePoint. Then you set up High trust (S2S) which will let your app use CSOM to communiate with your on-premise SharePoint, authenticated as a user.


text:
Q: How do I safely uninstall and reinstall a service pack on vista? I have a computer with Vista and no CD.
If I wanted to uninstall and reinstall SP2, but safely, i'd like to be able to roll back.
If it can be done safely, how would one go about it?
And is it possible to do it wrongly, i.e. like not being able to roll "back"(to any previous state, like when it was installed, or just after it was uninstalled).

A: It is generally a very safe operation, but if it fails, it will do a very good job of rolling it back to where you started all by itself.
Once a service pack is installed, if you decide to uninstall it, you would just do that in "Programs and Features", the way you would uninstall any update.
That said, to guarantee successfully (un)install, Microsoft has developed the "System Update Readiness Tool". If you want to improve your odds that it will install without error, run this tool. It can take anywhere from 15 minutes to 2 or more hours to complete, but it will fix underlying problems that you will never find on your own.
http://support.microsoft.com/kb/947821
As always, to be sure, you should have an image of the computer.

A: It is safest to do a clean boot of the system, un-install and re-install while clean booted.
To Boot Clean in Windows 7 and Vista
Accessing the System Configuration Utility
Click Start type msconfig in the search box and press Enter
Configure Selective Startup options

*

*On the General tab, choose Selective Startup

*Uncheck Load Startup Items

*Select the Services tab

*Check  Hide all Microsoft services

*Click  Disable all

*Click on OK

*Click  Restart.

After performing the necessary steps, restore your system to a normal boot by doing the following:

*

*Click Start type msconfig in the search box and press Enter

*On the General tab, choose Normal Startup

*Click Ok

*Click Yes, when asked to restart your computer

.
To Boot Clean in Windows XP

*

*Click Start --> Run --> Type MSCONFIG --> Click OK

*On the General tab, choose Selective Startup

*Uncheck Process SYSTEM.INI file

*Uncheck Process WIN.INI file

*Uncheck Load Startup Items

*Click on the Services tab

*At the bottom, check Hide All Microsoft Services

*Uncheck all boxes in the window or click the button labeled Disable All

*Click OK

*Click Restart

After performing the necessary steps, restore your XP system to normal boot by doing the following:

*

*Click Start --> Run --> Type MSCONFIG--> Click OK

*On the General tab, choose Normal Startup

*Click OK

*Click YES, when asked to restart your computer


text:
Q: Use Map Data Type with Compass I am using Compass with Sass (v 3.3 Maptastic Maple) and I am trying to use the new maps data structure. I am using grunt watch with compass, however when using the new maps syntax, it throws an error everytime I run grunt.
$colors: (
  header: #b06,
  text: #334,
  footer: #666777
);

This is the error:
error sass/main.scss (Line 73 of sass/base/_variables.scss: Invalid CSS after "  header": expected ")", was ": #b06,")

How can I use the new sass maps with compass?

A: I managed to get compass to compile the new syntax by installing the alpha of the latest version.
gem install compass --pre

Should do the trick.

A: I had the same issue with you, and after few hours of trying and googling, I found 2 solutions:

*

*If you can, use grunt-contrib-sass instead.

*But if you need to use grunt-contrib-compass, check the answer at this one Is Sass 3.3 compatible with Compass?


text:
Q: Styling browser dialog boxes
(from failblog)
Not only the background's been changed but also the buttons. How can this be done?

A: That's a screen shot of someone's dialog box.
That person obviously has set a custom theme on their OS with that style. This has not been controlled by the browser or anything that could have been done via the browser.

A: You can look at the jqueryui dialog box here:
http://jqueryui.com/demos/dialog/

A: The individual with the browser is probably running a different scheme via the OS which is modifying the dialog box.


text:
Q: No inserta datos a la base de datos desde el modal php y javascript Este es el codigo, probé todas las sentencias sql en el workbench y sí inserta y muestra los datos, pero, al momento de insertar desde el formulario modal, me dice fallo del servidor con el alertify.
No sé qué error podría tener, estoy aprendiendo javascript.
index.php
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Tabla Dinamica</title>

    <link rel="stylesheet" type="text/css" href="librerias/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="librerias/alertifyjs/css/alertify.css">
    <link rel="stylesheet" type="text/css" href="librerias/alertifyjs/css/themes/default.css">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Agregar equipo

      Nro Orden
        <input type="text" name="id_orden" id="id_orden" class="form-control input-sm">
        Serie
        <input type="text" name="serie_1" id="serie_1" class="form-control input-sm">
             Equipo
             <input type="text" name="equipo_1" id="equipo_1" class="form-control input-sm">
                Cable AV
                <select type="text" name="cable_av_1" id="cable_av_1" class="form-control input-sm">
                   <option value="si">Si</option>
                   <option value="no">No</option>
                </select>
                       Cable HDMI
                        <select type="text" name="cable_hdmi_1" id="cable_hdmi_1" class="form-control input-sm">
                         <option value="1">Si</option>
                         <option value="2">No</option>
                         </select>

                             Control
                             <select type="text" name="control_1" id="control_1" class="form-control input-sm">
                                     <option value="1">Si</option>
                                     <option value="2">No</option>
                             </select>
                                  Fuente
                                                  <select type="text" name="fuente_1" id="fuente_1" class="form-control input-sm">
                                                   <option value="1">Si</option>
                                                   <option value="2">No</option>
                                                   </select>

        <button type="button" class="btn btn-primary" data-dismiss="modal" id="guardarnuevo">Agregar</button>

agregardatos.php - Acá agrego los datos
<?php

    require_once "conexion.php";
    $conn=conn();
    $id_orden=$_POST['id_orden'];
    $serie_1= $_POST['serie_1'];
    $equipo_1=$_POST['equipo_1'];
    $cable_av_1=$_POST['cable_av_1'];
    $cable_hdmi_1=$_POST['cable_hdmi_1'];
    $control_1=$_POST['control_1'];
    $fuente_1=$_POST['fuente_1'];

    $sql="INSERT INTO ordenes (id_orden,serie_1, equipo_1, cable_av_1, cable_hdmi_1, control_1, fuente_1)
                VALUES ('$id_orden','$serie_1','$equipo_1','$cable_av_1','$cable_hdmi_1','$control_1','$fuente_1')";

    $result = mysqli_query($conn,$sql);
?>

funciones.js
function agregardatos(id_orden, serie_1, equipo_1, cable_av_1, cable_hdmi_1, control_1, fuente_1){

      cadena="orden=" + id_orden +
             "&serie=" + serie_1 +
             "&equipo=" + equipo_1 +
             "&cableav=" + cable_av_1 +
             "&cablehdmi=" + cable_hdmi_1 +
             "&control=" + control_1 +
             "&fuente=" + fuente_1;

    $.ajax({
        type:"POST",
        url:"php/agregardatos.php",
        data:cadena,
          success:function(r){
              if(r==1){
                $('#tabla').load('componentes/tabla.php');
                  alertify.success("agregado con exito");
              }else{
                  alertify.error("fallo el servidor");
              }

          }
    });

    }

conexion.php
<?php
           function conn(){
               $servidor="localhost";
               $usuario="root";
               $password="";
               $bd="formulario";

               $conn=mysqli_connect($servidor,$usuario,$password,$bd);

               return $conn;
           }
?>

tabla.php
<?php

  require_once "../php/conexion.php";
  $conn=conn();

?>

Tabla de registros express

             <button class="btn btn-primary"  data-toggle="modal" data-target="#modaNuevo">Agregar nuevo

             </button>

                Nro Orden
                Serie
                Equipo
                Cable AV
                Cable HDMI
                Control
                Fuente
                Editar
                Eliminar

              <?php
                  $sql="SELECT id_orden,serie_1, equipo_1, cable_av_1, cable_hdmi_1, control_1, fuente_1
                           from ordenes ";

                  $result=mysqli_query($conn,$sql);

                  while($ver=mysqli_fetch_row($result)){

              ?>

               <?php  echo $ver[0] ?>
               <?php  echo $ver[1] ?>
               <?php  echo $ver[2] ?>
               <?php  echo $ver[3] ?>
               <?php  echo $ver[4] ?>
               <?php  echo $ver[5] ?>
               <?php  echo $ver[6] ?>

                  <button class="btn btn-warning glyphicon glyphicon-pencil" data-toggle="modal" data-target="#modalEdicion"></button>

                  <button class="btn btn-danger glyphicon glyphicon-remove"></button>

            <?php
        }
            ?>

`

Los nombres que tengo en los id y name es como se llama en la base de datos. es mi primer mini proyecto con javascript.


text:
Q: Where is data_directory for homebrew? or for postgresql or how do I solve error, ""global/pg_filenode.map": No such file or directory"? I'm having difficulty with postgresql after installing via homebrew. I'm on Mac OS X 10.9.5 (just updated today and did restart).
Note I didn't deliberately change anything from a default postgresql installation via homebrew
PROBLEM

*

*I can't uninstall postgresql

*I can't log in to view tables / start the "command line" of postgres

*createdb returns an error about pg_filenode.map "no such file or directory"

*initdb returns error wondering where data_directory is (I don't know)

ANY OF THESE WOULD BE SUCCESS

*

*Log in to psql (so I can create a database or table like I can do in mysql, browse existing tables)

*Uninstall postgres altogether (so I can re-try with postgresql.app)

I've spent almost 10 hours troubleshooting this and come up short.
I've looked at loads of answers already (including SO questions 24132418 and 14510237) though I can't include all links due to not having reputation points yet
Any pointers would be really appreciated!
Below seems lengthy because I have pasted all the logs, please let me know if I have missed some important info though
Thanks, -Mark
DETAILS
I have been working my way through an introduction to Heroku, and they said installing postgresql was a requirment, so I did that using homebrew
brew install postgresql

I didn't check it, I proceeded building my app, but the next day I run the webapp locally and get error,
Request URL:    http://localhost:5000/admin/
Django Version: 1.6.5
Exception Type: OperationalError
Exception Value:
FATAL:  could not open relation mapping file "global/pg_filenode.map": No such file or directory
Exception Location: /Users/macuser/Dropbox/code/heroku/awe01/lib/python2.7/site-packages/psycopg2/__init__.py in connect, line 164

So I want to investigate.
Now I've never used postgresql before, so I want to "get to the command line" for postgresql
Please note, I'm a complete newbie and have never used postgresql before.
In mysql I know this would be
mysql -u root -p

(and then enter password)
I'm unable to do the equivalent in postgresql
  moriartymacbookair13:~ macuser$ postgres
  postgres does not know where to find the server configuration file.
  You must specify the --config-file or -D invocation option or set the PGDATA environment variable.
  moriartymacbookair13:~ macuser$ postgres -V
  postgres (PostgreSQL) 9.3.5

The more detailed heroku docs recommend installing postgresql using postgres.app
I hadn't done this, I used homebrew, so I tried uninstalling postgresql
moriartymacbookair13:~ macuser$ brew uninstall postgres
Uninstalling /usr/local/Cellar/postgresql/9.3.5_1...
Error: Permission denied - /usr/local/bin/clusterdb

That didn't work, so back to where I was. To figure out what path to specify, I ran
brew info postgresql

If you scroll down to the bottom of this, you can see it advises me of the path
moriartymacbookair13:~ macuser$ brew info postgres
postgresql: stable 9.3.5 (bottled), devel 9.4beta2
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.3.5_1 (2927 files, 38M) *
  Poured from bottle
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/postgresql.rb
==> Dependencies
Required: openssl ✔, readline ✔
Recommended: ossp-uuid ✔
==> Options
--32-bit
    Build 32-bit only
--enable-dtrace
    Build with DTrace support
--no-perl
    Build without Perl support
--no-tcl
    Build without Tcl support
--with-python
    Build with python support
--without-ossp-uuid
    Build without ossp-uuid support
--devel
    install development version 9.4beta2
==> Caveats
If builds of PostgreSQL 9 are failing and you have version 8.x installed,
you may need to remove the previous version first. See:
  https://github.com/Homebrew/homebrew/issues/issue/2510

To migrate existing data from a previous major version (pre-9.3) of PostgreSQL, see:
  http://www.postgresql.org/docs/9.3/static/upgrading.html

When installing the postgres gem, including ARCHFLAGS is recommended:
  ARCHFLAGS="-arch x86_64" gem install pg

To install gems without sudo, see the Homebrew wiki.

To reload postgresql after an upgrade:
    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Or, if you don't want/need launchctl, you can just run:
    postgres -D /usr/local/var/postgres

Note: I have ignored the comment at the top:
Conflicts with: postgres-xc
    /usr/local/Cellar/postgresql/9.3.5_1 (2927 files, 38M) *

Anyway there we have it, toward the end of that large output it confirms the path for me is /usr/local/var/postgres, so I tried -D
moriartymacbookair13:~ macuser$ postgres -D /usr/local/postgres
postgres cannot access the server configuration file "/usr/local/postgres/postgresql.conf": No such file or directory

So this time I specified the config file:
moriartymacbookair13:~ macuser$ postgres --config-file=/usr/local/var/postgres/postgresql.conf
postgres does not know where to find the database system data.
This can be specified as "data_directory" in "/usr/local/var/postgres/postgresql.conf", or by the -D invocation option, or by the PGDATA environment variable.

(Out of desperation, I even tried deleting it and going again)
                moriartymacbookair13:~ macuser$ initdb /usr/local/var/postgres
        The files belonging to this database system will be owned by user "macuser".
        This user must also own the server process.
The database cluster will be initialized with locale "en_GB.UTF-8".
        The default database encoding has accordingly been set to "UTF8".
        The default text search configuration will be set to "english".

        Data page checksums are disabled.

        initdb: directory "/usr/local/var/postgres" exists but is not empty
        If you want to create a new database system, either remove or empty
        the directory "/usr/local/var/postgres" or run initdb
        with an argument other than "/usr/local/var/postgres".
        moriartymacbookair13:~ macuser$ rm -rf /usr/local/var/postgres
        moriartymacbookair13:~ macuser$ initdb /usr/local/var/postgres -E utf8
        The files belonging to this database system will be owned by user "macuser".
        This user must also own the server process.

        The database cluster will be initialized with locale "en_GB.UTF-8".
        The default text search configuration will be set to "english".

        Data page checksums are disabled.

        creating directory /usr/local/var/postgres ... ok
        creating subdirectories ... ok
        selecting default max_connections ... 100
        selecting default shared_buffers ... 128MB
        creating configuration files ... ok
        creating template1 database in /usr/local/var/postgres/base/1 ... ok
        initializing pg_authid ... ok
        initializing dependencies ... ok
        creating system views ... ok
        loading system objects' descriptions ... ok
        creating collations ... ok
        creating conversions ... ok
        creating dictionaries ... ok
        setting privileges on built-in objects ... ok
        creating information schema ... ok
        loading PL/pgSQL server-side language ... ok
        vacuuming database template1 ... ok
        copying template1 to template0 ... ok
        copying template1 to postgres ... ok
        syncing data to disk ... ok

        WARNING: enabling "trust" authentication for local connections
        You can change this by editing pg_hba.conf or using the option -A, or
        --auth-local and --auth-host, the next time you run initdb.

        Success. You can now start the database server using:

            postgres -D /usr/local/var/postgres
        or
            pg_ctl -D /usr/local/var/postgres -l logfile start

    moriartymacbookair13:~ macuser$ postgres -D /usr/local/postgres
    postgres cannot access the server configuration file "/usr/local/postgres/postgresql.conf": No such file or directory
    moriartymacbookair13:~ macuser$ postgres --config-file=/usr/local/var/postgres/postgresql.conf
    postgres does not know where to find the database system data.
    This can be specified as "data_directory" in "/usr/local/var/postgres/postgresql.conf", or by the -D invocation option, or by the PGDATA environment variable.

So I took a look at that file:
In that in the conf file itself, the data variable is not defined
  moriartymacbookair13:~ macuser$ ls /usr/local/var/postgres/
  PG_VERSION       pg_ident.conf    pg_stat/         pg_xlog/
  base/            pg_multixact/    pg_stat_tmp/     postgresql.conf
  global/          pg_notify/       pg_subtrans/
  pg_clog/         pg_serial/       pg_tblspc/
  pg_hba.conf      pg_snapshots/    pg_twophase/
  moriartymacbookair13:~ macuser$ vim /usr/local/var/postgres/postgresql.conf

shows that the value is commented out (see line 41... almost the whole file is commented out)
 35 # FILE LOCATIONS
 36 #-----------------------------------------------------------------------------    -
 37
 38 # The default values of these variables are driven from the -D command-line
 39 # option or PGDATA environment variable, represented here as ConfigDir.
 40
 41 #data_directory = 'ConfigDir'           # use data in another directory
 42                                         # (change requires restart)
 43 #hba_file = 'ConfigDir/pg_hba.conf'     # host-based authentication file
 44                                         # (change requires restart)
 45 #ident_file = 'ConfigDir/pg_ident.conf' # ident configuration file
 46                                         # (change requires restart)
 47
 48 # If external_pid_file is not explicitly set, no extra PID file is written.
 49 #external_pid_file = ''                 # write an extra PID file
 50                                         # (change requires restart)

HELP: DOES ANYONE KNOW WHAT I SHOULD SPECIFY THAT 'ConfigDir' AS for where data_directory is?
In case helpful
here are contents of the Cellar folder
moriartymacbookair13:~ macuser$ ls /usr/local/Cellar/postgresql/9.3.5_1/
COPYRIGHT                       homebrew.mxcl.postgresql.plist
HISTORY                         include/
INSTALL_RECEIPT.json            lib/
README                          share/
bin/

(I don't understand why I have some postgres files in Cellar and some in usr/local/var)
I tried some other things too:
    moriartymacbookair13:~ macuser$ sudo -u postgres pg_ctl -D /usr/local/var/postgres -w start
    sudo: unknown user: postgres

That's based on other SO questions
    moriartymacbookair13:~ macuser$ ls -ld /usr/local/var/postgres/
    drwx------  19 macuser  admin   646B 20 Sep 19:46 /usr/local/var/postgres//
    moriartymacbookair13:~ macuser$ chown -R postgres /usr/local/var/postgres
    chown: postgres: illegal user name
    moriartymacbookair13:~ macuser$ brew uninstall postgresql
    Uninstalling /usr/local/Cellar/postgresql/9.3.5_1...
    Error: Permission denied - /usr/local/bin/clusterdb
    moriartymacbookair13:~ macuser$ brew uninstall postgres
    Uninstalling /usr/local/Cellar/postgresql/9.3.5_1...
    Error: Permission denied - /usr/local/bin/clusterdb
    moriartymacbookair13:~ macuser$

As I say, I installed Postgresql only to try out heroku, so here is the error Chrome gives me from the code when I run foreman start locally.
(Note "the django app" is just a demo app https://devcenter.heroku.com/articles/getting-started-with-python#prepare-the-app)
It works for localhost:5000 home, but when I add /admin (the page that would interact with a database), I get the following error:
OperationalError at /admin/
FATAL:  could not open relation mapping file "global/pg_filenode.map": No such file or directory
Request Method: GET
Request URL:    http://localhost:5000/admin/
Django Version: 1.6.5
Exception Location: /Users/macuser/Dropbox/code/heroku/awe01/lib/python2.7/site-packages/psycopg2/__init__.py in connect, line 164
Python Executable:  /Users/macuser/Dropbox/code/heroku/awe01/bin/python

Full error traceback log here: http://dpaste.com/3CREGVQ
Note this answer https://stackoverflow.com/a/5053003/870121
recommends createdb not just initdb
And the above error is the same as if I run createdb:
moriartymacbookair13:~ macuser$ createdb /usr/local/var/postgres/
createdb: could not connect to database template1: FATAL:  could not open relation mapping file "global/pg_filenode.map": No such file or directory

Steps advised here
    Postgres is failing with 'could not open relation mapping file "global/pg_filenode.map" '
are
Remove and re-add the launch agent
Kill the processes for <postgresql version number>
Initialize the db initdb /usr/local/var/postgres
Restart my computer

If this is relevant someone please tell me how to "Remove and re-add the launch agent"?
Is is this? (based on the output of the brew info postgresql from earlier)
moriartymacbookair13:~ macuser$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
moriartymacbookair13:~ macuser$ killall postgresql
No matching processes belonging to you were found
moriartymacbookair13:~ macuser$ killall postgres
No matching processes belonging to you were found
moriartymacbookair13:~ macuser$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

FINALLY
In case it inspires anyone,
moriartymacbookair13:~ macuser$ brew doctor
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry and just ignore them. Thanks!

Warning: The /usr/local directory is not writable.
Even if this directory was writable when you installed Homebrew, other
software may change permissions on this directory. Some versions of the
"InstantOn" component of Airfoil are known to do this.

You should probably change the ownership and permissions of /usr/local
back to your user account.

Warning: Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected dylibs:
    /usr/local/lib/libguide.dylib
    /usr/local/lib/libKLF_OGL.dylib

Warning: Some directories in your path end in a slash.
Directories in your path should not end in a slash. This can break other
doctor checks. The following directories should be edited:
    $/Users/macuser/Dropbox/code/aws/ElasticBeanstalkCommandLineTools/AWS-ElasticBeanstalk-CLI-2.6.3/AWSDevTools.sh/macosx/python2.7/    /Users/macuser/Dropbox/code/aws/ElasticBeanstalkCommandLineTools/AWS-ElasticBeanstalk-CLI-2.6.3/AWSDevTools/eb/macosx/python2.7/

Warning: /usr/bin occurs before /usr/local/bin
This means that system-provided programs will be used instead of those
provided by Homebrew. The following tools exist at both paths:

    git
    git-cvsserver
    git-receive-pack
    git-shell
    git-upload-archive
    git-upload-pack

Consider setting your PATH so that /usr/local/bin
occurs before /usr/bin. Here is a one-liner:
    echo export PATH='/usr/local/bin:$PATH' >> ~/.bash_profile
moriartymacbookair13:~ macuser$

Earlier today I had this error
    createdb: could not connect to database postgres: could not connect to server: No such file or directory
            Is the server running locally and accepting
            connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
as per http://www.postgresql.org/docs/9.3/interactive/tutorial-createdb.html
but that error seems to have gone away now
Any advice on un or re-installing postgresql, resolving the unknown user: postgres error, setting location of #data_directory = 'ConfigDir' or any other tips... I would really appreciate it. It's been a full day lost to this now so I would appreciate anything at all.

A:
FATAL:  could not open relation mapping file "global/pg_filenode.map": No such file or directory

You had a PostgreSQL install, but deleted or moved the data directory while the server was running. Or you installed it on a removable disk that you then removed. Or some application on your system is messing with how other apps change files.

  moriartymacbookair13:~ macuser$ postgres
  postgres does not know where to find the server configuration file.

postgres is the server application. The client is psql. However, if global/pg_filenode.map is missing you're not going to have any more luck with psql.

  moriartymacbookair13:~ macuser$ brew uninstall postgres

sudo brew uninstall postgres

Anyway there we have it, toward the end of that large output it
  confirms the path for me is /usr/local/var/postgres, so I tried -D
moriartymacbookair13:~ macuser$ postgres -D /usr/local/postgres
postgres cannot access the server configuration file "/usr/local/postgres/postgresql.conf": No such file or directory

You got the path wrong. Note what "brew info" said:

    Or, if you don't want/need launchctl, you can just run:
    postgres -D /usr/local/var/postgres

As for the postgres user:

moriartymacbookair13:~ macuser$ sudo -u postgres pg_ctl -D /usr/local/var/postgres -w start
sudo: unknown user: postgres

I think some Mac OS X installs use _postgres or postgres_. I don't have a mac, so I can't check. But it doesn't matter in your case anyway, because the datadir is owned by your user, not postgres:

moriartymacbookair13:~ macuser$ ls -ld /usr/local/var/postgres/
drwx------  19 macuser  admin   646B 20 Sep 19:46 /usr/local/var/postgres//

It looks to me like you or some tool on your system has mangled your PostgreSQL data directory, corrupting it. This shouldn't happen, so I'd be making an effort to find out what removed pg_filenode.map and how/when.
If there is no data you care about in the data directory, you should delete it and re-initdb.
I don't have a Mac and I can't see how Homebrew configures your PostgreSQL install's startup, but it sounds like it probably runs postgres as user macuser. In which case, just:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
rm -rf /usr/local/var/postgres
initdb -D /usr/local/var/postgres -U postgres --auth-local peer --auth-host md5 -E utf-8l
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Finally, re:

Note, when I tried to use the postgres.app installer now it told me
  "Could not start on Port 5432" and froze during installation

at a guess, when you tried that you had the postgres server from Homebrew already running on 5432, but nonfunctional because of the damaged data directory.
So you really have two things here:

*

*Re-initdb the datadir to get PostgreSQL working again; and

*Figure out how it got damaged in the first place

A: SOLUTION to the problem I posted

*

*sudo brew uninstall postgresql (literally, sudo solved my problem... I had read that sudo brew can be dangerous but it worked well in this case)

*Restart

*Tried to run postgres.app  ...got error

*Restart

*Fully uninstalled postgres.app (following instructions on site: quit, drag to the Trash, and then "Finder > Empty Trash..." as per http://postgresapp.com/documentation/install.html)

*Restart

*Delelted data folder as per trouble shooting instructions of postgresapp
i.e., the 5 steps here:
Resetting Postgres.app
http://postgresapp.com/documentation/troubleshooting.html (I may have done this earlier, I forget the order of steps 5/7)

*Restart

*Re-installed postgresql via postgres.app

*Added the path to my /etc/profile file... adding to ~/.bashrc or ~/.bash_profile doesn't work for me for some reason. Here in an

Extract from /etc/profile for me
It might be from another file for you, see https://apple.stackexchange.com/questions/12993/why-doesnt-bashrc-run-automatically#comment13715_13019
 # 1:
 # For postgresql postgres postgres.app:
 # Otherwise psql isn't a recognised command
 # Based on http://postgresapp.com/documentation/cli-tools.html
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin
 # 2:
 # And this from https://devcenter.heroku.com/articles/heroku-postgresql#local-setup
export PATH="/Applications/Postgres93.app/Contents/MacOS/bin:$PATH:$PATH"
 # 3:
 # And now this based on error of file not existing
 # from http://stackoverflow.com/questions/13868730/socket-file-var-pgsql-socket-s-pgsql-5432-missing-in-mountain-lion-os-x-ser -- don't think this made a difference though
export PGHOST=localhost

I think this is overkill; the first change is definitely useful as it allows me to go straight to psql just by typing "psql" in terminal (I personally didn't even need -h localhost); I'm less sure of the need of the other two additions
That's it.

HOW IT GOT DAMAGED IN THE FIRST PLACE
I haven't figured this out.

OTHER TIPS FOR ANY MAC USER WHO'S USING DJANGO ON HEROKU WITH POSTGRESQL
In case relevant, now that it's working, here are some more steps I've finished to get fully set up and comfortable with postgres and my new heroku app. This has been my first experience with heroku, django and postgresql so I have tried to note all details which struck me!
Note: I had locally finished the tutorial for the "polls" sample app (from https://docs.djangoproject.com/en/1.6/intro/tutorial01/). My goal was to add this /polls app to the "getting started" django sample app (from https://devcenter.heroku.com/articles/getting-started-with-python)
(Note: I chose django 1.6 since it seems to be the latest version supported by heroku right now.)
I am running Mac OS X 10.9.5 but some of my comments may be helpful for anyone confused about local/heroku postgres integration
Create a local postgres db to use with django app

*

*Once postgres app is running (launched by double-clicking the program in Applications -> Postgres, then look out for the elephant in the notification bar if you're on a Mac), I can log in to psql. But first straight from the command line, I made a database by command

createdb cool01db
Note if you get this,
   psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432? or similar error, then you haven't set up the postgres app/server correctly, so don't proceed through my instructions

*Now I could log in to psql as per instructions on http://postgresapp.com/documentation/cli-tools.html
psql cool01db
Running the psql command \d shows me they're nothing in this database yet; tables will be created automatically by django when I do my syncdb command

*Note: Since I had already completed the polls tutorial elsewhere, I had copied the "polls" folder (which contains things like models.py) into the folder of my heroku sample app, so "polls" was a folder alongside "gettingstarted" and "hello". Therefore I also added "polls" to the list of "installed apps" in the gettingstarted/settings.py as per https://docs.djangoproject.com/en/1.6/intro/tutorial01/#activating-models

*I edited the gettingstarted/settings.py file as per instructions on the django tutorial
https://docs.djangoproject.com/en/1.6/intro/tutorial01/#database-setup and https://docs.djangoproject.com/en/1.6/ref/settings/#std:setting-DATABASES
For me, this looked like:

DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.postgresql_psycopg2',
         'NAME': 'cool01db',
         'USER': '',
         'PASSWORD': '',
         'HOST': 'localhost', # '127.0.0.1' probably works also
         'PORT': '5432',
     }
 }
To use the newly-created local postgres DB and not the heroku one

*I commented out this link in gettingstarted/settings.py
#  DATABASES['default'] =  dj_database_url.config()
This is as per excellent comment, http://stackoverflow.com/a/16422414/870121

*I navigated into the project folder (which contains the above three folders and files like manage.py) and ran (locally, not on heroku) python manage.py syncdb
Here I was prompted to create a superuser with a password

Note, now the tables for the heroku sample app (tables like hello_greeting) and the django polls app (tables like polls_choice and polls_question) are all automatically created in the local postgres db, and I can view them if I log in to psql (psql cool01db from the terminal) and type \d (once you're in)

*I ran foreman start and navigated to http://localhost:5000/admin/ and entered my superuser username and password I had just created. This successfully logged me in to the /admin site powered by my LOCAL postgres database

*I saw the admin panel with the opportunity to add a Question as per django tutorial, so I added a question with some answers as per https://docs.djangoproject.com/en/1.6/intro/tutorial02/#make-the-poll-app-modifiable-in-the-admin

*Now I visited http://localhost:5000/polls and sure enough it was working

*If in the terminal I ran psql cool01db and then the sql command \d I could see the tables, and select * from question_choice showed me the updates just made. Very satisfying.

To use the heroku postgres db in development

*I uncommented this line in gettingstarted/settings.py
DATABASES['default'] =  dj_database_url.config()

*I ran heroku config
Knew to do this from https://devcenter.heroku.com/articles/getting-started-with-python#define-config-vars
Output was this:

(awe01)moriartymacbookair13:getstartapp macuser$ heroku config
=== awe01 Config Vars
DATABASE_URL:                 postgres://aqmorelettersqz:uqry_pnFmorelettersYf@ec2-XX-XXX-XX-XX.compute-1.amazonaws.com:5432/dbmorelettersce
HEROKU_POSTGRESQL_YELLOW_URL: postgres://aqmorelettersqz:uqry_pnFmorelettersYf@ec2-XX-XXX-XXX-XX.compute-1.amazonaws.com:5432/dbmorelettersce
PAPERTRAIL_API_TOKEN:         kmorelettersx
TIMES:                        2
(awe01)moriartymacbookair13:getstartapp macuser$

Then I pasted all of that into the hidden file .env which lies in the same folder as manage.py
Syntax note: this means the file .env looked like this:
TIMES=2
DATABASE_URL=postgres://aqmorelettersqz:uqry_pnFmorelettersYf@ec2-XX-XXX-XX-XX.compute-1.amazonaws.com:5432/dbmorelettersce
HEROKU_POSTGRESQL_YELLOW_URL=pos.... etc
...i.e., with = signs but no spaces around them (and no comments in this file)
Note, this involved deleting the original "DATABASE_URL=" entry from the .env file
As far as I understand, the .env file is what your local machine sees, but the output of "heroku config"  is what the heroku machine sees (corrections welcome), so I wanted them to match.

*NB: Once Postgres is installed and you can connect, you'll need to export the DATABASE_URL environment variable for your app to connect to it when running locally.

Run command export DATABASE_URL=postgres:///$(whoami)
This tells Postgres to connect locally to the database matching your user account name (which is set up as part of installation).
That's from https://devcenter.heroku.com/articles/heroku-postgresql#local-setup
Note (to self): I don't understand what happens here (I can't see a file that's changed as a result of running this, or what exactly happens). But I did a restart of computer and everything still works, I didn't need to run this again.

*Now on a heroku dyno I ran "syncdb"
heroku run python manage.py syncdb
(You will be prompted to create a superuser only if you haven't already done so)

*I went to myappname.herokuapp.com/admin and logged in with the superuser account created for heroku postgresql (which I have the same as local for convenience). There I was able to add a question, and this time this question is added to the heroku postgresql db. Visiting myappname.herokuapp.com/polls shows me that question available for votes

I think that's it
Now if I do foreman start, what I see at /db or /polls is the same as if I visit my locallhost:5000 or myappname.herokuapp.com, since both are using the heroku postgresdb (I don't even need my postgres server running)

*To view tables and run commants like \dt or SELECT * FROM... I can do a command heroku pg:psql as per https://devcenter.heroku.com/articles/getting-started-with-python#provision-a-database
Thanks Craig Ringer for the original answer.


text:
Q: What are the steps needed to build WSO2 Carbon Platform Patch Release 4.0.x? I'm trying to build the Carbon Platform from source.
I've tried this:
svn co https://svn.wso2.org/repos/wso2/carbon/platform/branches/4.0.0
cd patch-releases\4.0.9
set MAVEN_OPTS="-Xms512m -Xmx1024m -XX:MaxPermSize=1024m"
mvn clean install -Dmaven.test.skip=true

However, I had hit this problem: link
After fixing that problem, I have now run into this:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0:compile (default-compile) on project org.wso2.carbon.message.store: Compilation failure: Compilation failure:
[ERROR] C:\wso2\src\wso2_platform_branch_400\components\mediation\message-store\org.wso2.carbon.message.store\4.0.9\src\main\java\org\wso2\c
arbon\message\store\persistence\jms\JMSMessageStore.java:[29,39] cannot find symbol
[ERROR] symbol  : class MessageStores
[ERROR] location: package org.apache.synapse.message.store

I must be doing something wrong - I keep hitting errors at each turn?
Question: What are the steps needed to build WSO2 Carbon Platform Patch Release 4.0.x?

A: The necessary steps are, (if you want to build patch-release 4.0.x)
1) build orbit 4.0.0/
   Then build orbit/patch-release/4.0.x
2) build kernel 4.0.0/
   Then build kernel/patch-release/4.0.x
3) build platform 4.0.0/
   Then build platform/patch-release/4.0.x
This should work.


text:
Q: xml parser cannot Read ampersand mark and escaping text before '&'? this method contain the title which i want to parse but in title parser reading characters after the ampersand sign and escaping all words before the '&'
can any one help ? please
@Override
public void characters(char[] ch, int start, int length) throws SAXException {

    if (parsingTitle) {
        if (currentItem != null)
            currentItem.setTitle(new String(ch, start, length));
    } else if (parsingLink) {
        if (currentItem != null) {
            currentItem.setLink(new String(ch, start, length));
            parsingLink = false;
        }
    }
}


text:
Q: Error when accessing webservice I am trying to access a webservice from vb.net web app. Its throwing error like
"This is a secure webservice and should be accessed through https"
what does this error means? Any solution?
Thanks in Advance,
Pavan

A: I assume where you are trying to connect to the web service you are trying to connect to something like
http://webservice.services.com
you should be using
https://webservice.services.com


text:
Q: Stopping an Animation Drawable I have this animation with the xml below inside my activity. Do I need to stop it when the activity gets destroyed or not?
    backAnime = (AnimationDrawable) findViewById(R.id.activity_main).getBackground();
    backAnime.setEnterFadeDuration(2000);
    backAnime.setExitFadeDuration(3000);
    backAnime.start();

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/homegradient"
    android:duration="8000"/>

<item android:drawable="@drawable/homegradient2"
    android:duration="8000"/>

<item android:drawable="@drawable/homegradient3"
    android:duration="8000"/>

</animation-list>

A: I would say, stop it in the "onStop()" method, by doing this it will also cover those cases when the app goes in the background (where onDestroy() is not called).


text:
Q: Ios 7 custom UINavigationController animation fails with mapView in destination controller I am playing around with the new UIViewControllerContextTransitioning between UViewControllerinside UINavigationViewController
And what I have and what I want to achieve is quite simple but I fail somewhere
I have a MKMapView (300px * 60px) inside a UIScrollView. And from a click on that map (no matter where in the visible scroll it is) I want to segue over to next view that containts a fullsized MKMapView.
The feeling and animation I am aiming for is for the user to feel they are being sucked into the map (kind of) =)
I have so far added:
<UIViewControllerTransitioningDelegate, UINavigationControllerDelegate>
and
-(id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{

if (operation == UINavigationControllerOperationPush) {
    NSLog(@"inside itself");
    FixRTransitionAnimator *animator = [FixRTransitionAnimator new];
    animator.presenting = YES;
    CGRect absoluteframe = [self.mainScrollView convertRect:self.mapView.frame toView:self.view];
    animator.mapFrame = absoluteframe;
    NSLog(@"the map frame is %@", NSStringFromCGRect(self.mapView.frame));
    return animator;
}
else
    NSLog(@"nope its outside");
return nil;
}

And to the prepareForSegue method I have:
   [super prepareForSegue:sender sender:sender];

    MapViewController *mapViewController = segue.destinationViewController;
    mapViewController.transitioningDelegate = self;
    mapViewController.modalPresentationStyle = UIModalPresentationCustom;

And finally I have the `FixRTransitionAnimator.m``
-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
NSLog(@"the time is timed");
return 0.5f;
}
 -(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
NSLog(@"we are inside %@",NSStringFromCGRect(self.mapFrame));
UIViewController *fromVController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toVController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

CGRect endFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height);

if (self.presenting) {
    fromVController.view.userInteractionEnabled = NO;

    [[transitionContext containerView]addSubview:fromVController.view];
    [[transitionContext containerView]addSubview:toVController.view];

    toVController.view.frame = self.mapFrame;

     [UIView animateWithDuration:[self transitionDuration:transitionContext]      animations:^{
        fromVController.view.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;
        NSLog(@"inside the animation");
        toVController.view.frame = endFrame;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}else{
   ...
}

}

The transition animation works nice and fine with the destinationViewController empty. But with the map inside the animation works really weird and not at all as I wanted.
Any1 got any pointers to what I miss or need to think of?

A: I wrote a post in another answer, but make sure you are setting your UINavigationControllerDelegate.
There is a UIViewControllerTransitioningDelegate for presented controllers, and a UINavigationControllerDelegate for pushed controllers.  The delegate methods inside the protocols return your animator.


text:
Q: SQL - Get one of each in a join I've got 2 tables. Table A and B.
Table A has an id and some data which isn't important for the question.
Table B has an id and an A_id. The last one is used to combine the 2 of them. There can be either multiple rows with the same A_id, only 1 or none at all.
I need a query which will do the following:

*

*Get only 1 of each row from table A

*Join table B into it

*No duplicates from table A

I know it might sound complicated, so here is an example
Table A
id other info
 1 ...
 2 ...
 3 ...
 4 ...

Table B
id A_id
 1    2
 2    3
 3    3
 4    3

Output
 A.id other info B.id A_id
    1 ...        NULL  NULL
    2 ...           1     2
    3 ...           2     3
    4 ...        NULL  NULL

So, even though there are multiple rows in table B of which A_id is 3, I only need the one of them. And even though there is no row in table B of which the A_id is 1 or 4, I still need both of them to show up.
This is as clear as I can possibly describe my question, please give feedback on how I can improve this question.

A: I think the simplest way is to use a correlated subquery:
select a.*,
       (select max(b.id) from b where b.a_id = a.id)
from a;

A: I can't test it right now but it seems that you want something like this
SELECT * FROM A
LEFT JOIN B ON A.ID = B.A_ID

UPDATE:
WITH tmp AS (
SELECT MIN(ID) ID FROM B GROUP BY A_id
)
SELECT A.*, B.* FROM B
INNER JOIN tmp ON B.Id = tmp.ID
RIGHT JOIN A ON A.Id = B.A_Id

A: Assuming your database supports ANSI SQL and when there are multiple rows in B you want the last one based on ID:
with lastB (B_Id) as (
  select max(id) from tableB group by A_id
),
BRows as (
select * from tableB
    where Id in (select B_Id from lastB)
)
select a.field1, a.field2, a.fieldN,
   b.field1, b.field2, b.fieldN
from tableA a
left join BRows b on a.Id = b.A_Id

EDIT: Oops. You edited your question and wnat the first one. Then simply make max(), min().
with lastB (B_Id) as (
  select min(id) from tableB group by A_id
),
BRows as (
select * from tableB
    where Id in (select B_Id from lastB)
)
select a.field1, a.field2, a.fieldN,
   b.field1, b.field2, b.fieldN
from tableA a
left join BRows b on a.Id = b.A_Id

EDIT: Here is the MS SQL sample I promised for:
DECLARE @tableA TABLE ( id INT, other VARCHAR(10) );
DECLARE @tableB TABLE
    (
      id INT ,
      A_Id INT ,
      other VARCHAR(10)
    );

INSERT  @tableA
        ( id, other )
VALUES  ( 1, 'v1' ),
        ( 2, 'v2' ),
        ( 3, 'v3' ),
        ( 4, 'v4' );

INSERT  @tableB
        ( id, A_Id, other )
VALUES  ( 1, 2, 'v21' ),
        ( 2, 3, 'v31' ),
        ( 3, 3, 'v32' ),
        ( 4, 3, 'v33' );

WITH    fromB ( B_Id )
          AS ( SELECT   MIN(id)
               FROM     @tableB
               GROUP BY A_Id
             ),
        BRows
          AS ( SELECT   *
               FROM     @tableB
               WHERE    id IN ( SELECT  B_Id
                                FROM    fromB )
             )
    SELECT  a.id AS A_Id ,
            a.other AS A_Other ,
            b.id AS B_Id ,
            b.other AS B_Other
    FROM    @tableA a
            LEFT JOIN BRows b ON a.id = b.A_Id;

Result:
A_Id A_Other B_Id B_Other
1    v1      NULL NULL
2    v2      1    v21
3    v3      2    v31
4    v4      NULL NULL

A: Big thank you for Gordon Linoff for pushing me in the right direction. The initial answer was:
select A.*,
       (select count(B.A_id) from B where B.A_id = A.id)
from A

I'm sorry for not telling this in my question, but all I actually needed was to get every row from A and at the same time check if there was any row in table B which had the same value in A_id as the A.id had.
This query counts all rows which have the same value of A_id as A.id.
To be clear, the output will give:
 A.id other info count
    1 ...        0
    2 ...        1
    3 ...        3
    4 ...        0


text:
Q: Adding values from the sqlite3 callback function to wxGrid I have a table of students like this (~60 students in table)
| ID  | FULL_NAME |
| 1   | Tony      |
| 2   | Max       |
Then i'm passing a pointer to a wxGrid object as second argument of GetStudents function.
int cDatabase::GetStudents(wxString path_to_db, wxGrid* grid)
{
    sqlite3* db;

    char* zErrMsg = 0;
    int rc;
    std::string sql;

    rc = sqlite3_open(path_to_db, &db);

    if (rc) {
        wxLogMessage(sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }
    sql = "SELECT FULL_NAME FROM 'STUDENTS'; ";
    rc = sqlite3_exec(db, sql.c_str(), callback, grid, &zErrMsg);

    if (rc) {
        wxLogMessage(sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }
    sqlite3_close(db);
    return 0;
}

Then in callback i'm creating a grid (on a pointer to wxGrid object) with the number of rows equal to argc received from a callback function
int cDatabase::callback(void* c_data, int argc, char** argv, char** azColName)
{
    wxGrid* grid = reinterpret_cast<wxGrid*>(c_data);

    grid->CreateGrid(argc, 1);

    return 0;
}

But at the very end argc equals to 1. Also if i will go trough the argv,
for (size_t i = 0; i < argc; i++)
{
    grid->SetCellValue(i, 1, wxString::FromUTF8(argv[i]));
}

this will cause an access violation error.
Also, must to note that if i use Append function with wxComboBox object
cb_group->Append(wxString::FromUTF8(*argv));

this will work without any problems, it just fills the combobox with received from callback values.
How can i easily iterate trough the argv without errors?
Any solutions please, I'm really tired of this.


text:
Q: The procedure entry point could not be located in dynamic link library Qt5Cored.dll
I just built the project that I'm supposed to fix. I double checked that correct DLLs are loaded - the project uses Qt 5.3.0, and the dlls are loaded from 5.3.0 directory. I am not sure where is the problem. Is my project using incorrect Qt headers? Or is the DLL build incorrectly?
I'm building in Debug with Visual Studio 2017. The DLLs are also built with visual studio. I tried Vidual Studio 2010 instead, since it's 2010 project, but the error was the same.

A: Are you in release or debug mode? QtCoded.dll is related to debug profile.
Another explanation could be how your Qt was built.
If I remember correctly Qt was built with msvc2015 so you have to use msvc2015 to build your exe with Visual Studio and it is not possible to use a msvc version before or after that.
Please remeber that you can't use the Qt framework built with mingw with msvc.
In other words I suggest you to check which version of msvc are you using with Visual Studio and which version of Qt framework.
Regards.

A: In my case, the problem was following:
One of the sub-projects was accidentally configured to use Qt 5.6.1, whereas the rest of the solution used 5.3.0. I found out by opening the result binary in dependency walker.

A: I just had the same problem with QT 4.
The solution was found on this post: The procedure entry point could not be found

I ran into the same problem, and in my case, this was due to the fact that I had two versions of the same library installed on my computer.

In the end, the problem was that I was linking my program against the new LIB file while my PATH was pointing to the old DLL. When the library version number is not included in the LIB or DLL file names, it is very easy to mix the versions.

I my case I was using a QtCored4.dll and others from an older version of QT. The solution was copy the DLLs directly from my QT installation directory which was used to build the application (as it was set by my QTDIR environment variable):  C:\Qt\4.8.7\bin to my application directory.


text:
Q: Certain apps like supertux no loner exist after upgrading from 15.10 to 16.04 I attempted to find supertux in the dash but it seems to of disappeared. Also I couldn't find it in Ubuntu software when I tried to reinstall it. Actually, I can't any software except for software already installed on my system in the new software manger but I can in software center? Yet when I try to reinstall supertux in Ubuntu Software Center it says that "There isn't a software package called "supertux-stable" in your current software sources." Please help.

A: There is no supertux-stable in 16.04. There's just supertux. From the package index:

Package supertux

*

*xenial (games): Classic 2D jump 'n run sidescroller with Tux [universe]
0.4.0-1: amd64 arm64 armhf i386 powerpc ppc64el s390x


text:
Q: create a if statement where only one button at a time can have a border I want my swift code to use a if statement or another sequence to only display a border on one of the buttons if click at a time. So a border can only be seen on one button at a time that button would be the last one pressed. I know I could say layer.border with 0 on each button that should be selected but I want to see if there is a more efficient way to do this.
import UIKit

class ViewController: UIViewController {

    var ba = UIButton()
    var bb = UIButton()
    var bc = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        [ba,bb,bc].forEach {

            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
        }
        ba.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        bb.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
        bc.frame = CGRect(x: 200, y: 0, width: 100, height: 100)

        ba.backgroundColor = .blue
        bb.backgroundColor = .orange
        bc.backgroundColor = .darkGray
        ba.addTarget(self, action: #selector(pressa), for: .touchDown)
        bb.addTarget(self, action: #selector(pressb), for: .touchDown)
        bc.addTarget(self, action: #selector(pressc), for: .touchDown)

    }

    @objc func pressa(){
        ba.layer.borderWidth = 2

    }
    @objc func pressb(){
        bb.layer.borderWidth = 2
      }
    @objc func pressc(){
          bc.layer.borderWidth = 2
      }

}

A: It could be 1 method like this
  [ba,bb,bc].forEach { $0.addTarget(self, action: #selector(pressAll(_:)), for: .touchDown) }
}

@objc func pressAll(_ sender:UIButton) {
    [ba,bb,bc].forEach { $0.layer.borderWidth = 0 } // reset all
    sender.layer.borderWidth = 2
}

A: you can add target to all buttons at the forEach and be only one method as @Sh_Khan mention
import UIKit

class ViewController: UIViewController {

    var ba = UIButton()
    var bb = UIButton()
    var bc = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        [ba,bb,bc].forEach {

            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
      $0.addTarget(self, action: #selector(pressAll(_:)), for: .touchDown)
        }
        ba.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        bb.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
        bc.frame = CGRect(x: 200, y: 0, width: 100, height: 100)

        ba.backgroundColor = .blue
        bb.backgroundColor = .orange
        bc.backgroundColor = .darkGray
    }

  @objc func pressAll(_ sender:UIButton) {
    [ba,bb,bc].forEach { $0.layer.borderWidth = 0 } // reset all
    sender.layer.borderWidth = 2
}

}

A: See how you have used an array in [ba,bb,bc].forEach { ... } to reduce code duplication? Using arrays is the key. Rather than putting the three buttons in an array inline like that, create a property instead:
var buttons: [UIButton]!
override func viewDidLoad() {
    super.viewDidLoad()
    buttons = [ba,bb,bc]
    buttons.forEach {
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.addTarget(self, action: #selector(buttonPressed), for: .touchDown)
    }
    ...
}

I have used the same selector buttonPressed for all three buttons. buttonPressed can accept a parameter of type UIButton, that tells us which button is pressed:
@objc func buttonPressed(_ sender: UIButton) {
    buttons.forEach { ba.layer.borderWidth = 0 } // deselect all buttons first...
    sender.layer.borderWidth = 2 // select the tapped button
}

If you have more than 3 buttons to manage, I suggest you don't use UIButtons at all. You should use a UICollectionView. (Learn how to use them) This view will handle the selection for you. It also allows scrolling when there's not enough space to show all the buttons. You just need to create a custom UICollectionViewCell and override its isSelected property:
override var isSelected: Bool {
    didSet {
        if isSelected {
            self.layer.borderWidth = 2
        } else {
            self.layer.borderWidth = 0
        }
    }
}


text:
Q: Proper place to put Postgres JDBC Driver (postgresql-42.1.4.jar) on linux import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

class Demopsql{

Demopsql()
{
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
            return;
    }
}

where should it be paste postgresql-42.1.4.jar or extracted at where?
so that program won't throw class not found exception.

A: If you are using eclipse, you can follow the method which is written on this post:
Import Libraries in Eclipse?
You will have to put it as an "external jar".
Or you can look at the maven project possibility:
https://maven.apache.org/
You will just have to create a maven project and put a dependency into a file (pom.xml). It will be downloaded when you will do a maven update operation on your project.
I give you the text which should be added to the pom.xml file:
<dependency>
   <groupId>org.postgresql</groupId>
   <artifactId>postgresql</artifactId>
   <version>42.1.4</version>
</dependency>

A: If you are using a build tool like maven, add this jar as a dependency. Otherwise you have to make sure that this jar is accessible in classpath. In Eclipse go to project properties -> build path -> Libraries tab , you can find a button to Add External JARs. Add this JAR as external jar.


text:
Q: Input field not erasing React I'm learning React and I created a simple todo list app and I'm trying to erase the input field as I did for my onClick function on my keypress function. However, it doesn't render the same when I use  setTodoInput(""); on that keypress function. It only shows the first character of the input. If I comment out  setTodoInput(""); out of the keypress function, it works fine, but the input field doesn't erase. I don't understand why although I have a controlled input, it doesn't function the same. if someone can please explain, it would be appreciated.
this is my code for my App file:
import React, { useState } from "react";
import InputArea from "./InputArea";
import ToDoTask from "./ToDoTask";

function App() {
  const [todoTasks, setTodoTasks] = useState([]);

  function addTask(todoInput) {
    setTodoTasks((prevTodoTasks) => {
      return [...prevTodoTasks, todoInput];
    });
  }

  function handleKeyPress(event) {
    if (event.key === "Enter") {
      setTodoTasks((prevTodoInput) => {
        const newTodoInput = event.target.value;
        return [...prevTodoInput, newTodoInput];
      });
      // const newTodoInput = event.target.value;
      //   setTodoTasks((prevTodoTasks) => {
      //     console.log(newTodoInput);
      //     return [...prevTodoTasks, newTodoInput];
      //   });
      // }
    }
  }

  function deleteTodoTask(id) {
    setTodoTasks((prevTodoTasks) => {
      return prevTodoTasks.filter((task, i) => {
        return i !== id;
      });
    });
  }

  return (

To-Do List

        <InputArea onAdd={addTask} onKeyPress={handleKeyPress} />

          {todoTasks.map((todoTasks, i) => (
            <ToDoTask
              key={i}
              id={i}
              text={todoTasks}
              onChecked={deleteTodoTask}
            />
          ))}

  );
}

export default App;

I also created an input component:
import React, { useState } from "react";

function InputArea(props) {
  const [todoInput, setTodoInput] = useState("");

  function handleChange(event) {
    const newInput = event.target.value;
    setTodoInput(newInput);
  }

  return (

      <input
        onKeyDown={(event) => {
          props.onKeyPress(event);
          setTodoInput("");
        }}
        onChange={handleChange}
        type="text"
        value={todoInput}
      />
      <button
        onClick={() => {
          props.onAdd(todoInput);
          setTodoInput("");
        }}
      >
        Add
      </button>

  );
}

export default InputArea;

this is my todoTask component:
import React from "react";

function ToDoTask(props) {
  return (

 {
        props.onChecked(props.id);
      }}
    >

{props.text}

  );
}

export default ToDoTask;

A: If the goal is to clear the input when "enter" is pressed then I suggest using a form element. So long as there is just the one input then pressing enter while focused will submit the form. Use the form's submit handler to call the onAdd callback and reset the local todoInput state.
InputArea
function InputArea({ onAdd }) {
  const [todoInput, setTodoInput] = useState("");

  const submitHandler = (e) => {
    e.preventDefault();
    if (todoInput) {
      onAdd(todoInput);
      setTodoInput("");
    }
  };

  function handleChange(event) {
    const { value } = event.target;
    setTodoInput(value);
  }

  return (
    <form onSubmit={submitHandler}>
      <input onChange={handleChange} type="text" value={todoInput} />
      <button type="submit">
        Add
      </button>
    </form>
  );
}

Demo

function InputArea({ onAdd }) {
  const [todoInput, setTodoInput] = React.useState("");

  const submitHandler = (e) => {
    e.preventDefault();
    if (todoInput) {
      onAdd(todoInput);
      setTodoInput("");
    }
  };

  function handleChange(event) {
    const { value } = event.target;
    setTodoInput(value);
  }

  return (
    <form onSubmit={submitHandler}>
      <input onChange={handleChange} type="text" value={todoInput} />
      <button type="submit">
        Add
      </button>
    </form>
  );
}

function ToDoTask(props) {
  return (

 {
        props.onChecked(props.id);
      }}
    >

{props.text}

  );
}

function App() {
  const [todoTasks, setTodoTasks] = React.useState([]);

  function addTask(todoInput) {
    setTodoTasks((prevTodoTasks) => {
      return [...prevTodoTasks, todoInput];
    });
  }

  function deleteTodoTask(id) {
    setTodoTasks((prevTodoTasks) => {
      return prevTodoTasks.filter((task, i) => {
        return i !== id;
      });
    });
  }

  return (

To-Do List

        <InputArea onAdd={addTask} />

          {todoTasks.map((todoTasks, i) => (
            <ToDoTask
              key={i}
              id={i}
              text={todoTasks}
              onChecked={deleteTodoTask}
            />
          ))}

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);


text:
Q: Как сбросить тригер Вопрос такой, пользователь вводит текст, дальше, он нажимает на любое место в форме, и ввод текста больше не доступен.
Я понимаю что нужно использовать тригер, но какой, и как?

A: Прмиерно вот так. А что бы отработало при нажатии на любой элемент на форме RoutedEvent="Mouse.PreviewMouseDown" но тогда не представляю как вы будете вводить текст, но вы сами так поставили задачу
   <Window.Triggers>
        <EventTrigger RoutedEvent="Mouse.MouseDown">
            <BeginStoryboard>
                <Storyboard>
                    <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsEnabled"
                                                            Storyboard.TargetName="TextBox1">
                        <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="False"/>
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Window.Triggers>
    <Grid>
        <TextBox x:Name="TextBox1" Width="200" Height="50"/>
    </Grid>


text:
Q: Brute-force transposition decryption - word segmentation I'm a 2nd year B. Comp. Sci. student and have a cryptography assignment that's really giving me grief. We've been given a text file of transposition-encrypted English phrases and an English dictionary file, then asked to write a program that deciphers the phrases automatically without any user input.
My first idea was to simply brute-force all possible permutations of the ciphertext, which should be trivial. However, I then have to decide which one is the most-likely to be the actual plaintext, and this is what I'm struggling with.
There's heaps of information on word segmentation here on SO, including this and this amongst other posts. Using this information and what I've already learned at uni, here's what I have so far:
string DecryptTransposition(const string& cipher, const string& dict)
{
    vector<string> plain;

    int sz = cipher.size();
    int maxCols = ceil(sz / 2.0f);
    int maxVotes = 0, key = 0;

    // Iterate through all possible no.'s of cols.
    for (int c = 2; c <= maxCols; c++)
    {
        int r = sz / c;     // No. of complete rows if c is no. of cols.
        int e = sz % c;     // No. of extra letters if c is no. of cols.

        string cipherCpy(cipher);
        vector<string> table;
        table.assign(r, string(c, ' '));

        if (e > 0) table.push_back(string(e, ' '));
        for (int y = 0; y < c; y++)
        {
            for (int x = 0; x <= r; x++)
            {
                if (x == r && e-- < 1) break;
                table[x][y] = cipherCpy[0];
                cipherCpy.erase(0, 1);
            }
        }
        plain.push_back(accumulate(table.begin(),
            table.end(), string("")));

        // plain.back() now points to the plaintext
        // generated from cipher with key = c
        int votes = 0;
        for (int i = 0, j = 2; (i + j) <= sz; )
        {
            string word = plain.back().substr(i, j);
            if (dict.find('\n' + word + '\n') == string::npos) j++;
            else
            {
                votes++;
                i += j;
                j = 2;
            }
        }
        if (votes > maxVotes)
        {
            maxVotes = votes;
            key = c;
        }
    }
    return plain[key - 2];      // Minus 2 since we started from 2
}

There are two main problems with this algorithm:

*

*It is incredibly slow, taking ~30 sec. to decrypt a 80-char. message.

*It isn't completely accurate (I'd elaborate on this if I hadn't already taken up a whole page, but you can try it for yourself with the full VC++ 2012 project).

Any suggestions on how I could improve this algorithm would be greatly appreciated. MTIA :-)


text:
Q: Fluent validation Db password with user input I would like to know what can I do to have properly running my code.
I want to validate the oldPassword enter by the user in the form against the password that is stored in the db. Is they are the same is good to go if are different raise an error.
So far I have this but I have errors and don't pretty sure how to fix it.
I have the function IsSameAsOldPassword but i dont know how to send the parameters.
RuleSet(() => RuleFor(x => x.OldPassword)
                    .Must((x) => IsSameAsOldPassword(x.Id, x.OldPassword))
                    .WithMessage("Old password incorrect"), RuleSets.Update);

private bool IsSameAsOldPassword(Guid id, string oldPassword)
{
    var user = _userManager.FindByIdAsync(id.ToString());
    return _userManager.CheckPasswordAsync(user.Result, oldPassword).Result;
}

Any improvement to the code will be welcome.

A: I just found a solution, hope this help someone else, we just need to remove the field. the final solution will be like this:
RuleSet(() =>
{
    RuleFor(x => x)
        .MustAsync((x, cancellation) => IsSameAsOldPassword(x))
        .WithMessage("Old password incorrect");
}, RuleSets.Update);

private async Task<bool> IsSameAsOldPassword(UserSetInputModel userInputModel)
{
    userInputModel.fieldToUse
}


text:
Q: fabfile.py not working: No module named Crypto I was following this tutorial, and reached the section on using Fabric to deploy django projects. However when I run my fabfile.py I get this error. And here is my fabfile.py. For what i can deduce the Crypto library is missing, by I've tried pip install Crypto and still get the same error. Any suggestions? Thanks.

A: It could be that when you installed it, it didn't compile all the necessary files. Try re-installing again.  Make sure you see no errors, if you do you might be missing some development files/headers.
pip uninstall pycrypto
pip install pycrypto

You can just test it from the python shell:
python

Then:
>>> import Crypto

If you don't see any errors you are good.
If for some reason the module got compiled as crypto instead of Crypto on the Mac you can try:
>> import crypto
>> import sys
>> sys.modules['Crypto'] = crypto


text:
Q: Autenticação com Spring Security Olá, estou fazendo um projeto utilizando o Spring Framework, e preciso fazer uma autenticação bem simples, usando usuários criados na tabela user mesmo (sem qualquer integração com redes sociais). Porém não sei como fazer, estou utilizando Spring e AngularJs, como faço para o usuário se autenticar? Tenho pouquíssima experiência com Spring.
Obrigado.

A: Utilizando JWT.
Manager:
public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserRepository repository;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        try {
            User user = repository.findByEmail(auth.getName().toString());
            if (auth.getCredentials().toString().equals(user.getPassword())) {
                return auth;
            }
        } catch (NullPointerException e){
            throw new BadCredentialsException("Usuário não cadastrado!");
        }
        throw new BadCredentialsException("Senha incorreta");
    }
}

Configuration:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // disable caching
        http.headers().cacheControl();
        http.csrf().disable()
                // disable csrf for our requests.
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
                .antMatchers(HttpMethod.GET, "/api/questions/**").permitAll()
                .antMatchers(HttpMethod.GET, "/api/answers/**").permitAll()
                .antMatchers(HttpMethod.POST, "/api/users").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/api/users").permitAll()
                .antMatchers(HttpMethod.GET, "/api/comment/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/login requests
                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                // And filter other requests to check the presence of JWT in header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOrigin("*"); //Cors
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.addExposedHeader("Authorization");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return new CustomAuthenticationManager();
    }
}

Serviço para autenticar o token:
public class TokenAuthenticationService {

    private long EXPIRATIONTIME = 1000 * 60 * 60 * 24 * 10; // 10 days
    private String secret = "Meu secret";
    private String tokenPrefix = "Bearer";
    private String headerString = "Authorization";
    public void addAuthentication(HttpServletResponse response, String username)
    {
        // We generate a token now.
        String JWT = Jwts.builder()
                    .setSubject(username)
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .compact();
        response.addHeader(headerString,tokenPrefix + " "+ JWT);
    }

    public String getUserName(String token){
        if(token != null)
        {
            // parse the token.
            String username = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
            if(username != null) // we managed to retrieve a user
            {
                return username;
            }
        }
        return null;
    }

    public Authentication getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader(headerString);
        if(token != null)
        {
            // parse the token.
            String username = Jwts.parser()
                        .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody()
                        .getSubject();
            if(username != null) // we managed to retrieve a user
            {
                return new AuthenticatedUser(username);
            }
        }
        return null;
    }
}


text:
Q: How should one properly handle opening and closing of Azure Service Bus/Topic Clients in an Azure Function? I'm not sure of the proper way to manage the lifespans of the various clients necessary to interact with the Azure Service Bus. From my understanding there are three different but similar clients to manage: ServiceBusClient, a Topic/Queue/Subscription Service, and then a Sender of some sort. In my case, its TopicService and a Sender. Should I close the sender after every message? After a certain amount of downtime? And same with all the others? I feel like I should keep the ServiceBusClient open until the function is entirely complete, so that probably carries over to the Topic Client as well. There's just so many ways to skin this one, I'm not sure where to start to draw the line. I'm pretty sure it's not this extreme:
function sendMessage(message: SendableMessageInfo) {
    let client=createServiceBusClientFromConnectionString(connectionString)
    let tClient = createTopicClient(client);
    const sender = tClient.createSender();
    sender.send(message);
    sender.close();
    tClient.close();
    client.close();
}

But leaving everything open all the time seems like a memory leak waiting to happen. Should I handle this all through error handling? Try-catch, then close everything in a finally block?
I could also just use the Azure Function binding, correct me if I'm wrong:
const productChanges: AzureFunction = async function (context: Context, products: product[]): Promise<void> {
    context.bindings.product_changes = []
    for (let product of product) {
        if(product.updated) {
            let message = this.createMessage(product)
            context.bindings.product_changes.push(message)
        }
    }
    context.done();
}

I can't work out from the docs or source which would be better (both in terms of performance and finances) for an extremely high throughput Topic (at surge, ~100,000 requests/sec).
Any advice would be appreciated!

A: In my opinion, we'd better use Azure binding or set the client static but not create the client every time. If use Azure binding, we will not consider the problem about close the sender, if set the client static, it's ok too. Both of the solutions have good performance and there is no difference in cost (you can refer to this tutorial for servicebus price: https://azure.microsoft.com/en-us/pricing/details/service-bus/) between these twos. Hope it would be helpful to your question.

A: I know this is a late reply, but I'll try to explain the concepts behind the clients below in case someone lands here looking for answers.
Version 1
_ ServiceBusClient (maintains the connection)
  |_ TopicClient
     |_ Sender (sender link)

Version 7
_ ServiceBusClient (maintains the connection)
  |_ ServiceBusSender (sender link)

In both version 1 and version 7 of @azure/service-bus SDK, when you use the sendMessages method or the equivalent send method for the first time, a connection is created on the ServiceBusClient if there was none and the new sender link is created.
The sender link remains active for a while and is cleared on its own(by the SDK) if there is no activity. Even if it is closed by inactivity, the subsequent send call even after waiting for a long duration would work just fine since it creates a new sender link.
Once you're done using the ServiceBusClient, you can close the client and all the internal senders, receivers are also closed with this if they are not already closed individually.
The latest version 7.0.0 of @azure/service-bus has been released recently.

*

*@azure/service-bus - 7.0.0

*Samples for 7.0.0

*Guide to migrate from @azure/service-bus v1 to v7


text:
Q: How to copy files on unix shell using wildcards I'm trying to copy some files into existing folders. This is an example of the schema
# origin
/home/user/myfiles/folder1/group1/1.jpg
/home/user/myfiles/folder1/group1/2.jpg
/home/user/myfiles/folder1/group2/1.jpg
/home/user/myfiles/folder1/group2/2.jpg
/home/user/myfiles/folder2/group1/1.jpg
/home/user/myfiles/folder2/group1/2.jpg
/home/user/myfiles/folder2/group2/1.jpg
/home/user/myfiles/folder2/group2/2.jpg

The destination folder schema already exists, its just the origin files (jpgs) that are not there.
My question is how to do this?
I would like to end up with something like below, but this is not working. Maybe I should include regex in the query to separate asterisk into values and use as origin/destination?
 cp /home/user/myfiles/*/*/*.jpg  /home2/user/myfiles/*/*/*.jpg

My original intend is to use this copying schema on my unanswered question:  s3cmd: how to copy files from local to S3 bucket with existing structure as a possible solution.

A: With GNU cp you can use the --parents option, like this:
cd /home/user/myfiles ; cp --parents */*/*.jpg /home2/user/myfiles/

You have to cd first because if you do cp --parents /home/user/myfiles/... it will create those parents too, and you'll end up with /home2/user/myfiles/home/parents/myfiles/.
If you need a non-GNUish answer, the traditional unix method would be tar over a pipe.
cd /home/user/myfiles ; tar cf - */*/*.jpg | ( cd /home2/user/myfiles ; tar xf - )

The second cd is in a subshell with the second tar, so that's where the files get extracted. The tarball itself is created, sent over the pipe, and extracted all at the same time. Add a v flag to one of the tars if you want progress reporting.

A: The following should do the trick:
for i in `find /home/user/myfiles/folder1 -print`; do
  if [ ! -d $i ];
    then filePath=`echo $i | cut -f 4- -d"/"`;
         cp $i /home/user/myfiles/folder2/$filePath;
  fi;
done

Basically, I am extracting the part of the filename that is going to change between the two folders, and then issuing a copy command.
Notice the "cut -f 4-" above - it gets the fields from the 4th one onwards. You can change the number as per your wish
Perhaps even basename or a simpler command exists... but this will do for now :)


text:
Q: Combine two given Elliptic Curves I want to combine two Elliptic curves such $E_p$ (defined in the field $F_p$) and $E_q$  (defined in the field $F_q$) i.e to find $E_n$ where $n=pq$. Is there any method to do it?

A: Here is a concrete example. Let $E_5: y^2 = x^3+1$, defined over $\mathbb{F}_5$, and let $E_7: y^2=x^3+2x+3$ defined over $\mathbb{F}_7$. We want to find an elliptic curve $E/\mathbb{Q} : y^2=x^3+Ax+B$, with $A,B\in \mathbb{Z}$ such that $E\equiv E_5 \bmod 5$ and $E\equiv E_7 \bmod 7$. It suffices to find integers $A$ and $B$ such that
$$\begin{cases}A\equiv 0\bmod 5,\\ A\equiv 2\bmod 7\end{cases},\quad \text{ and }\quad  \begin{cases}B\equiv 1\bmod 5,\\ B\equiv 3\bmod 7\end{cases}.$$
The solutions of these congruences are
$$A\equiv 30 \bmod 35, \quad \text{ and } \quad B\equiv 31 \bmod 35,$$
so we can pick $A=30$ and $B=31$, and the curve we are looking for is
$$E: y^2=x^3+30x+31$$
whose discriminant is $\Delta=-2143152= -2^4\cdot 3^3\cdot 11^2\cdot 41\neq 0$, so $E$ is non-singular, and by construction, $E\equiv E_5 \bmod 5$ and $E\equiv E_7 \bmod 7$.

A: I assume you want to construct $E ~ \colon \quad  y^2+a_1 xy + a_3 y=x^3 + a_2x^2+a_4x+a_6$ modulo $pq$ so that modulo $p$ the $a_i$ coefficients are the same as those of $E_p$ and modulo $q$ as those of $E_q$. This is possible by using the Chinese Remainder theorem to (uniquely) determine each coefficient. Of course, curves with the same coefficients mod $p$ will have the same points mod $p$.
But I think most people will agree that this construction isn't mathematically interesting.

A: Chinese remainder theorem is the way to understand elliptic curves (mod n).  You have to be careful about points that are infinity mod p but not mod q.
Such curves have been used for some crypto applications.  See:

*

*N. Demytko, A New Elliptic Curve Based Analogue of RSA, EUROCRYPT 1993, 40-49.

*S. Galbraith, Elliptic curve Paillier schemes, Journal of Cryptology, Vol. 15, No. 2 (2002) 129-138.


text:
Q: filter from dplyr: where two string columns need to be compared along with numeric I need to apply the filter condition on String columns along with numeric columns. This way it is not giving the expected output. If anyone has encountered the same problem, please help
Num1<-c(1,2,3,4,5)
Num2<-c(1,2,2,1,1)
String1<-c("AA","BB","CC","DD","EE")
String2<-c("AA","BB","CC","DD","FF")
data<-c(Num1,Num2,String1,String2)
df<-data%>%
filter((Num2<Num1) & (String1==String2))

A: We need to create a data.frame instead of a vector
data<- data.frame(Num1,Num2,String1,String2, stringsAsFactors=FALSE)

and then the OP would work
data %>%
    filter(Num2 < Num1 & String1 == String2)
#   Num1 Num2 String1 String2
#1    3    2      CC      CC
#2    4    1      DD      DD


text:
Q: Properties change with out a server restart I have externalized all my application needed property files from webapps in tomcat. Now i can simply change a property file value without a need of rebuilding the war file and deploy it again. However each change to property file is associated with server recyling.
Is there a way how the recycling can be avoided for a property file change.
I am using spring to read the property files for few webapps and java property traditional way for few webapps.
Please suggest how to acheive

A: You may want to consider spring-cloud-config-server or spring-cloud-consul all of these options supports distributed properties management as well as value changes refresh without a need to recycle app servers.
And you can use @RefreshScope for Spring @Beans that want to be reinitialized when configuration changes, they also provide the following Management endpoints out of the box and many more as explained  on the project git page

*

*/refresh for refreshing the @RefreshScope beans

*/restart for restarting the Spring context (disabled by default)

This is supported by either option (spring-cloud-config-server or spring-cloud-consul)

A: You may also give cfg4j a try. It supports reloading configuration from local files as well as remote services (git repository, Consul, etc.).


text:
Q: TeXLive2016 lualatex does not use optical sizes for MinionPro opentype font With current texlive 2016, the file
\documentclass{article}
\usepackage{fontspec}
\defaultfontfeatures{Ligatures={TeX}}
\setmainfont{Minion Pro}

\begin{document}%
\newcommand{\MyText}{No offence meant, I even upvoted your answer.}

\verb|\tiny|=\tiny\MyText\par
\verb|\scriptsize|=\scriptsize\MyText\par
\verb|\footnotesize|=\footnotesize\MyText\par
\verb|\normalsize|=\normalsize\MyText\par
\verb|\large|=\large\MyText\par
\verb|\Large|=\Large\MyText\par
\verb|\LARGE|=\LARGE\MyText\par
\verb|\huge|=\huge\MyText\par
\verb|\Huge|=\Huge\MyText\par

\end{document}

results in a PDF that makes use of LMMono8, -10, and -12, but from the MinionPro Opticals, only MinionPro-Regular is used. Switching back to
TeXLive-2015 results in a file with MinionPro-Regular, -Capt, -Subh, and -Disp, as expected.
Any hint on how to restore automatic selection of proper optical
sizes for opentype fonts?

A: Section 8.6 of the fontspec manual says:

[...] OpenType fonts with optical scaling will exist in several discrete
  sizes, and these will be selected by XETEX and LuaTEX automatically
  determined by the current font size [...]

But it can only do so, if it gets the information it needs to make this automatical selection. What information does it need? The fontspec manual only gives an indrect hint in the next paragraph by specifing how it expects the information to be provided:

The SizeFeatures feature (Section 7.6 on page 17) can be
  used to specify exactly which optical sizes will be used for ranges
  of font size. [...]

Fontspec needs the design sizes of the fonts. As the name says this size is determined by the font designer. Unfortunately the otf file format does not contain this information. If you buy the fonts they usually come with a readme file. In case of Minion Pro this readme file has a section on optical sizes. There a little table can be found, that provides the need information.

Caption: from 6.0 to 8.4 points
Body Text: from 8.4 to 13.0 points
Subhead: from 13.0 to 19.9 points
Display: from 19.9 to 72.0 points

This table is likely to be different for every font, because the respective font designer made different choices.
As already mentioned in the comments you now can change
\setmainfont{Minion Pro}

which is not enough, too
\setmainfont{minionpro-}[
Extension={.otf},
UprightFont={*regular},
ItalicFont={*it},
BoldFont={*bold},
BoldItalicFont={*boldit},
Numbers={Proportional,OldStyle},
SizeFeatures={
    {Size={-8.4},Font=*capt},
    {Size={8.4-13.0}},
    {Size={13.0-19.9},Font=*subh},
    {Size={19.91-},Font=*disp}
}]

This is of course dependant on the naming conventions of the otf files. As there is no standard that I am aware of you probably have to adjust them. The otf files on my computer are all in lower case thus I have file names like:
minionpro-capt.otf
minionpro-regular.otf
minionpro-subh.otf
minionpro-disp.otf

for the upright fonts, for the italics ones I have
minionpro-itcapt.otf
minionpro-it.otf
minionpro-itsubh.otf
minionpro-itdisp.otf

and so on
minionpro-boldcapt.otf
minionpro-bold.otf
minionpro-boldsubh.otf
minionpro-bolddisp.otf

Minion Pro also comes with medium and semibold versions. Thus if the "normal" bold version is too bold, then one could replace them by changing
BoldFont={*bold},
BoldItalicFont={*boldit},

into
BoldFont={*medium},
BoldItalicFont={*mediumit},

fontspec also offers to work with the font names instead for the fonts file names. According to the fontspec manual section 7.6 page 22

Interaction with other features For SizeFeatures to work with ItalicFeatures, BoldFeatures, etc., and SmallCapsFeatures, a strict heirarchy is required: [...]

I can get it to work by writing this:
\setmainfont{Minion Pro}[
Numbers={Proportional,OldStyle},
UprightFeatures={
  SizeFeatures={
    {Size={-8.4},Font=*Capt},
    {Size={8.4-13.0},Font=*Regular},
    {Size={13.0-19.9},Font=*Subh},
    {Size={19.9-},Font=*Disp}
}},
ItalicFeatures={
  SizeFeatures={
    {Size={-8.4},Font=*It Capt},
    {Size={8.4-13.0},Font=*It},
    {Size={13.0-19.9},Font=*It Subh},
    {Size={19.9-},Font=*It Disp}
}},
BoldFeatures={
  SizeFeatures={
    {Size={-8.4},Font=*Bold Capt},
    {Size={8.4-13.0},Font=*Bold},
    {Size={13.0-19.9},Font=*Bold Subh},
    {Size={19.9-},Font=*Bold Disp}
}},
BoldItalicFeatures={
  SizeFeatures={
    {Size={-8.4},Font=*Bold It Capt},
    {Size={8.4-13.0},Font=*Bold It Capt},
    {Size={13.0-19.9},Font=*Bold It Subh},
    {Size={19.9-},Font=*Bold It Disp}
}}]

A: Before fontspec is loaded the document class defines all font sizes, the reason why Latin Modern is used here as a default. However, after loading fontspec and using \setmainfont everything is redefined. Compare the output: in the left column there is Minion Pro and in the right Latin Modern.
\documentclass[twocolumn]{article}
\usepackage{fontspec}
\setmainfont{Minion Pro}
\parindent=0pt
\newcommand\MyText{No offence meant, I even upvoted your answer.}
\newcommand\cs[1]{\texttt{\textbackslash#1}}

\begin{document}%

    \cs{tiny}=\tiny\MyText\par
    \cs{scriptsize}=\scriptsize\MyText\par
    \cs{footnotesize}=\footnotesize\MyText\par
    \cs{normalsize}=\normalsize\MyText\par
    \cs{large}=\large\MyText\par
    \cs{Large}=\Large\MyText\par
    \cs{LARGE}=\LARGE\MyText\par
    \cs{huge}=\huge\MyText\par
    \cs{Huge}=\Huge\MyText\par

\newpage\normalsize
\fontspec{Latin Modern Roman}
    \cs{tiny}=\tiny\MyText\par
    \cs{scriptsize}=\scriptsize\MyText\par
    \cs{footnotesize}=\footnotesize\MyText\par
    \cs{normalsize}=\normalsize\MyText\par
    \cs{large}=\large\MyText\par
    \cs{Large}=\Large\MyText\par
    \cs{LARGE}=\LARGE\MyText\par
    \cs{huge}=\huge\MyText\par
    \cs{Huge}=\Huge\MyText\par
\end{document}

However, the
[...]
ZUQBJT+MinionPro-Capt-Identity-H     CID Type 0C       Identity-H       yes yes yes      9  0
GZICFI+MinionPro-Subh-Identity-H     CID Type 0C       Identity-H       yes yes yes     15  0
VLPSCX+MinionPro-Disp-Identity-H     CID Type 0C       Identity-H       yes yes yes     17  0
[...]

are used only by xelatex, if not defined via fontspec