text:
Q: Array with integers and string in iphone app Im creating a rugby app where I need to make a record of every time a match event occurs. So every time there is a pass they click pass, every time theres a tackle they press tackle etc.
This information then is going to be put in an external database so it can be also viewed on a website.
So the events in the app will be recorded and look similar to this.
1, pass
2, pass
3, try
4, pass
etc
When the user clicks up upload itll be uploaded to the database so will be using sql.
Because the pass is a string and ID is a number will I have problems?
Is this the best way to go about this ?
Thanks

A: If you want to store Strings and Numbers in the same array use NSNumber instead of int
NSNumber *myNumber = [NSNUmber numberWithInt:3]

or
NSNumber *myNumber = @3;

Later , when uploading data, if you want you can retrieve the human-readable string value from the integer like this,
   [myNumber stringValue];


text:
Q: How to scroll DataRow items in DataTable widget I have DataTable widget contains four DataColumn and many DataRow, As it is shown in the picture:

The problem is that I cannot scroll DataRow items, with Keeping header,
I tried SingleChildScrollView Widget but to no avail, The result is :

What I want is just scroll the content DataTable and not the whole DataTable.
Thanks...

A: You need to create your own table widget:

import 'dart:math';

import 'package:flutter/material.dart';

Random random = Random();
void main() => runApp(
      MyApp(),
    );

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stackoverflow'),
        ),
        body: SafeArea(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

String getRandomDateString() =>
    DateTime.now().subtract(Duration(days: random.nextInt(100))).toString();

List<String> generateMockRowData() => [
      random.nextInt(10000).toString(),
      random.nextInt(10000).toString(),
      random.nextInt(10000).toString(),
      getRandomDateString()
    ];
List<List<String>> mockData =
    List<List<String>>.generate(300, (_) => generateMockRowData());

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Color(0xFFF4F1F1),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          SizedBox(height: 10),
          _header(),
          SizedBox(height: 10),
          Divider(
            height: 1,
          ),
          Flexible(
            child: ListView.separated(
              itemBuilder: (_, index) {
                return Padding(
                  padding: EdgeInsets.only(top: index == 0 ? 10 : 0),
                  child: _getRow(mockData[index]),
                );
              },
              separatorBuilder: (_, __) => Divider(),
              itemCount: mockData.length,
            ),
          )
        ],
      ),
    );
  }

  _header() {
    return Row(
      children: <Widget>[
        _element(Text(
          'Col4',
          textAlign: TextAlign.end,
        )),
        _element(Text(
          'Col3',
          textAlign: TextAlign.end,
        )),
        _element(Text(
          'Col2',
          textAlign: TextAlign.end,
        )),
        _element(
            Text(
              'Col1',
              textAlign: TextAlign.end,
            ),
            2),
      ],
    );
  }

  Flexible _element(Widget widget, [flex = 1]) {
    return Flexible(
      fit: FlexFit.tight,
      flex: flex,
      child: widget,
    );
  }

  Widget _getRow(List<String> data) {
    return Row(
      children: [
        _element(Text(
          data[0],
          textAlign: TextAlign.end,
        )),
        _element(Text(
          data[1],
          textAlign: TextAlign.end,
        )),
        _element(Text(
          data[2],
          textAlign: TextAlign.end,
        )),
        _element(
            Text(
              data[3],
              textAlign: TextAlign.end,
            ),
            2),
      ],
    );
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to automatically call a method when Session["something"] throws a NullReferenceException? I am going to be using Session["firmaid"] quite alot in my application. This value is set when someone logs in to my system.
If something happens, and this value is lost from the Session, i would like to somehow have a global method that will get it, if it throws a NullReferenceException.
How can i do this?
Currently, my solution is to try and catch every time i use Session["firmaid"], then execute the method that will put firmaid in the Session, if it throws an Exception.
Is there an easier way to do this?

A: Instead of try/catching everytime you could wrap the access to the session in a strongly typed class and then access the session through this wrapper.
Or even write an extension method:
public static class SessionExtensions
{
    public static string GetFirmaId(this HttpSessionStateBase session)
    {
        var firmaid = session["firmaid"] as string;
        if (string.IsNullOrEmpty(firmaid))
        {
            // TODO: call some method, take respective actions
        }
        return firmaid;
    }
}

and then in your code instead of:
try
{
    var firmaid = Session["firmaid"];
    // TODO: do something with the result
}
catch (Exception ex)
{
    // TODO: call some method, take respective actions
}

use:
var firmaid = Session.GetFirmaId();
// TODO: do something with the result

A: Why not simply write a static wrapper around this? Much more robust and more DRY:
public static int GetFirmaid() {
  if (HttpContext.Current.Session["firmaid"] == null) {
     //do something to fall back
  }
  return HttpContext.Current.Session["firmaid"]
}

You obviously would have to put this in a Class you can easily access and then call it through:
Class.GetFirmaid()

A: You can create an action filter which will ensure that Session["firmaid"] has a value:
public class SetFirmaIdAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        try
        {
            var firmaId = Session["firmaid"];
        }
        catch (Exception ex)
        {
            // pass filterContext if you need access to Request, Session etc.
            Session["firmaid"] = SetFirmaId(filterContext);
        }
   }

   private int SetFirmaId(ActionExecutingContext filterContext)
   {
       // TODO: implement some logic
   }
}

OnActionExecuting will be called before action executes so you will already have Session["firmaid"] set when the action gets executed.
Once you implement this attribute you can put it on an action, controller or set it as global.


text:
Q: PL/SQL Developer Initialization error I want use PL/SQL Developer
first my oracle directory
C:\oracle\product\10.2.0\client_1\BIN
I use windows10 and environment variable setting
ORACLE_HOME C:\oracle\product\10.2.0\client_1
Path C:\oracle\product\10.2.0\client_1\BIN
but execute Initialization error.
Initialization error
Could not load "C:\oracle\product\10.2.0\client_1\bin\oci.dll"

OracleHomeKey: SOFTWARE\ORACLE\KEY_OraClient10g_home1
OracleHomeDir: C:\oracle\product\10.2.0\client_1
Found: oci.dll
Using: C:\oracle\product\10.2.0\client_1\bin\oci.dll
LoadLibrary(C:\oracle\product\10.2.0\client_1\bin\oci.dll) return 0

A: I meet the same error on my new windows 10 computer. At last i found that i missed the Microsoft Visual Studio 2013 Redistributable. After i install it, the error gone.

A: I was getting below error while connecting to database from PL/SQL developer (in windows10 64 bit).

Initialization error
Could not initialize
"C:\app<username>\product\12.2.0\dbhome_1\bin\oci.dll"

Make sure you have the 32 bits Oracle Client installed.
OracleHomeKey:
OracleHomeDir: C:\app\<username>\product\12.2.0\dbhome_1
Found: oci.dll
Using: C:\app\<username>\product\12.2.0\dbhome_1\bin\oci.dll
LoadLibrary(C:\app\<username>\product\12.2.0\dbhome_1\bin\oci.dll)
return 0

To resolve this issue, refer to the below documentation provided by Oracle to install the Oracle Instant Client. If your windows is 64 bit, then download the 32 bit Oracle Instant Client from below link -
Oracle guide
Link to download the Oracle Instant Client - (Download the BASIC and SDK and SQL*Plus Package)
Take all the above three packages in one directory and extract the same and add the path of extracted directory in system environment variable PATH and OCI_LIB32.
If OCI_LIB32 is not present then create the same.
Try to connect to database from PLSQL developer, if you getting error as 'ORACLE initialization or shutdown in progress' then go through the below link
Good Luck :)

A: *

*download oracle instant client (64 bits for latest version of PL/SQL; 32 bits for old version)

*extract to a folder. for example: c:\oracle\instantclient

*open PL/SQL developer--> Configure--> Preferences --> Oracle Connection

*under OCI library, keyin OCI.DLL file path in the text box: c:\oracle\instantclient\oci.dll

*click OK and restart PL/SQL

A: Check Environment Variables %PATH%

A: I had the similar problem and these steps did helped me
steps:

*

*Download oracle instant client (64 bits for latest version of PL/SQL; 32 bits for old version)

*Extract to a folder. for example: c:\oracle\instantclient

*Open PL/SQL developer--> Configure-->Preferences--> Oracle Connection

*Under OCI library, keyin OCI.DLL file path in the text box: c:\oracle\instantclient\oci.dll

*Click OK and restart PL/SQL
done

A: Most of the cases this happens

*

*If you dont have any oracle client

In this case, you can download instant client and put it in C drive, then copy the path of the oci.dll file path and put it in the OCI library text field in the PL SQL Dev config option

*If you have multiple oracle home

If you have multiple homes reflecting, then check the correct oracle home from the Oracle Home drop down in PLSQL Dev config option.
Attached the image of the config screen for easy reference.

A: Download oracle client after that use PL/SQL to connect


text:
Q: PHPMailer - how to check if address(es) added You add addresses via $mailer->addAddress($address['mail'], $address['name']);. But how do you check if there are any address(es) added to the PHPMailer instance?
Pseudo code:
if (count($mailer->Addresses) > 0) {
    $mailer->send();
}

Thanks in advance!

A:
You can use getAllRecipientAddresses() function  of
PHPMailer class
to get all the email addresses.

https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php#L4988
It allows for public read access to all_recipients property.


text:
Q: Can Dictionary values be populated through a list without looping? Can we have something like -
Dictionary<string, string> dict = new Dictionary<string, string>();

List<string> keysList=  new List<string>();
List<string>valuesList=  new List<string>();

//Assuming both the list have the same number of items
dict.keys = keysList;
dict.values = valuesList;

Mostly, I want to know if there is a way to populate the keys and values by directly assigning them to a list?

A:
Mostly, I want to know if there is a way to populate the keys and values by directly assigning them to a list?

No, but just zip them and then use ToDictionary:
var dict = keysList.Zip(valuesList, (key, value) => Tuple.Create(key, value))
                   .ToDictionary(pair => pair.Item1, pair => pair.Item2);

A: A dictionary, internally isn't storing the data as two lists.  It's storing the data in a hash table, which means it need to take each key, generate a hash for it, and then place the item at the location that corresponding to that hash.  Because of this the only way to add a group of items is just to loop through the group and add each item.  You can use the LINQ ToDictionary method, as mentioned in another answer, but internally all it's going to do is loop through each item and add it to the dictionary.  This prevents you from seeing the loop, but the loop is still there.


text:
Q: Reiniciar winodws form en c# luego de inactividad Es posible que los valores de mi form windows (digase labels, textbox, picturebox, datagrids) se borren o regresen a su valor null luego de que haya pasado cierto tiempo y de ser posible cómo o cuál es el método para poder lograr esto?
Y si alguien tiene un pequeño ejemplo de que hay que hacer se agradece también pero cualquier ayuda es bienvenida

A: Para lo que planteas se puede usar System.Windows.Forms.Timer. En el siguiente ejemplo luego de 10 segundos se borra una caja de texto (este comportamiento se define en el manejador del timer (timer1_Tick). Se detiene con un Stop sobre la instancia del Timer.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;
        }

        private void setTimer()
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();

            t.Interval = 10000; // Especificas el tiempo que queres en milisegundos. En este caso le puse 10 segundos
            t.Tick += new EventHandler(timer1_Tick);
            t.Start();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            setTimer();

        }

    }

}

Saludos y espero sea de tu utilidad.


text:
Q: IDE recomendation for postscript Im learning postscript to use in making vector art with my laser-cutter.
I have been straight typing all the code, and began wondering what is out there for PostScript IDE.

A: You can try PostScript Development Tools for Eclipse.
It features syntax coloring, outline view, code folding, content assist, auto-edit for brackets, marked syntax errors, debugger, documentation, integration with ghostscript.


text:
Q: $\dim$ $C(X,\mathbb{R})<\infty$ we need to show $|X|<\infty$, $X$ be a compact Hausdorff space such that $\dim$ $C(X,\mathbb{R})<\infty$  we need to show $|X|<\infty$, I must say I have no idea how to prove this result. please help. Thank you!

A: Let $N$ be the dimension of $C(X,\Bbb R)$. Assume that there are $N+1$ distinct points $x_1,\dots,x_{N+1}$ in $X$. As $X$ is compact and Hausdorff it is normal, hence by the Urysohn lemma, we can find for each $j$ a continuous function $g_j\colon X\to\Bbb R$ such that $g_j(x_k)=0$ when $k\neq j$ and $g_j(x_j)=1$.
The family $\{g_j,1\leqslant j\leqslant N+1\}$ is necessarily linearly dependent, so we can assume that $g_{N+1}=\sum_{j=1}^Ng_j$. Evaluating this equality at $x_{N+1}$ yields a contradiction.
This proves that $\dim C(X,\Bbb R)=\operatorname{card}(X)$.
The result is not necessarily true when $X$ is not assumed to be Hausdorff. For example, take $X$ an infinite set with the topology $\{\emptyset,X\}$. The only continuous functions are constant ones.


text:
Q: Java Brute Force Password Cracker I am making a brute force password cracker. I am able to use for loops to find which characters match the original password. But the output is not in the correct order. the output is in alphabetical order. How do i fix this?
the output should be something like"
z
ze
zeb
zebr
zebra

Code:
        public static void main(String[] args) {
    String password = "zebra";
    char [] passArr = new char [password.length()];
    passArr = password.toCharArray();

    String brutePass = "";
    char[] alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    boolean solved = false;

    while (solved != true) {
        for (int i = 0; i < alphabet.length; i++) {
            for (int j = 0; j < passArr.length; j++) {
                if (alphabet[i] == passArr[j]) {
                    //brutePass +=passArr[j];
                    //System.out.println(brutePass);

                    StringBuilder forcedPass = new StringBuilder(brutePass);
                    forcedPass.insert(passArr[j], alphabet[i]);
                    System.out.println(forcedPass.toString());
                    solved = true;
                }
            }
        }
    }
}

}

A: Based on your required output, the code should look like below:
public static void main(String[] args) {
    String password = "zebra";
    char [] passArr = password.toCharArray();

    String brutePass = "";
    char[] alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    boolean solved = false;
   StringBuilder forcedPass = new StringBuilder(brutePass); // Initialize StringBuilder outside.
    while (solved != true) {
         for (int j = 0; j < passArr.length; j++) { //Moved for loop outside.
        for (int i = 0; i < alphabet.length; i++) {

                if (alphabet[i] == passArr[j]) {
                    forcedPass.append(passArr[j]); // Used append instead of insert
                    System.out.println(forcedPass.toString());
                    solved = true;
                }
            }
        }
    }
}

Here, I have made two changes, I swop the position of your inner and outer loop and You have used insert() method of StringBuilder class, which is incorrect. You have to use the append() method of it. To find out more about StringBuilder methods,visit this.

A: Move the passArr loop outside.
public static void main(String[] args) {
    String password = "zebra";
    char[] passArr = new char[password.length()];
    passArr = password.toCharArray();

    StringBuilder forcedPass = new StringBuilder();
    char[] alphabet = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    boolean solved = false;

    while (solved != true) {
        for (int j = 0; j < passArr.length; j++) {
            for (int i = 0; i < alphabet.length; i++) {
                if (alphabet[i] == passArr[j]) {
                    forcedPass.append(alphabet[i]);
                    System.out.println(forcedPass.toString());
                    solved = true;
                }
            }
        }
    }
}


text:
Q: Cocos2D Android How to have a scene object? I can get the scene from a layer, but I don't know how to have a Scene that manages layers. I can do this on iPhone, but on Android my code doesn't even get called.
This is in my start Activity:
CCDirector.sharedDirector().runWithScene(EditorScene.node());

This is my scene class:
public class EditorScene extends CCScene
{

public EditorScene()
{

    CanvasBackgroundLayer canvasBackgroundLayer = (CanvasBackgroundLayer) CanvasBackgroundLayer.node();
    CanvasEditorLayer canvasEditorLayer = (CanvasEditorLayer) CanvasEditorLayer.node();

    addChild(canvasBackgroundLayer,0);
    this.addChild(canvasEditorLayer);

}
}

My constructor here is never called.  Any ideas on what to do?

A: Any subclasses of CCScene have to reimplement the static method node(). Have a look at the bottom of CCScene.h.


text:
Q: How to create table in SQL Server 2012 using script file generated from SQL Server 2005? How to use a script file generated from SQL Server 2005 and create the same table in SQL Server 2012?
Plus I have a script file for each table, how could I combine them all to generate my database?

A: Just create a database on SQL Server 2012 and run each create object script.
If some error or warning arises you can work it by demand.
note the tables got dependencies, so it's a good idea to create that tables in the right order.
You also can create the tables and put a no check in the FKs creation snipets and switch all FKs to check once all tables ar in place.
Also it's good to create all tables before creating the views, etc.


text:
Q: remote mysql database connection issue I can connect to a remote database via application server by command line but unable to connect via PHP application.
It gives me Can't connect to MySQL server on *.*.*.* Error.
I added IP in /etc/hosts file, added IP and bind-address in my.cnf in an Application server, create a new user with application IP and flush privileges in database server but nothing works.
is there any packages missing?, I did install MySQL-Client on the application server but no luck.
Thanks in advance.

A: I had a problem to connect to MySQL with the function mysql_connect(...) . After looking around, I figure out that on CentOS there is protection and one of them was blocking the connection.
Ensure that httpd_can_network_connect_db is enable (=on).
getsebool -a | grep httpd_can_network_connect_db

setsebool httpd_can_network_connect_db=on

This could be nice in a Wiki section :)
Hope this help folks with the same issue


text:
Q: Ghostscript converting Postscript to PNG is over-saturated I'm trying to use Ghostscript and/or ImageMagick to convert each page of a Postscript document into PNG images. The problem is that both produce images that are way too saturated (I think that's the right terminology).
Here are the commands I'm trying:
gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -dGraphicsAlphaBits=4 -sOutputFile=page_%02d.png brochure.ps
convert brochure.ps im_page_%02d.png

This is the input Postscript file (brochure.ps from above)
Here's a couple of the output images I'm getting:
Page 1
Page 6
As you can see (especially on the page with the big green map of New Hampshire), the colors of the output PNGs are too bright/saturated. How can I prevent the colors from being changed so much and get a more accurate conversion?
Preview in OS X 10.6 automatically does a very accurate conversion to PNG when you open a Postscript file in it. This leads me to believe there is just something screwy with the way ghostscript converts ps->png (I'm fairly confident ImageMagick is just a wrapper for ghostscript for this operation). Is there a tool besides ghostscript I should be using instead?
Note: As pipitas points out below, the visible difference of colors varies by OS. It is very obvious in OS X 10.6, but apparently not very noticeable in Windows XP.

A: You are right in assuming ImageMagick just being a wrapper for Ghostscript when converting from PostScript or PDF to an image format.
I think, this problem can only be solved to anybody's satisfaction once the efforts to add support for ICC profile handling and color management (currently underway) are completed for Ghostscript (design document as PDF). That point in time is close, however. If I understand recent commits to http://svn.ghostscript.com/trunk/ correctly, the next release (which will be dubbed 9.00 and out hopefully in August) will include support for color management via LittleCMS. Yay!

A: OSX 10.4 and up provide sips (scriptable image processing system) and it works well with PDF format. Perhaps it can be a temporary solution until Ghostscript supports color management.


text:
Q: Write a list containing data frames into excel file using parallel processing Can we write a list containing data frames as excel worksheets in single workbook using parallel processing.
Currently I am doing this using for loop and using xlsx package. But its taking around 2 minutes for 150 sheets.

EDIT- Added my code sample with two data frames in a list

d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
list_df <- list(d1, d2)

for(i in 1: length(list_df)){
  write.xlsx(list_df[[i]], file="sample.xlsx", sheetName=paste0("sheet ", i), append = T, row.names=F, col.names = F )

}

I am trying to optimize time for this using parallel computing. But don't know how to apply it in this case.

A: I have been able to write to a Excel file in parallel with R with the following code :
library(RDCOMClient)
library(parallel)
library(doParallel)
path_Excel_File_Output <- "D:\\test.xlsx"

list_df <- list()

for(i in 1 : 20)
{
  if(i %% 2 == 0)
  {
    list_df[[i]] <- data.frame(y1 = c(1,2,3), y2 = c(4,5,6))

  }else
  {
    list_df[[i]] <- data.frame(y1 = c(3,2,1), y2 = c(6,5,4))
  }
}

nb_CPU <- 10
cluster <- parallel::makeCluster(nb_CPU)
doParallel::registerDoParallel(cl = cluster)

xlApp <- COMCreate("Excel.Application")
xlApp[["Visible"]] <- TRUE
xlWbk <- xlApp$Workbooks()$Open("D:\\test.xlsx")
Sheets <- xlWbk$Sheets()

for(i in 1 : 20)
{
  Sheets$Add()
}

fn_Par <- function(i, list_df)
{
    library(RDCOMClient)
    xlApp <- COMCreate("Excel.Application")
    xlApp[["Visible"]] <- TRUE
    xlWbk <- xlApp$Workbooks()$Open("D:\\test.xlsx")

    Sheets <- xlWbk$Sheets()
    nb_Row <- dim(list_df[[i]])[1]
    nb_Col <- dim(list_df[[i]])[2]
    col_End_Range <- LETTERS[nb_Col]
    row_End_Range <- nb_Row
    range_To_Write <- paste0("A1:", col_End_Range, row_End_Range, collapse = "")
    obj_Range <- Sheets[[i]]$Range(range_To_Write)
    obj_Range[["Value"]] <- asCOMArray(list_df[[i]])
}

parLapply(cluster, X = 1 : 20, fun = fn_Par,  list_df = list_df)

This code writes the 20 data.frame in parallel in the Excel file D:\test.xlsx.


text:
Q: Dynamodb item designed for retrieval We are making an internal collector for the meta data around deploying kube images to clusters and storing in dynamodb (it would keep track of every time a new image tag is deployed in a list). This will be the first time I am working with dynamodb and maybe the 5th time with nosql concepts.
Thinking about rest calls they would like: to get all items by service_name, cluster_name, and image_name. Initially, I did not understand how differently the retrieval work in this database vs relational. I now understand I will be using an anti pattern as I do not plan on using the UUID for any useful searching and would need to make 3 Global Search Indexes that would allow me to make those other retrievals.....is this really the best way to do it?
I feel like I may be missing the mark.
The only other thing I could think of is to see if the users of the system would be fine with always giving me the cluster_name and service_name as a base. Then I could make that a concatenated field and search based on that.
Data I would like to store:
{ "uuid" : "generated_uui",
  "cluster_name" : "cluster",
  "service_name" : "servicename",
  "image_name" : "imagename",
  "image_tags" : [{"date" : "date", "tag" : "imagetag"},
                  {"date" : "date", "tag" : "imagetag"}
                 ]
}

A: Is your problem creating a GSI for every attribute you want it to be queryable? For now,  you have three service_name, cluster_name, and image_name.
If thats the case you can do GSI Overloading, and make use of schemaless advantages of DynamoDB. In short, you can put your queryable attributes in a single attribute (which will be your sort key and also your GSI partition key)
Example 1:
|   PartitionKey  | SortKey and GSI PartionKey |  Atrribute 1 | Atrribute 2 |
|:---------------:|---------------------------:|:------------:|
| generated_uui_1 |        image_tags          |     [{tag: 1}]
| generated_uui_1 | cluster:a_cluster_name_1   |
| generated_uui_1 | service:a_service_name_1   |
| generated_uui_1 | image:a_image_name_1       |
| generated_uui_2 |        image_tags          |     [{tag: 2}]
| generated_uui_2 | cluster:a_cluster_name_2   |
| generated_uui_2 | service:a_service_name_2   |
| generated_uui_2 | image:a_image_name_2       |

Here you can query both 3 attributes in single GSI. But it has to be the exact match of the string you are searching for because its only hash key.
If you want to query for instance clusters with starting 'a_cluster' prefix you can simply modify the upper table to this
Example 2:
|   PartitionKey  | SortKey and GSI PartionKey |  Atrribute 1 (GSI SortKey) | Atrribute 2 |
|:---------------:|---------------------------:|:--------------------------:|
| generated_uui_1 |        image_tags          |     [{tag: 1}]
| generated_uui_1 |        cluster_name        |     a_cluster_name_1
| generated_uui_1 |        service_name        |     a_service_name_1
| generated_uui_1 |        image_name          |     a_image_name_1
| generated_uui_2 |        image_tags          |     [{tag: 2}]
| generated_uui_2 |        cluster_name        |     a_cluster_name_2
| generated_uui_2 |        service_name        |     a_service_name_2
| generated_uui_2 |        image_name          |     a_image_name_2

Now with the advantages of the Sort Key you can query with for instance BEGINS_WITH (and many more capabilities), such as Get me all services that starts with 'a_service_name'
But now it requires extra read if you want to get image_tags of 'a_service_name_1` item. Or you can denormalize it Attribute 1, Attribute 2 so on...


text:
Q: How to not overwritten the data in input/output in ADA programming I need to take the input from user and save the data in a file but data must not be overwritten. The code is running well but data is overwritten. How to correct my code to get desired results?
I could not manage to data to be overwritten. The demand is:"Ask the user to input name, id and CGPA one by one, and then write it in the file. Existing data must not be ". I also have tried the new generated file data to be stored in another file but getting the same result.
with Ada.Command_Line, Ada.Text_IO;
use Ada.Command_Line, Ada.Text_IO;
procedure Main is
   -- Initializing
   Read_From     : constant String := "inputFile.txt";
   Write_To      : constant String := "studentData.txt";
   name          : String (1 .. 13);
   studentID     : String (1 .. 11);
   cgpa          : String (1 .. 4);
   Input, Output : File_Type;
begin
   -- taking inputs
   Put_Line ("My Student ID Is *******bc150400162*******");
   Put_Line ("Enter the details for first student.");
   Put_Line ("Please enter your name:");
   Get (name);
   Put_Line ("Please enter your Student ID:");
   Get (studentID);
   Put_Line ("Please enter your CGPA:");
   Get (cgpa);
   -- opening file
   begin
      Open (File => Input, Mode => In_File, Name => Read_From);
   exception
      when others =>
         Put_Line
           (Standard_Error,
            "Can not open the file '" & Read_From & "'. Does it exist?");
         Set_Exit_Status (Failure);
         return;
   end;
   -- Creating new file file

   begin
      Create (File => Output, Mode => Out_File, Name => Write_To);
   exception
      when others =>
         Put_Line
           (Standard_Error, "Can not create a file named '" & Write_To & "'.");
         Set_Exit_Status (Failure);
         return;
   end;
   -- Here is the loop.............................................
   ------------------
   loop
      declare
         Line : String := Get_Line (Input);
      begin
         Put_Line (Output, Line);
         Put_Line (Output, "The Student details are: ");
         Put_Line (Output, name);
         Put_Line (Output, studentID);
         Put_Line (Output, cgpa);
      end;
   end loop;
exception
   when End_Error =>
      if Is_Open (Input) then
         Close (Input);
      end if;
      if Is_Open (Output) then
         Close (Output);
      end if;
end Main;

A: The standard way to do this is to try to open the file in append mode, and if that fails create it (again, in append mode). If creating the file fails, you have a different problem (e.g. illegal name? no permissions? file system is read-only? file system is full? none of these addressable in your program!)
Note, open first, create if open fails; the other way round, the file may be reset, which is exactly what you don't want.
with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.IO_Exceptions;
procedure Appending is
   Output : Ada.Text_IO.File_Type;
   Name : constant String := "appending.dat";
begin

We need a block here, so the exception can be caught here.
   begin

Try to open the file ...
      Ada.Text_IO.Open (File => Output,
                        Name => Name,
                        Mode => Ada.Text_IO.Append_File);

Open succeeded!
   exception
      when Ada.IO_Exceptions.Name_Error =>

Open failed because the name didn't represent an openable file. Try to create it ...
         Ada.Text_IO.Create (File => Output,
                             Name => Name,
                             Mode => Ada.Text_IO.Append_File);

The file Output is now open, in append mode.
(At first glance, you might wonder what the point of opening a file that must have been empty in append mode is. Normally, of course, it might as well have been opened in standard out mode; the only difference would be if for some reason you had to use the modeless Reset. In that case, if the file was created in append mode it would remain in append mode, so any previous updates wouldn't be lost.)
   end;

Write something 'unique' to it, so we can tell it worked ...
   Ada.Text_IO.Put_Line
     (File => Output,
      Item => Ada.Calendar.Formatting.Image (Ada.Calendar.Clock));

... and we're done. Could leave the OS to close the file for us on exit, but let's be sure.
   Ada.Text_IO.Close (File => Output);
end Appending;


text:
Q: How to make a comment in issue to the top? There are many comments in an issue, and I think one of them is important, so I want to set this comment  to the top of the issue.
Is this possible? How can I get it?

A: Comments are listed in the order that they were made, and this order cannot be adjusted.
You can, however, link to a comment by clicking the three dots on the right of it, then clicking Copy link. Pasting this link into the navbar will take you straight to the individual comment if it is needed as a reference at a later date.
This will work for comments on both issues and pull requests.


text:
Q: Create custom properties at runtime I am trying to create a custom property (like Name, BackgroundImage etc.) for my dynamically created PictureBox called "angle". And use it like that:
PictureBox.angle = 20;
Is there a way to do that? Any help is appreciated.

A: Create a custom component (Right click Project -> Add -> Component). Change it to inherit from PictureBox, and add the property.
using System.ComponentModel;

namespace Playground.WinForms
{
    public partial class MyCustomPictureBox : PictureBox
    {
        public int Angle { get; set; }

        public MyCustomPictureBox()
        {
            InitializeComponent();
        }

        public MyCustomPictureBox(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
    }
}

When you build your WinForms solution, it will appear in your Toolbox, at which point your can drag it onto your form, or create one dynamically as you mentioned above.

A: var v = new { Amount = 108, Message = "Hello" };

// Rest the mouse pointer over v.Amount and v.Message in the following // statement to verify that their inferred types are int and string.
Console.WriteLine(v.Amount + v.Message);

Try use anonynous types
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/anonymous-types


text:
Q: How to execute mysqldump command from the host machine to a mysql docker container I want to create mysql dumps for a database which is running in docker container. However I do not want to get into the container and execute the command but do it from the host machine. Is there a way to do it. I tried few things but probably I am wrong with the commands.
docker exec -d mysql sh mysqldump -uroot -pSomePassword DBName > /dumps/MyNewDump.sql
docker exec -d mysql sh $(mysqldump -uroot -pSomePassword DBName > /dumps/MyNewDump.sql)
docker exec -d mysql mysqldump -uroot -pSomePassword DBName > /dumps/MyNewDump.sql
the dumps directory is already bind to the host machine.
These commands are seems not the right way to do it or probably not the right way to do it at all. These always ends up with an error:

bash: /dumps/MyNewDump.sql: No such file or directory

But if I just run mysqldump -uroot -pSomePassword DBName > /dumps/MyNewDump.sql inside the container it works fine.

A: This worked on my end(just replace the container ID):
docker exec 1d3595c0ce87 sh -c 'mysqldump -uroot -pSomePassword DBName > /dumps/MyNewDump.sql'

mysqldump: [Warning] Using a password on the command line interface can be insecure.

A: mysqldump takes the usual MySQL CLI options to connect to a server running somewhere else.  That means you can run it directly from the host, without needing docker exec (administrator) permissions.
mysqldump -h127.0.0.1 -uroot -pSomePassword DBName > MyNewDump.sql

In contrast to the docker exec forms, this creates the dump file on the host, but that's probably what you want.


text:
Q: Slurping http://foobar.mp3 that redirects to http://fizzbar.mp3 in Clojure I am trying to programatically download mp3 files from this rss feed.
When I open an url such as: http://menlochurch.podbean.com/mf/feed/5gv2gb/170219_jortberg.mp3
it redirects to an url like: http://s62.podbean.com/pb/67f34563539acbe87b9566ecc5738d57/58aeff8e/data4/fs145/948579/uploads/170219_jortberg.mp3
If I curl the first url it downloads an empty file.
If I curl -L the first url it correctly downloads the file.
If I curl the second url it correctly downloads the file.
If I slurp the first url in Clojure it downloads something that looks like an mp3 (is big and has no legible text) but is unplayable and not the same as the output from curl -L.
If I slurp the second url in Clojure it also downloads something that looks like an mp3 (is big and has no legible text) but is unplayable and not the same as the output from curl -L and is identical to the output from the previous slurp.
➜  ~ git:(master) ✗ ls -l *.mp3
-rw-r--r-- 1 adam adam 38038533 Feb 23 08:32 curl-url1.mp3
-rw-r--r-- 1 adam adam 38038533 Feb 23 08:37 curl-url2.mp3
-rw-r--r-- 1 adam adam        0 Feb 23 08:45 curl-without-L.mp3
-rw-r--r-- 1 adam adam 67144297 Feb 23 08:31 slurp-url1.mp3
-rw-r--r-- 1 adam adam 67144297 Feb 23 08:31 slurp-url2.mp3
As you can see whatever I'm slurping, is almost twice as big as what I'm curling.
I don't know what to make of this, am I using slurp in an inappropriate context?  Any advice would be appreciated!

A: slurp is for strings so won't work with binary data.
user=> (doc slurp)
-------------------------
clojure.core/slurp
([f & opts])
  Opens a reader on f and reads all its contents, returning a string.
  See clojure.java.io/reader for a complete list of supported arguments.

A: While slurping binary data is not possible, the following function will do something similar to slurp but accepts binary streams:
(defn copy-uri-to-file [uri file]
  (with-open [in (clojure.java.io/input-stream uri)
              out (clojure.java.io/output-stream file)]
    (clojure.java.io/copy in out)))
For this particular example the mp3 file can be downloaded like this:
(copy-uri-to-file "http://menlochurch.podbean.com/mf/feed/5gv2gb/170219_jortberg.mp3" "foo.mp3")


text:
Q: How to rewrite url in htaccess to make user freindly url I have a site in wordpress in which a page is showing questions based on its ID.
http://example.com/index.php/question/?questionid=9&title='how-to-rewite-htaccess'

I am the beginner to php I'm not able to graps other examples found on stackoverflow.com
Here's my .htaccess code
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteRule ^/question/([^/]*)/([^/]*)/$ /question/?questionid=$1&title=$2 [NC,L]

</IfModule>

But this is not working. please tell where is error.

A: Since your using Wordpress you can turn on permalinks which takes care of the url friendly urls for you see https://codex.wordpress.org/Settings_Permalinks_Screen.
Login to your admin then go to permalinks and set a preferred style.

A: example.com/index.php/question/9/how-to-rewite-htaccess doesn't match your rewrite rule because the rule has a trailing /.  Change the regex (first) part of your rewrite rule to:
^/question/([^/]*)/([^/]*)/?$

Adding ? makes the trailing / optional.

A: Once you go to setting > permalinks and set the pretty links, WordPress will automatically generate .htaccess based on the setting you choose. Don't forget to save.
More information here http://www.wpbeginner.com/beginners-guide/why-you-cant-find-htaccess-file-on-your-wordpress-site/


text:
Q: Entity Framework - how do I update correctly? I get the following error: https://i.imgur.com/d13B1vi.png
My system: on server startup, I load all database accounts into a list Accounts_.
Every 5 minutes I want to update all accounts in the database with updated Accounts_ entries.
So I change for example the level from an entry in Accounts_ and want to sync it to the database. Currently I get the error shown above, but second point is that that update all accounts - but I want to update all that have been changed.
My code: https://i.imgur.com/MYtDXpb.png

A: Code:
internal static async void SaveAllAccounts()
    {
        try
        {
            using (var db = new gtaContext())
            {
                foreach (var accounts in Model.ServerAccounts.Accounts_.ToList())
                {
                    db.Entry(accounts).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                    db.Accounts.Update(accounts);
                }
                await db.SaveChangesAsync();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"{e}");
        }
    }

sometimes "Connection not opened"


text:
Q: Gitblit: Ability to delete branches from the web interface We are migrating our repositories from Stash to Gitblit.
I saw that there should be the possibility in Gitblit to delete branches of a repository in the web interface: https://github.com/gitblit/gitblit/issues/417.
But I cannot find this possibility on the web interface (I am owner of the repository).
Google and the Gitblit documentation could not enlighten me.
Does anybody know about this possibility?
Any hint or advice is appreciated.
Thanks in advance.

A: From the repo summary page click the all branches link.  This will bring you to the repo's branches page.  If you have delete permissions for the repo you should have a delete link for each branch.


text:
Q: Swift 4 Decodable - decoding JSON object into `Data` I have the following data structure:
{
    "type": "foo"
    "data": { /* foo object */ }
}

Here's my class for decoding it:
final public class UntypedObject: Decodable {

    public var data: Data

    enum UntypedObjectKeys: CodingKey {
        case data
    }

    required public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: UntypedObjectKeys.self)

        self.data = try values.decode(Data.self, forKey: .data)
    }
}

I am fetching an array of such objects and this is how I am decoding it:
let decoder = JSONDecoder()
let objectList = try decoder.decode([UntypedObject].self, from: data)

However I am receiving this error in the console:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), Playground_Sources.UntypedObject.UntypedObjectKeys.data], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

So the question would be is it possible at all to decode proper JSON object into a Data typed attribute and if so - how can I achieve this?

A: This is likely too late for the OP, but I had a similar problem that needed a solution.
Hopefully this is useful for others.
For my problem, I wanted to use Decodable to decode my JSON
with Swift 5.1. However at various points in my object hierarchy, I wanted to return an objC object (from a third party library) that did not support Decodable, but did support decoding from a (non-trivial) JSON string. I solved the problem by using JSONSerialization to create an untyped object hierarchy I could retrieve from the decoder's userInfo property and search with the decoder's contextPath to find my data, and then use JSONSerialization to
convert it back to string data.
This solution makes no assumption about the object/array hierarchy required to get to the object that has the "data" key.
// Swift 5.1 Playground
import Foundation

// Input configuration JSON
let jsonStr = """
{
  "foo":"bar",
  "bars": [
    {
      "data":{
        "thing1":"#111100",
        "thing2":12
      }
    },
    {
      "data":{
        "thing1":"#000011",
        "thing2":64.125
      }
    }
  ]
}
"""

// Object passed to the decoder in the UserInfo Dictionary
// This will contain the serialized JSON data for use by
// child objects
struct MyCodingOptions {
  let json: Any

  static let key = CodingUserInfoKey(rawValue: "com.unique.mycodingoptions")!
}

let jsonData = Data(jsonStr.utf8)
let json = try JSONSerialization.jsonObject(with: jsonData)
let options = MyCodingOptions(json: json)

let decoder = JSONDecoder()
decoder.userInfo = [MyCodingOptions.key: options]

// My object hierarchy
struct Root: Decodable {
  let foo: String
  let bars: [Bar]
}

struct Bar: Decodable {
  let data: Data?

  enum CodingKeys: String, CodingKey {
    case data = "data"
  }
}

// Implement a custom decoder for Bar
// Use the context path and the serialized JSON to get the json value
// of "data" and then deserialize it back to data.
extension Bar {
  init(from decoder: Decoder) throws {
    var data: Data? = nil
    if let options = decoder.userInfo[MyCodingOptions.key] as? MyCodingOptions {
      // intialize item to the whole json object, then mutate it down the "path" to Bar
      var item: Any? = options.json
      let path = decoder.codingPath // The path to the current object, does not include self
      for key in path {
        if let intKey = key.intValue {
          //array
          item = (item as? [Any])?[intKey]
        } else {
          //object
          item = (item as? [String:Any])?[key.stringValue]
        }
      }
      // item is now Bar, which is an object (Dictionary)
      let bar = item as? [String:Any]
      let dataKey = CodingKeys.data.rawValue
      if let item = bar?[dataKey] {
        data = try JSONSerialization.data(withJSONObject: item)
      }
    }
    self.init(data: data)
  }
}

if let root = try? decoder.decode(Root.self, from: jsonData) {
  print("foo: \(root.foo)")
  for (i, bar) in root.bars.enumerated() {
    if let data = bar.data {
      print("data #\(i): \(String(decoding: data, as: UTF8.self))")
    }
  }
}

//prints:
// foo: bar
// data #0: {"thing2":12,"thing1":"#111100"}
// data #1: {"thing2":64.125,"thing1":"#000011"}

A: For your error in particular changing
let objectList = try decoder.decode([UntypedObject].self, from: data)

to
let objectList = try decoder.decode(UntypedObject.self, from: data)

would fix it (but I still don't think you'd be able to get the content of the "data" key on the JSON as Data.)
The reason for your error is because your JSON response contains an object as the root which is seen as a dictionary in Swift (because of the key/value mapping) but you were trying to decode an array of objects instead.

A: When you are decoding it, can you check to see if it is an Array first?
Then your code above works if "true",   else decode for a dictionary
Check out this article on decoding that I found helpful:
https://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375


text:
Q: Pandas interprets 'timestamp without timezones' columns as different types I read a table with pandas:
import pandas as pd
import numpy as np
con = psycopg2.connect(...)
mframe = pd.read_sql('''select dt_A, dt_B from (...)''',con)

Both columns (dt_A and dt_B) are of type 'timestamp without timezone' in the database. However, they are read as different types by pandas:
mframe.dt_A.dtype,  mframe.dt_B.dtype

Yields:
(dtype('O'), dtype('<M8[ns]'))

I was able to force both columns to be recognized as
"<M8[ns]"

using the 'parse_dates' parameter, but I'd like to understand what causes this. As far as I've checked, neither column contains any 'Na's (which was my first suspicion). What could case them to be interpreted differently?
Update:
I'm using Pandas version 0.15.1; and I can reproduce the problem using both sqlalchemy and psycopg2 connections.
Update 2: running the original query with a small limit works as I expected - that is, both columns have the same dtype "M8[ns]". Still not sure what kind of entry (something ill-formatted?) is causing this, but I'm satisfied for now.
Update 3: joris got it. See the comments below.

A: As you noted that it works correctly when limiting to some data (with adding LIMIT 5 to your query), it probably has to do with some 'incorrect' values in the dates.
To find out what value is causing the problem, you can read in all data (resulting in the object dtype), and then do the conversion manually with:
pd.to_datetime(column, errors='raise')

The errors='raise' will ensure you get an error message indicating which date cannot be converted.
To ensure that the column is converted to datetime64 values, regardless of invalid values, you should specify the column in the parse_dates kwarg.

It seems that when using read_sql_table, the invalid date will be converted to NaT automatically, while read_sql_query will leave the values as datetime.datetime values. I opened an issue for this inconsistency: https://github.com/pydata/pandas/issues/9261


text:
Q: Why does Travis fail to find rospy when running unit tests? We have unit tests that require rospy (One of the test uses geometry_msgs/Twist).
When we run the unit tests locally, everything is fine.
pytest
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: /home/cedric/Programming/robotics-prototype, inifile: pytest.ini
collected 10 items

tests/unit/branch_name_test.py ......                                    [ 60%]
tests/unit/drive_controls_test.py ..                                     [ 80%]
tests/unit/import_test.py ..                                             [100%]

========================== 10 passed in 2.73 seconds ===========================

When we run it on Travis, it fails. This is because it fails to find rospy. Our Travis setup installs ROS, runs catkin_make successfully, but fails at the unit tests.
The repo is public so if you're interesting in seeing the complete travis logs click here.
os: linux
dist: bionic
language: python
cache:
  - apt
env:
  global:
    - REPO_ROOT=$(pwd)
    - ARDUINO_IDE_VERSION="1.8.12"
    - ARDUINO_PATH="$HOME/arduino-$ARDUINO_IDE_VERSION" # Required for CMake script
    - TEENSYDUINO_VERSION="152"
    - ROS_PYTHON_VERSION="3.6"
    - ROS_VERSION="melodic"
    - OS_VERSION="bionic"

install:
  # Taken from this tutorial https://github.com/newdigate/teensy-blink
  - mkdir -p robot/rover/build
  - mkdir -p ~/Arduino/libraries
  - wget --quiet https://downloads.arduino.cc/arduino-$ARDUINO_IDE_VERSION-linux64.tar.xz
  - tar xf arduino-$ARDUINO_IDE_VERSION-linux64.tar.xz -C /home/$USER/
  - curl -fsSL https://www.pjrc.com/teensy/td_$TEENSYDUINO_VERSION/TeensyduinoInstall.linux64 -o TeensyduinoInstall.linux64
  - chmod +x TeensyduinoInstall.linux64
  - /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16
  - sleep 3
  - export DISPLAY=:1.0
  - ./TeensyduinoInstall.linux64 --dir=$ARDUINO_PATH

  # Install pip dependencies and setup robot python package
  - pip install -r requirements.txt -r requirements-dev.txt
  - pip install -e .

  # Install ros-base and necessary packages
  - sudo sh -c "echo \"deb http://packages.ros.org/ros/ubuntu $OS_VERSION main\" > /etc/apt/sources.list.d/ros-latest.list"
  - sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
  - sudo apt update -q
  - sudo apt install -y ros-$ROS_VERSION-ros-base ros-$ROS_VERSION-cv-camera ros-$ROS_VERSION-web-video-server
  - sudo apt install -y python-rosdep python-wstool

  # Install ros package dependencies
  - cd $REPO_ROOT/robot/rospackages
  - sudo rosdep init
  - rosdep update
  - rosdep install -y -r --from-paths src --ignore-src --rosdistro $ROS_VERSION

script:
  # Set up 'robot' python module and test python installation
  - cd $REPO_ROOT
  - python setup.py develop
  - pytest --continue-on-collection-errors

  # Set up and initialize catkin workspace for ros packages
  - cd $REPO_ROOT/robot/rospackages
  - source /opt/ros/$ROS_VERSION/setup.bash
  - catkin_make

  # Allow to compile arduino code in external IDEs or something
  - cd $REPO_ROOT/robot/rover/build
  - cmake ..
  - make

notifications:
  email:
    recipients:
      - (hidden for the purpose of the question)
    on_success: change
    on_failure: change

python:
  - "3.6"

git:
  submodules: true

A: It seems that you are calling the test before sourcing your ROS environment. You need change that around:
script:
  # Set up and initialize catkin workspace for ros packages
  - cd $REPO_ROOT/robot/rospackages
  - source /opt/ros/$ROS_VERSION/setup.bash
  - catkin_make

  # Set up 'robot' python module and test python installation
  - cd $REPO_ROOT
  - python setup.py develop
  - pytest --continue-on-collection-errors


text:
Q: Starting a dialog from conversationUpdate event in Node.js BotBuilder I want to show the message and call a dialog when chatbot initialize. The below code shows the message. But, can not call a dialog.
bot.on('conversationUpdate', function (activity) {
// when user joins conversation, send welcome message
if (activity.membersAdded) {
    activity.membersAdded.forEach(function (identity) {
        if (identity.id === activity.address.bot.id) {
            var reply = new builder.Message()
                .address(activity.address)
                .text("Hi, Welcome ");
            bot.send(reply);
            // bot.beginDialog("initialize", '/');
            // session.beginDialog("initialize");
        }
    });
}});bot.dialog('/', intents);

Below is the code for dialog. I need to call below dialog when chatbot begins
bot.dialog('initialize', [
function (session, args, next) {
  builder.Prompts.choice(session, "Do you have account?", "Yes|No", { listStyle: builder.ListStyle.button });
}, function (session, args, next) {
    if (args.response.entity.toLowerCase() === 'yes') {
        //session.beginDialog("lousyspeed");
        session.send("No pressed");
    } else if (args.response.entity.toLowerCase() === 'no') {
        session.send("Yes pressed");
        session.endConversation();
    }
}]).endConversationAction("stop",
"",
{
    matches: /^cancel$|^goodbye$|^exit|^stop|^close/i
    // confirmPrompt: "This will cancel your order. Are you sure?"
});

I tried below methods. But it is not working
        1. bot.beginDialog("initialize", '/');
        2. session.beginDialog("initialize");

A: You are hitting this error because, although they have the same method name, the method signatures differ between session.beginDialog() and <UniversalBot>bot.beginDialog().
This can be a bit confusing since the first argument to session.beginDialog() is the dialogId, but when using bot.beginDialog() the first argument is the address, and the second param is the dialogId.
To solve this, call bot.beginDialog() with the correct input parameters as described in the SDK reference documentation - Eg. bot.beginDialog(activity.address, dialogId);
https://docs.botframework.com/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot.html#begindialog
You can also see the full method signature in the botbuilder.d TypeScript definition file here:
/**
 * Proactively starts a new dialog with the user. Any current conversation between the bot and user will be replaced with a new dialog stack.
 * @param address Address of the user to start a new conversation with. This should be saved during a previous conversation with the user. Any existing conversation or dialog will be immediately terminated.
 * @param dialogId ID of the dialog to begin.
 * @param dialogArgs (Optional) arguments to pass to dialog.
 * @param done (Optional) function to invoke once the operation is completed.
 */
beginDialog(address: IAddress, dialogId: string, dialogArgs?: any, done?: (err: Error) => void): void;

A: I fixed my problem by using single line code
bot.beginDialog(activity.address, 'initialize');


text:
Q: VS code newline adding tab instead of spaces I am having trouble finding a setting for new line spaces in VS code. Currently, I have it set up to a tab is the size of 8 spaces (after detecting indentation from content). This is because a principal software engineer edits in a different program, and set tabs to be 8 spaces, but code inside brackets were only indented 4 spaces.
Is there a way to set new lines following a bracket opening to tab only 4 spaces, but keep the rest of my tabs set to 8 spaces?
I've tried resetting tabs to only 4 spaces, but that changes the document as a whole and the indentation is off.
For example, when tabs are set to 8 (after detecting indentation from content), this is what it looks like (I added a comment to show where hitting a new line brings the cursor to):
if ((access(LOGFILE, F_OK)) != -1)
    {
        if(remove(LOGFILE) == -1) // Remove the older file
    {
            //this is where the newline starts
        printf("Unable to delete the older log file.\n");
        return ERROR;
    }
}

Whereas, when I set tabs to 4, this is what it looks like (if statement indentation is bad):
if ((access(LOGFILE, F_OK)) != -1)
{
    if(remove(LOGFILE) == -1) // Remove the older file
{
    //this is where the newline starts
    printf("Unable to delete the older log file.\n");
    return ERROR;
}
}

Is there a way to change it so I can use the 8 tab format (first example), but when a new line is created after an if statement, it'll only add 4 spaces? Normally. I would just reformat the whole file with a formatter and select those options, but that would make looking at changes when pushing to git nearly impossible, plus the other software engineer still uses the tab 8, spaces 4 system to edit.
Any help is appreciated!

A: Indentation is same in whole file,
you cant use two saperate indentation at once
simple solution will be: set your tabs to 4 spaces and use tabs 1 and 2 times whenever needed.
For reference: Indentation | VS Code Docs


text:
Q: using access token issued from Google & facebook in backend web API I'm creating a Xamarin mobile app which uses a Resources backend ASP core Restful Web API and an "Identity server 4" for issuing JWT Tokens. And I'm OK with it until now.
Now I want to add social login options to my app. So the user will be able to login with his Google or Facebook account and the app receives a access token. Then the app must send the access token to Resources backend. Then Resources backend checks Access token for validation and returns list of resource items requested by user.
My question is that how the backend Resource should know that the token is issued from google or Facebook to check its validation based on secret and ClientId?
Diagram of what I'm tying to do
If access token is issued from Google {check validity of access token based on OAuth credentials obtained from google}
Else If is issued from Facebook {check validity based on OAuth credentials obtained from Facebook}
Else If is issued from Identity Sever 4 {check validity based on OAuth credentials obtained from Identity Sever 4}.
Is this the solution?
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = "http://localhost:1941",
                RequireHttpsMetadata = false,
                EnableCaching = true,
                ScopeName = "api1",
                ScopeSecret = "secret",
                AutomaticAuthenticate = true
            });
app.UseGoogleAuthentication(new GoogleOptions
            {
                ClientId = "[YOUR APP CLIENT ID]",
                ClientSecret = "[YOUR APP SECRET]"
            });
app.UseFacebookAuthentication(new FacebookOptions
            {
                ClientId = "[YOUR APP CLIENT ID]",
               ClientSecret = "[YOUR APP SECRET]"
            });


text:
Q: How to show the number of rows of the result in SQL Server Management Studio? In my SQL Server Management Studio the number of rows of the result in the bottom bar has disappeared. In the image attached is the red circle
I have been looking for the configuration of the bar but I haven't found it. How can I show it again?
Thanks

A: You can do it by modifying Options


text:
Q: Tools for checking correctness of algebraic operations? I have many cases for which this question is relevant but one case would be the following. Are there any computer-aided tools for checking the correctness of expanding algebraic expressions such as
$$
\begin{align}
    (\mathbf{Xw}-\mathbf{t})^T(\mathbf{Xw}-\mathbf{t}) &= ((\mathbf{Xw})^T-\mathbf{t}^T)(\mathbf{Xw}-\mathbf{t})\\
    &= (\mathbf{Xw})^T\mathbf{Xw} - (\mathbf{Xw})^T\mathbf{t} - \mathbf{t}^T\mathbf{Xw} + \mathbf{t}^T\mathbf{t}\\
    &= \mathbf{w}^T\mathbf{X}^T\mathbf{Xw}-\mathbf{w}^T\mathbf{X}^T\mathbf{t} - \mathbf{t}^T\mathbf{Xw} + \mathbf{t}^T\mathbf{t}
    %\mathbf{w}^T\mathbf{X}^T
\end{align}
$$


text:
Q: Set Action on Local Notification in iphone SDK In my app, i scheduled Local Notification on my first view Controller. It works fine.
To set the action on "View" button my code is as below:
//AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *localNotif =
    [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif)
    {
// did something Here when app launch by View button of notification
// added row in Db
}
    return YES;
}

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{

    // Handle the notificaton when the app is running
    NSLog(@"Recieved Notification %@",notif);

    app.applicationIconBadgeNumber=notif.applicationIconBadgeNumber++;
}

Question:  It works fine for the first time only.
But for the second time, the notification is showing but the row is not added in my DB
// Edited
I want to give some action when user presses the button "View".
How can I identify that action?
edited
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{

    // Handle the notificaton when the app is running
    NSLog(@"Recieved Notification %@",notif);

    app.applicationIconBadgeNumber=notif.applicationIconBadgeNumber++;

    UIApplicationState state = [app applicationState];
    if (state == UIApplicationStateInactive) {
        // Application was in the background when notification
        // was delivered.

        [self localNotif];

    }

}

- (void) localNotif
{

    [self databaseOpen];
    NSString *maxIdPt = [NSString stringWithFormat:@"select Max(id) from Points"];
    NSLog(@"Max id from points table %@",maxIdPt);
    NSMutableArray *p1 = [[NSMutableArray alloc]init];
    p1 = [[[database executeQuery:maxIdPt]mutableCopy]retain];

    int p=[[[p1 objectAtIndex:0]valueForKey:@"Max(id)"]intValue];
    NSLog(@"%d",p);

    NSString *maxPt = [NSString stringWithFormat:@"select Points from Points where id = %d",p];
    NSLog(@"Maxp %@",maxPt);
    NSMutableArray * p2 = [[NSMutableArray alloc]init];
    p2 =[[[database executeQuery:maxPt]mutableCopy]retain];

    int k = [[[p2 objectAtIndex:0]valueForKey:@"Points"]intValue];
    NSLog(@"Points %d",k);

    k = k + 250;

    NSLog(@"%d",k);

    NSString *mtpoints = [NSString stringWithFormat:@"insert into Points(Points) values (%d)",k];
    NSLog(@" lbl Points are %@",mtpoints);
    NSMutableArray * m1 = [[NSMutableArray alloc]init];
    m1 = [[[database executeQuery:mtpoints]mutableCopy]retain];
    [database close];

}

The same method i called in application didFinishLaunchingWithOptions
First time the score is updated but second time it doesn't. Even the notification is not shown.

A: Probably the second time the didFinishLaunchingWithOptions function is not called when the user presses the button in the notification, as the app is already running in the background (as opposed to being started from the not-running state).
You also have to handle the function call to
(void)application:(UIApplication *)application
        didReceiveLocalNotification:(UILocalNotification *)notification {
// do your db update here, too ...
}

in order to cover situations where your app is already running in the background.
EDIT:
To see whether the app was started or was already running (= user pressed "View" on notification versus app is running in foreground), check the APplication state:
UIApplicationState state = [application applicationState];
  if (state == UIApplicationStateInactive) {
    // Application was in the background when notification
    // was delivered.
  }

Credits to Use Your Loaf - Adding Local Notifications With iOS 4.

A:     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {

        sk = [[SKDatabase alloc] init];
        NSString *db = @"MindEditor.db";
        [sk initWithDynamicFile:db];
        userid=@"0";
    }

   SKDatabase.h

//
//  SKDatabase.h
//  Version 1.1
//
//  Created by Shannon Appelcline on 9/11/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <sqlite3.h>

@protocol SKDatabaseDelegate <NSObject>
@optional
- (void)databaseTableWasUpdated:(NSString *)table;
@end

@interface SKDatabase : NSObject {

    id<SKDatabaseDelegate> delegate;
    sqlite3 *dbh;
    BOOL dynamic;
}

@property (assign) id<SKDatabaseDelegate> delegate;
@property sqlite3 *dbh;
@property BOOL dynamic;

- (id)initWithFile:(NSString *)dbFile;
- (id)initWithDynamicFile:(NSString *)dbFile;
- (void)close;

- (sqlite3_stmt *)prepare:(NSString *)sql;

- (id)lookupColForSQL:(NSString *)sql;
- (NSDictionary *)lookupRowForSQL:(NSString *)sql;
- (NSArray *)lookupAllForSQL:(NSString *)sql;

- (int)lookupCountWhere:(NSString *)where forTable:(NSString *)table;
- (int)lookupMax:(NSString *)key Where:(NSString *)where forTable:(NSString *)table;
- (int)lookupSum:(NSString *)key Where:(NSString *)where forTable:(NSString *)table;

- (void)insertArray:(NSArray *)dbData forTable:(NSString *)table;
- (void)insertDictionary:(NSDictionary *)dbData forTable:(NSString *)table;

- (void)updateArray:(NSArray *)dbData forTable:(NSString *)table;
- (void)updateArray:(NSArray *)dbData forTable:(NSString *)table where:(NSString *)where;
- (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table;
- (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table where:(NSString *)where;
- (void)updateSQL:(NSString *)sql forTable:(NSString *)table;

- (void)deleteWhere:(NSString *)where forTable:(NSString *)table;

- (BOOL)runDynamicSQL:(NSString *)sql forTable:(NSString *)table;

@end

   SKDatabase.m

//
//  SKDatabase.m
//  Version 1.1
//
//  Created by Shannon Appelcline on 9/11/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "SKDatabase.h"

@implementation SKDatabase

@synthesize delegate;
@synthesize dbh;
@synthesize dynamic;

// Two ways to init: one if you're just SELECTing from a database, one if you're UPDATing
// and or INSERTing

- (id)initWithFile:(NSString *)dbFile {
    if (self = [super init]) {

        NSString *paths = [[NSBundle mainBundle] resourcePath];
        NSString *path = [paths stringByAppendingPathComponent:dbFile];

        int result = sqlite3_open([path UTF8String], &dbh);
        NSAssert1(SQLITE_OK == result, NSLocalizedStringFromTable(@"Unable to open the sqlite database (%@).", @"Database", @""), [NSString stringWithUTF8String:sqlite3_errmsg(dbh)]);
        self.dynamic = NO;
    }

    return self;
}

- (id)initWithDynamicFile:(NSString *)dbFile {
    if (self = [super init]) {

        NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [docPaths objectAtIndex:0];
        NSString *docPath = [docDir stringByAppendingPathComponent:dbFile];

        NSFileManager *fileManager = [NSFileManager defaultManager];

        if (![fileManager fileExistsAtPath:docPath]) {

            NSString *origPaths = [[NSBundle mainBundle] resourcePath];
            NSString *origPath = [origPaths stringByAppendingPathComponent:dbFile];

            NSError *error;
            int success = [fileManager copyItemAtPath:origPath toPath:docPath error:&error];
            NSAssert1(success,[NSString stringWithString:@"Failed to copy database into dynamic location"],error);
        }
        int result = sqlite3_open([docPath UTF8String], &dbh);
        NSAssert1(SQLITE_OK == result, NSLocalizedStringFromTable(@"Unable to open the sqlite database (%@).", @"Database", @""), [NSString stringWithUTF8String:sqlite3_errmsg(dbh)]);
        self.dynamic = YES;
    }

    return self;
}

// Users should never need to call prepare

- (sqlite3_stmt *)prepare:(NSString *)sql {

    const char *utfsql = [sql UTF8String];

    sqlite3_stmt *statement;

    if (sqlite3_prepare([self dbh],utfsql,-1,&statement,NULL) == SQLITE_OK) {
        return statement;
    } else {
        return 0;
    }
}

// Three ways to lookup results: for a variable number of responses, for a full row
// of responses, or for a singular bit of data

- (NSArray *)lookupAllForSQL:(NSString *)sql {
    sqlite3_stmt *statement;
    id result;
    NSMutableArray *thisArray = [NSMutableArray arrayWithCapacity:4];
    if (statement = [self prepare:sql]) {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSMutableDictionary *thisDict = [NSMutableDictionary dictionaryWithCapacity:4];
            for (int i = 0 ; i < sqlite3_column_count(statement) ; i++)
            {
                if (sqlite3_column_decltype(statement,i) != NULL &&
                    strcasecmp(sqlite3_column_decltype(statement,i),"Boolean") == 0)
                {
                    result = [NSNumber numberWithBool:(BOOL)sqlite3_column_int(statement,i)];
                }
                else if (sqlite3_column_type(statement, i) == SQLITE_TEXT)
                {
                    result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                }
                else if
                    (sqlite3_column_type(statement,i) == SQLITE_INTEGER)
                {
                    result = [NSNumber numberWithInt:(int)sqlite3_column_int(statement,i)];
                }
                else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT)
                {
                    result = [NSNumber numberWithFloat:(float)sqlite3_column_double(statement,i)];
                }
                else
                {
                    result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                }
                if (result)
                {
                    [thisDict setObject:result
                                 forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];
                }
            }
            [thisArray addObject:[NSDictionary dictionaryWithDictionary:thisDict]];
            [thisArray retain];
        }
    }
    sqlite3_finalize(statement);
    return thisArray;
}

- (NSDictionary *)lookupRowForSQL:(NSString *)sql {
    sqlite3_stmt *statement;
    id result;
    NSMutableDictionary *thisDict = [NSMutableDictionary dictionaryWithCapacity:4];
    if (statement = [self prepare:sql])
    {
        if (sqlite3_step(statement) == SQLITE_ROW)
        {
            for (int i = 0 ; i < sqlite3_column_count(statement) ; i++)
            {
                if (strcasecmp(sqlite3_column_decltype(statement,i),"Boolean") == 0)
                {
                    result = [NSNumber numberWithBool:(BOOL)sqlite3_column_int(statement,i)];
                }
                else if (sqlite3_column_type(statement, i) == SQLITE_TEXT)
                {
                    result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                }
                else if (sqlite3_column_type(statement,i) == SQLITE_INTEGER)
                {
                    result = [NSNumber numberWithInt:(int)sqlite3_column_int(statement,i)];
                }
                else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT)
                {
                    result = [NSNumber numberWithFloat:(float)sqlite3_column_double(statement,i)];
                }
                else
                {
                    result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                }
                if (result)
                {
                    [thisDict setObject:result
                                 forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];
                }
            }
        }
    }
    sqlite3_finalize(statement);
    return thisDict;
}

- (id)lookupColForSQL:(NSString *)sql {

    sqlite3_stmt *statement;
    id result;
    if (statement = [self prepare:sql]) {
        if (sqlite3_step(statement) == SQLITE_ROW) {
            if (strcasecmp(sqlite3_column_decltype(statement,0),"Boolean") == 0) {
                result = [NSNumber numberWithBool:(BOOL)sqlite3_column_int(statement,0)];
            } else if (sqlite3_column_type(statement, 0) == SQLITE_TEXT) {
                result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)];
            } else if (sqlite3_column_type(statement,0) == SQLITE_INTEGER) {
                result = [NSNumber numberWithInt:(int)sqlite3_column_int(statement,0)];
            } else if (sqlite3_column_type(statement,0) == SQLITE_FLOAT) {
                result = [NSNumber numberWithDouble:(double)sqlite3_column_double(statement,0)];
            } else {
                result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)];
            }
        }
    }
    sqlite3_finalize(statement);
    return result;

}

// Simple use of COUNTS, MAX, etc.

- (int)lookupCountWhere:(NSString *)where forTable:(NSString *)table {

    int tableCount = 0;
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE %@",
                     table,where];
    sqlite3_stmt *statement;

    if (statement = [self prepare:sql]) {
        if (sqlite3_step(statement) == SQLITE_ROW) {
            tableCount = sqlite3_column_int(statement,0);
        }
    }
    sqlite3_finalize(statement);
    return tableCount;

}

- (int)lookupMax:(NSString *)key Where:(NSString *)where forTable:(NSString *)table {

    int tableMax = 0;
    NSString *sql = [NSString stringWithFormat:@"SELECT MAX(%@) FROM %@ WHERE %@",
                     key,table,where];
    sqlite3_stmt *statement;
    if (statement = [self prepare:sql]) {
        if (sqlite3_step(statement) == SQLITE_ROW) {
            tableMax = sqlite3_column_int(statement,0);
        }
    }
    sqlite3_finalize(statement);
    return tableMax;

}

- (int)lookupSum:(NSString *)key Where:(NSString *)where forTable:(NSString *)table {

    int tableSum = 0;
    NSString *sql = [NSString stringWithFormat:@"SELECT SUM(%@) FROM %@ WHERE %@",
                     key,table,where];
    sqlite3_stmt *statement;
    if (statement = [self prepare:sql]) {
        if (sqlite3_step(statement) == SQLITE_ROW) {
            tableSum = sqlite3_column_int(statement,0);
        }
    }
    sqlite3_finalize(statement);
    return tableSum;

}

// INSERTing and UPDATing

- (void)insertArray:(NSArray *)dbData forTable:(NSString *)table {

//  NSMutableString *sql = [NSMutableString stringWithCapacity:16];
//  [sql appendFormat:@"INSERT INTO %@ (",table];
//
//
//  for (int i = 0 ; i < [dbData count] ; i++) {
//      NSLog(@"%@",[[dbData objectAtIndex:i] objectForKey:@"mid"]);
//      [sql appendFormat:@"%@",[[dbData objectAtIndex:i] objectForKey:@"key"]];
//      if (i + 1 < [dbData count]) {
//          [sql appendFormat:@", "];
//      }
//  }
//  [sql appendFormat:@") VALUES("];
//  for (int i = 0 ; i < [dbData count] ; i++) {
//      if ([[[dbData objectAtIndex:i] objectForKey:@"value"] intValue]) {
//          [sql appendFormat:@"%@",[[[dbData objectAtIndex:i] objectForKey:@"value"] intValue]];
//      } else {
//          [sql appendFormat:@"'%@'",[[dbData objectAtIndex:i] objectForKey:@"value"]];
//      }
//      if (i + 1 < [dbData count]) {
//          [sql appendFormat:@", "];
//      }
//  }
//  [sql appendFormat:@")"];
//  [self runDynamicSQL:sql forTable:table];
    for(int i=0;i<[dbData count];i++)
    {
        NSDictionary *dict=[dbData objectAtIndex:i];
        NSMutableString *sql = [NSMutableString stringWithCapacity:16];
        [sql appendFormat:@"INSERT INTO %@ (",table];

        NSArray *dataKeys = [dict allKeys];
        for (int i = 0 ; i < [dataKeys count] ; i++) {
            [sql appendFormat:@"%@",[dataKeys objectAtIndex:i]];
            if (i + 1 < [dataKeys count]) {
                [sql appendFormat:@", "];
            }
        }

        [sql appendFormat:@") VALUES("];
        for (int i = 0 ; i < [dataKeys count] ; i++) {
            if ([[dict objectForKey:[dataKeys objectAtIndex:i]] intValue]) {
                [sql appendFormat:@"%@",[dict objectForKey:[dataKeys objectAtIndex:i]]];
            } else {
                [sql appendFormat:@"'%@'",[dict objectForKey:[dataKeys objectAtIndex:i]]];
            }
            if (i + 1 < [dict count]) {
                [sql appendFormat:@", "];
            }
        }

        [sql appendFormat:@")"];
        [self runDynamicSQL:sql forTable:table];
    }
}

- (void)insertDictionary:(NSDictionary *)dbData forTable:(NSString *)table {

    NSMutableString *sql = [NSMutableString stringWithCapacity:16];
    [sql appendFormat:@"INSERT INTO %@ (",table];

    NSArray *dataKeys = [dbData allKeys];
    for (int i = 0 ; i < [dataKeys count] ; i++) {
        [sql appendFormat:@"%@",[dataKeys objectAtIndex:i]];
        if (i + 1 < [dbData count]) {
            [sql appendFormat:@", "];
        }
    }

    [sql appendFormat:@") VALUES("];
    for (int i = 0 ; i < [dataKeys count] ; i++) {
        //if ([[dbData objectForKey:[dataKeys objectAtIndex:i]] intValue]) {
//          [sql appendFormat:@"%@",[dbData objectForKey:[dataKeys objectAtIndex:i]]];
//      } else {

        [sql appendFormat:@"'%@'",[dbData objectForKey:[dataKeys objectAtIndex:i]]];
        //}
        if (i + 1 < [dbData count]) {
            [sql appendFormat:@", "];
        }
    }

    [sql appendFormat:@")"];
    [self runDynamicSQL:sql forTable:table];
}

- (void)updateArray:(NSArray *)dbData forTable:(NSString *)table {
    [self updateArray:dbData forTable:table where:NULL];
}

- (void)updateArray:(NSArray *)dbData forTable:(NSString *)table where:(NSString *)where {

    NSMutableString *sql = [NSMutableString stringWithCapacity:16];
    [sql appendFormat:@"UPDATE %@ SET ",table];

    for (int i = 0 ; i < [dbData count] ; i++) {
        if ([[[dbData objectAtIndex:i] objectForKey:@"value"] intValue]) {
            [sql appendFormat:@"%@=%@",
             [[dbData objectAtIndex:i] objectForKey:@"key"],
             [[dbData objectAtIndex:i] objectForKey:@"value"]];
        } else {
            [sql appendFormat:@"%@='%@'",
             [[dbData objectAtIndex:i] objectForKey:@"key"],
             [[dbData objectAtIndex:i] objectForKey:@"value"]];
        }
        if (i + 1 < [dbData count]) {
            [sql appendFormat:@", "];
        }
    }
    if (where != NULL) {
        [sql appendFormat:@" WHERE %@",where];
    } else {
        [sql appendFormat:@" WHERE 1",where];
    }
    [self runDynamicSQL:sql forTable:table];
}

- (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table {
    [self updateDictionary:dbData forTable:table where:NULL];
}

- (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table where:(NSString *)where {

    NSMutableString *sql = [NSMutableString stringWithCapacity:16];
    [sql appendFormat:@"UPDATE %@ SET ",table];

    NSArray *dataKeys = [dbData allKeys];
    for (int i = 0 ; i < [dataKeys count] ; i++) {
        if ([[dbData objectForKey:[dataKeys objectAtIndex:i]] intValue]) {
            [sql appendFormat:@"%@=%@",
             [dataKeys objectAtIndex:i],
             [dbData objectForKey:[dataKeys objectAtIndex:i]]];
        } else {
            [sql appendFormat:@"%@='%@'",
             [dataKeys objectAtIndex:i],
             [dbData objectForKey:[dataKeys objectAtIndex:i]]];
        }
        if (i + 1 < [dbData count]) {
            [sql appendFormat:@", "];
        }
    }
    if (where != NULL) {
        [sql appendFormat:@" WHERE %@",where];
    }
    [self runDynamicSQL:sql forTable:table];
}

- (void)updateSQL:(NSString *)sql forTable:(NSString *)table {
    [self runDynamicSQL:sql forTable:table];
}

- (void)deleteWhere:(NSString *)where forTable:(NSString *)table {

    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@",
                     table,where];
    [self runDynamicSQL:sql forTable:table];
}

// INSERT/UPDATE/DELETE Subroutines

- (BOOL)runDynamicSQL:(NSString *)sql forTable:(NSString *)table {

    int result;
    //NSAssert1(self.dynamic == 1,[NSString stringWithString:@"Tried to use a dynamic function on a static database"],NULL);
    sqlite3_stmt *statement;
    if (statement = [self prepare:sql]) {
        result = sqlite3_step(statement);
    }
    sqlite3_finalize(statement);
    if (result) {
        if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(databaseTableWasUpdated:)]) {
            [delegate databaseTableWasUpdated:table];
        }
        return YES;
    } else {
        return NO;
    }

}

// requirements for closing things down

- (void)dealloc {
    [self close];
    [delegate release];
    [super dealloc];
}

- (void)close {

    if (dbh) {
        sqlite3_close(dbh);
    }
}

@end


text:
Q: Mutliple CSV files through AWS S3 I am new at AWS and looking for example code. My problem is the following. I loaded a zipped file in my S3 bucket which contains several CSV files with different column names.
I would like with the use of my AWS Lambda handler (in Python) is to:

*

*Unzip each file

*Turn each file to panda dataframe

*Iterate over each for data cleaning

*Then concat merge them into a final data frame.

On my local system I did all this with no problem. The problem is that it did not work on Lambda.
If any examples where they have seen at list step one and two done. That would be helpful. I have seen examples online for one CSV file, but not for a zipped file containing multiple CSVs in it.
Thank you in advance.


text:
Q: Easiest way to instantiate a transceiver in Quartus to avoid unused channel degradation This answer in the altera knowledge base indicates that the TX channels on the Arria 10 degrade over time if left unused. I have added the recommended assignment to my QSF file, but it has no effect if I don't already use some transceivers:
Warning(18584): There are no transceiver channels used in the design. You must use or instantiate at least 1 transceiver channel to preserve the rest of the unused channels.

I'm just trying out some very simple examples to start with and am trying to find my way around Quartus. How can I instantiate a transceiver with minimum fuss so I don't ruin the boards?

A: It seems that adding an IOPLL counts, even though the number of unused channels stays the same:
iopll iopll_i (
  .locked(),
  .refclk(FPGA_CLK2K_P),
  .rst(~A10_RST_L),
  .outclk_0(clk)
);

Routing the reference clock through an IOPLL with multiply/divide settings of 1/1 does not change the clock frequency but allows the transceiver preservation settings to take effect.


text:
Q: error trying to migrate test environment database in rails, possibly devise? I am trying to run a migration on my test db and i get this error. I can create it and drop it but not migrate it.
undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x007fccae8e1bb0>/Users/McGroarty/projects/gll/db/migrate/20111105225808_devise_create_users.rb:4:in `block in up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:160:in `create_table'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:434:in `create_table'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:466:in `block in method_missing'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:438:in `block in say_with_time'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:438:in `say_with_time'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:458:in `method_missing'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:334:in `method_missing'
/Users/McGroarty/projects/gll/db/migrate/20111105225808_devise_create_users.rb:3:in `up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:370:in `up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:410:in `block (2 levels) in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:410:in `block in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:129:in `with_connection'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:389:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:528:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:720:in `block (2 levels) in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:777:in `call'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:777:in `ddl_transaction'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:719:in `block in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:700:in `each'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:700:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:570:in `up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:551:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/railties/databases.rake:193:in `block (2 levels) in <top (required)>'
NoMethodError: undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x007fccae8e1bb0>
/Users/McGroarty/projects/gll/db/migrate/20111105225808_devise_create_users.rb:4:in `block in up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:160:in `create_table'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:434:in `create_table'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:466:in `block in method_missing'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:438:in `block in say_with_time'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:438:in `say_with_time'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:458:in `method_missing'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:334:in `method_missing'
/Users/McGroarty/projects/gll/db/migrate/20111105225808_devise_create_users.rb:3:in `up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:370:in `up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:410:in `block (2 levels) in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:410:in `block in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:129:in `with_connection'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:389:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:528:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:720:in `block (2 levels) in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:777:in `call'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:777:in `ddl_transaction'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:719:in `block in migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:700:in `each'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:700:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:570:in `up'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/migration.rb:551:in `migrate'
/Users/McGroarty/.rvm/gems/ruby-2.1.2/gems/activerecord-3.2.15/lib/active_record/railties/databases.rake:193:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Here is my Gemfile
gem 'active_link_to'
gem 'acts_as_list'
gem 'acts_as_tree'
gem "airbrake"
gem 'ancestry' #rails g migration add_ancestry_to_things ancestry:string
gem "annotate", "~> 2.6.1", group: [:development]
gem "arel"
gem 'autotest-rails', group: [:development,:test]
gem 'aws-s3'
gem 'binding_of_caller', group: :development
gem 'bootstrap-sass', '~>2.0.1'
gem "breadcrumbs"
gem 'cache_digests'
gem 'cancan'
gem 'capistrano'
gem 'capistrano-ext'
gem "capybara", :git=>"https://github.com/jnicklas/capybara.git", group: [:development,:test]
gem 'carrierwave' #rails g uploader YOURMODEL
gem 'chronic'
gem 'cityhash'
gem 'colorize', group: [:development, :test]
gem 'coveralls', require: false, group: [:development,:test]
gem 'cucumber', "<= 1.3.1", group: [:development,:test]
gem "cucumber-rails", require: false, group: [:development,:test]
gem "coffee-rails","~>3.2.1"
gem 'coffee-script'
gem "compass", "~> 0.12.3"
gem "compass-rails"
gem "csv_builder"
gem 'dalli'
gem 'database_cleaner', group: [:development,:test]
gem 'decent_exposure'
gem 'devise' #rails g devise:install && rails g devise MODEL
gem 'execjs'
gem "factory_girl_rails", ">= 1.0.0"
gem "factory_girl_generator", ">= 0.0.1"
gem 'fastercsv'
gem 'ffi', group: [:development,:test]
gem 'faker'
gem 'fog'
gem "friendly_id", '~> 4.0'
gem 'geokit',"1.6.7"
gem 'gmaps4rails', "1.4.5"
gem 'guard-jasmine', group: [:development,:test]
gem 'guard-spork', group: [:development,:test]
gem 'haml'
gem 'haml-rails'
gem 'identity_cache'
gem 'jasmine', group: [:development,:test]
gem 'jasminerice', group: [:development,:test]
gem 'jquery-rails','2.1.4'
gem 'json'
gem 'kaminari'
gem 'launchy', ">= 2.3.0", group: [:development,:test]
gem 'lazybox'
gem 'libnotify', '~>0.5.2', group: [:development,:test]
gem 'meta_request', group: :development
gem "meta_search"
gem 'mimetype-fu'
gem 'mini_magick'
gem 'mysql2'
gem 'nested_form', :git => "https://github.com/ryanb/nested_form.git"
gem 'paper_trail', '~> 2' #bundle exec rails generate paper_trail:install
gem 'parallel_tests', group: [:development,:test]
gem "prawn"
gem 'pry', group: :development
gem 'pry-rails', group: :development
gem "rabl"
gem "rack-test", group: [:development,:test]
gem 'rack-rewrite'
gem 'rails', '~>3.2'
#gem 'rails_view_annotator', group: :development
gem "rake",">=10.1.1"
gem 'rb-fsevent', group: [:development,:test]
gem 'remotipart' # Ajax image uploading
gem 'rest-client'
gem 'rspec', '>= 2.8.0', group: [:development,:test]
gem 'rspec-rails', '>= 2.8.0', group: [:development,:test]
gem 'rvm-capistrano', group: [:development,:test]
gem "sass", "~> 3.2.14"
gem 'sass-rails', "~>3.2.0"
gem 'simple_form', '>=2.0'
gem 'simplecov', require: false, group: [:development,:test]
gem 'spork', group: [:development,:test]
gem 'spreadsheet'
gem 'therubyracer'
gem "thinking-sphinx", "3.0.0"
gem 'thor'
gem "tinymce-rails", :git => 'https://github.com/newbray/tinymce-rails.git'
gem 'uglifier', '>= 1.0.3', :require => 'uglifier'
gem 'unf'
gem 'unicode'
gem 'unicorn'
gem 'whenever'
gem "will_paginate"
gem 'workflow'
#gem 'ZenTest', '~>4.9.4', group: [:development,:test]
gem 'zeus-parallel_tests', group: [:development,:test]

I've tried backdating version of devise, as well as this article but still no joy.
I cloned this repo recently. My development database is working fine.
does anybody have any suggestions as to why this is occurring?
Thanks in advance


text:
Q: How to get the anchor from the URL using jQuery? I have a URL that is like:
www.example.com/task1/1.3.html#a_1

How can I get the a_1 anchor value using jQuery and store it as a variable?

A: Use
window.location.hash

to retrieve everything beyond and including the #

A: For current window, you can use this:
var hash = window.location.hash.substr(1);

To get the hash value of the main window, use this:
var hash = window.top.location.hash.substr(1);

If you have a string with an URL/hash, the easiest method is:
var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:
var hash = $(location).attr('hash');

A: jQuery style:
$(location).attr('hash');

A: If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:
var url = "www.example.com/task1/1.3.html#a_1"
var anchor = url.match(/#(.*)/)[1]

A: You can use the .indexOf() and .substring(), like this:
var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:
var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

A: You can use the following "trick" to parse any valid URL. It takes advantage of the anchor element's special href-related property, hash.
With jQuery
function getHashFromUrl(url){
    return $("<a />").attr("href", url)[0].hash.replace(/^#/, "");
}
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

With plain JS
function getHashFromUrl(url){
    var a = document.createElement("a");
    a.href = url;
    return a.hash.replace(/^#/, "");
};
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1


text:
Q: JMeter: Get list of column headers and their index I am looking for a solution to get list of column headers and their indexes.
Task: pass column headers from a CSV file and their indexes to a variable for further use in HTTP request. Idea is to create a mapping which would indicate which column to use for the given header, as following example:

name
position
company

John
manager
Alphabet

Smith
intern
JP Morgan

So the request would contain:
{"name":0},{"position":1},{"company":2}
I use multiple files where number of columns can be anything from 3 to 50 (or more), so there's no max size. I thought about following approach:

*

*Read all headers and split by coma into a list / collection

*Loop through them and use index of the list items as the index I need:
Headers: |header_1 | header_2 | ... | heade_n |
Request: {"header_1":0},{"header_2":1}...{"header_n":n-1}
Question: How to iterate through all columns while size of the file is unknown?
I found this answer where the OP has a fixed number of columns, and solution uses every value for a separate request, but I have to send only one request with the list of headers and indexes.
P.S. I am new to JMeter and Groovy, so didnt have enough time to make a full scale research. So if the answer will explain how to use pass this variable to the request would be appreciated.

A: There are no "headers" or "columns" in CSV files, there is "first line" and entries delimited by comma.
So if you file looks like:
name,position,company
John,manager,Alphabet
Smith,intern,JP Morgan

You can generate the desired request body like:
def payload = []
def firstLine = new File('test.csv').readLines().get(0)
def entries = firstLine.split(',').size() - 1

0.upto(entries, { index ->
    payload.add([('header_' + (index + 1)): index])
})

vars.put('payload', new groovy.json.JsonBuilder(payload).toString())

and refer generated value as ${payload} where required
Demo:

More information:

*

*Reading a File in Groovy

*Apache Groovy - Parsing and producing JSON

*Apache Groovy - Why and How You Should Use It

A: You can use Groovy to get the names of column headers.
File file = new File("<path-to-file-name>.csv")
String header_1, header_2, header_3

file.withReader {reader ->
    def lstColumns = reader.readLine().split(",")
    header_1 = lstColumns[0]
    header_2 = lstColumns[1]
    header_3 = lstColumns[2]
}

A: I need to get the value for  given index so the request would be like {"name":0},{"position":1},{"company":2}, i.e. not just "header_{0}"; and with your heads-up and those links, came up with following:
def payload = []
def firstLine = new File('test.csv').readLines().get(0)
def entries = firstLine.split(',')
entries.eachWithIndex{value, index ->
    log.info("'${value}': ${index}")
    payload.add("{'${value}': ${index}}")
}

vars.put('payload', new groovy.json.JsonBuilder(payload).toString())
//log.info('payload : ' + new groovy.json.JsonBuilder(payload).toString())