text:
Q: Firebase Security: Only users who are referenced in the object should read it I have objects in my Firebase and I want to restrict access only to users who are referenced in the object. My Firebase structure looks like this:

*

*Object

*

*object_info

*contacts

*

*$contact_id

*

*user_id

*user_role

*users

*

*$user_id

*

*user_info

object/contacts/$contact_id/user_id references to users/$user_id
So every user who should have access appears as user_id in one child of contacts. Unfortunately I cannot find a method to search all children of contacts for a certain user_id.
Is there a way to set this Firebase security rule of should I change my whole Database Structure in order to keep it safe?

A: You can check for the existence of the user's node:
{
  "Object": {
    ".read": "data.child('contacts').child(auth.uid).exists()"
  }
}


text:
Q: How to generate SQL if we are adding column in middle in table using liquibase Suppose in v1 I have a table
create table test1
{
col1 varchar2(10),
col2 varchar2(10),
col3 varchar2(10),
}

in version v2, there is request to add table in middle column col1_2 like
create table test1
{
col1 varchar2(10),
col1_2 varchar2(30),
col2 varchar2(10),
col3 varchar2(10)
}

so does liquibase has ability to add generate table  of rebuild table?

A: No, Liquibase can not do this in a generic way. You could drop and re-create the table, but that is probably not what you want to do. If you want to do something like this, you would need to do a SQL change that did something fairly complex. One way would be to create a new table with the columns in the order you want, and then copy the data from the old table to the new one, then drop the old table, and finally rename the new table to the correct name.
An easier way to do it might be with a view.
In general, the order of columns in a table should not be considered important.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a web-kit or gecko based Webbrowser library on wp7? The original browser doesn't support css3 and HTML5,It even cannot display jQuery Mobile demo and Ckeditor.Is there any replacement for this?

A: wp7 still runs IE7 which was made when HTML5 and CSS3 were not even though about!.
You could check out Opera Mobile as of now.
for jQuery mobile demo, you could refer browser support here: http://jquerymobile.com/gbs/
cheers

A: There's an update (codename Mango) on the way to bring IE9 and its new Javascript compiler to Windows Phone 7. IE9 is an implementation of HTML5/CSS3. I have not special knowledge but the rumors on the web:
http://gizmodo.com/5724937/windows-phone-7-rumored-updates-copy--paste-ie9-html5-and-silverlight-coming


text:
Q: Unable to refer to a textbox because I haven't created it yet I am using VB to make a file editing system that allows the user to edit multiple files on multiple tabs like Notpad++.
I hit a slight snag though. Seeing as tabs don't contain text, I add a textbox to each tab upon creation.
For loading files I want to check if the current tab's textbox is empty so I don't end up adding the loaded file as a new tab, which would just create clutter (like how when word opens a file, it checks if the current document is an unsaved file with no text before loading.)
Problem is, how do I check this with tabs I haven't added yet? (Ie will be added whilst the program is running as opposed to in design mode)
If anyone knows the answer, it would be greatly appreciated.

A: I don't know VB.NET, but I have made this code in C# which checks to see if a TabPage contains a TextBox which is empty. I think it's easy to translate it to VB.NET if you know that language.
Here is the function that checks to see if a TabPage contains an empty TextBox. The function receives the TabPage as its parameter and returns true or false.
private bool ContainsEmptyTextBox(TabPage tp)
{
    bool foundTextBox = false;
    bool textBoxIsEmpty = false;
    foreach (Control c in tp.Controls)
    {
        if (c is TextBox)
        {
            foundTextBox = true;
            TextBox tb = c as TextBox;
            if (String.IsNullOrEmpty(tb.Text))
            {
                textBoxIsEmpty = true;
            }
            break;
        }
    }
    if (foundTextBox == true && textBoxIsEmpty == true)
        return true;
    else
        return false;
}

And here is how you can use that function to iterate trough all the tabs in a TabControl and see which one contains an empty TextBox:
private void button1_Click(object sender, EventArgs e)
{
    foreach (TabPage tp in tabControl1.TabPages)
    {
        if (ContainsEmptyTextBox(tp))
        {
            // This tabpage contains an empty textbox
            MessageBox.Show(tabControl1.TabPages.IndexOf(tp) + " contains an empty textbox");
        }
    }
}

EDIT: I used this site to automatically convert the C# code into VB.NET.
Private Function ContainsEmptyTextBox(tp As TabPage) As Boolean
    Dim foundTextBox As Boolean = False
    Dim textBoxIsEmpty As Boolean = False
    For Each c As Control In tp.Controls
        If TypeOf c Is TextBox Then
            foundTextBox = True
            Dim tb As TextBox = TryCast(c, TextBox)
            If [String].IsNullOrEmpty(tb.Text) Then
                textBoxIsEmpty = True
            End If
            Exit For
        End If
    Next
    If foundTextBox = True AndAlso textBoxIsEmpty = True Then
        Return True
    Else
        Return False
    End If
End Function

Private Sub button1_Click(sender As Object, e As EventArgs)
    For Each tp As TabPage In tabControl1.TabPages
        If ContainsEmptyTextBox(tp) Then
            ' This tabpage contains an empty textbox
            MessageBox.Show(tabControl1.TabPages.IndexOf(tp) & " contains an empty textbox")
        End If
    Next
End Sub

A: A long time ago I also had to make a Notepad++ clone in C#, that needed to support editing multiple files in tabs. I remember that I had a List<string> OpenFiles member in my form that contained the filenames of the open files. Each time I opened a new file, I would do this:

*

*Add a new item to OpenFiles

*Create a new tab with a textbox and add it to the TabControl

In this way, the OpenFiles list was synchronized with the tabs in the TabControl. For example, item 3 in OpenFiles was the filename for the 4th tab in the TabControl.
Of course, when I opened a new file, I needed to check if the file was opened before. If it was opened before, I switched to its tab; if not, I would open a new tab.
Having the OpenFiles member, this was easy. The full algorithm for opening files was this:

*

*Check to see if the file is already open by searching the OpenFiles list

*If the file is already open (if it exists in OpenFiles), and its position in OpenFiles is idx(for example), then activate the idxth tab

*If the file does not exist in OpenFiles

*

*Add it to OpenFiles at the end

*Add a new tab with a textbox to the end of the TabControl

When closing a file (for example closing the idxth tab), I did this:

*

*Check if the file has been saved, if not prompt the user if he wants to save it or not (Yes/No/Cancel messagebox).

*

*If he chose yes, then save it and continue

*If he chose no, then don't save it and continue

*If he chose cancel, then abort the operation (return)

*Remove the idxth tab from the TabControl

*Remove the idxth item in the OpenFiles list

I think you can apply the same logic in your application.


text:
Q: How to group and select elements of dataframe using tidyr/dplyr I have a table in the tibble format which I need to rearrange:
AUS   CAN   DEN   original_period

NA    NA    4.3    1955-02
3.2   NA    NA     1955-02
NA    1.1   NA     1955-02
3.1   NA    NA     1955-03
NA    NA    9.7    1955-03
NA    1.2   NA     1955-03

So as of now I have one valid value per item per row. My aim is to eliminate all the NAs and all the original_period duplicates, so that my table looks like this:
AUS   CAN   DEN   original_period

3.2   1.1   4.3    1955-02
3.1   1.2   9.7    1955-03

Anyone know how to do this efficiently using tidyr or dplyr?
data
df1 <- read.table(h=T,strin=F,text="
AUS   CAN   DEN   original_period
NA    NA    4.3    1955-02
3.2   NA    NA     1955-02
NA    1.1   NA     1955-02
3.1   NA    NA     1955-03
NA    NA    9.7    1955-03
NA    1.2   NA     1955-03")

A: We can group by 'original_period' and with summarise_all either remove all the NA elements per row with na.omit (assuming that the NA elements are distributed equally across groups in all columns) or use mean/max/min etc if there is only single non-NA observation per group
library(dplyr)
df1 %>%
    group_by(original_period) %>%
    summarise_all(mean, na.rm = TRUE) %>%
    # or remove the NAs with na.omit
    #summarise_all(na.omit) %>%
    select(names(df1))
# A tibble: 2 x 4
#     AUS   CAN   DEN original_period
#   <dbl> <dbl> <dbl> <chr>
#1   3.2   1.1   4.3 1955-02
#2   3.1   1.2   9.7 1955-03

A: We can also use coalesce :
library(dplyr)
df1 %>%
  group_by(original_period) %>%
  summarise_all(~coalesce(!!!.))

# # A tibble: 2 x 4
#   original_period   AUS   CAN   DEN
#   <chr>           <dbl> <dbl> <dbl>
# 1 1955-02           3.2   1.1   4.3
# 2 1955-03           3.1   1.2   9.7


text:
Q: Fit models with robust standard errors I am using the following R code to run several linear regression models and extract results to dataframe:
library(tidyverse)
library(broom)

data <- mtcars
outcomes <- c("wt", "mpg", "hp", "disp")
exposures <- c("gear", "vs", "am")

models <- expand.grid(outcomes, exposures) %>%
group_by(Var1) %>% rowwise() %>%
summarise(frm = paste0(Var1, "~factor(", Var2, ")")) %>%
group_by(model_id = row_number(),frm) %>%
do(tidy(lm(.$frm, data = data))) %>%
mutate(lci = estimate-(1.96*std.error),
     uci = estimate+(1.96*std.error))

How can I modify my code to use robust standard errors similar to STATA?
* example of using robust standard errors in STATA
regress y x, robust

A: There is a comprehensive discussion about the robust standard errors in lm models at stackexchange.
You can update your code in the following way:
library(sandwich)

models <- expand.grid(outcomes, exposures) %>%
 group_by(Var1) %>% rowwise() %>%
 summarise(frm = paste0(Var1, "~factor(", Var2, ")")) %>%
 group_by(model_id = row_number(),frm) %>%
 do(cbind(
  tidy(lm(.$frm, data = data)),
  robSE = sqrt(diag(vcovHC(lm(.$frm, data = data), type="HC1"))) )
 ) %>%
 mutate(
  lci  = estimate - (1.96 * std.error),
  uci  = estimate + (1.96 * std.error),
  lciR = estimate - (1.96 * robSE),
  uciR = estimate + (1.96 * robSE)
 )

The important line is this:
sqrt(diag(vcovHC(lm(.$frm, data = data), type="HC1"))) )

Function vcovHC returns covariance matrix. You need to extract variances on the diagonal diag and take compute a square root  sqrt.


text:
Q: Python - Convert certain fields of a dict into a list I have the following Python dict:
{
  'parameter_010': False,
  'parameter_009': False,
  'parameter_008': False,
  'parameter_005': 'CMAX',
  'parameter_004': 'L',
  'parameter_007': False,
  'parameter_006': 'R',
  'parameter_001': 'Foo',
  'id': 7542,
  'parameter_003': 'D',
  'parameter_002': 'M'
}

As seen there are a number of fields named parameter_nnn where nnn is a sequential number. Some are False and others have values populated.
I would like to generate a list with just the parameter_nnn field values which, but just the ones which contains a given value, sorted by number from 001 upwards.
So in this specific case the desired output is:
["Foo", "M", "D", "L", "CMAX", "R"]

Which would be the pythonic way of doing this? I obviously can start iterating but wondering if there is something better than that.
Python 2.7

A: So, assuming you know that you are working with a JSON and how to deserialize:
>>> import json
>>> s = """{
...   "parameter_010": false,
...   "parameter_009": false,
...   "parameter_008": false,
...   "parameter_005": "CMAX",
...   "parameter_004": "L",
...   "parameter_007": false,
...   "parameter_006": "R",
...   "parameter_001": "Foo",
...   "id": 7542,
...   "parameter_003": "D",
...   "parameter_002": "M"
... }"""
>>> d = json.loads(s)

If your parameter_nnn always and strictly follow this format, you can simply sort the items filtered by your requirements (since lexicographical sorting is what you want!):
>>> sorted([(k,v) for k, v in d.items() if v and k.startswith('parameter')])
[('parameter_001', 'Foo'), ('parameter_002', 'M'), ('parameter_003', 'D'), ('parameter_004', 'L'), ('parameter_005', 'CMAX'), ('parameter_006', 'R')]

If you just want the values, just do another pass:
>>> [v for _,v in sorted([(k,v) for k, v in d.items() if v and k.startswith('parameter')])]
['Foo', 'M', 'D', 'L', 'CMAX', 'R']
>>>

Note, you are going to have to loop somehow...
A more readable version:
>>> selection = [(k,v) for k, v in d.items() if v and k.startswith('parameter')]
>>> [v for _,v in sorted(selection)]
['Foo', 'M', 'D', 'L', 'CMAX', 'R']

 EDIT: Major Caveat
Note, if the values can be 0 or any other falsy value that you actually want, then this won't work, so for example:
>>> pprint(d)
{'id': 7542,
 'parameter_001': 'Foo',
 'parameter_002': 'M',
 'parameter_003': 'D',
 'parameter_004': 'L',
 'parameter_005': 'CMAX',
 'parameter_006': 'R',
 'parameter_007': False,
 'parameter_008': False,
 'parameter_009': False,
 'parameter_010': False,
 'parameter_011': 0}
>>> selection = [(k,v) for k, v in d.items() if v and k.startswith('parameter')]
>>> [v for _, v in sorted(selection)]
['Foo', 'M', 'D', 'L', 'CMAX', 'R']

So if you want to filter instances of False specifically (and not 0) then you have to use is:
>>> selection = [(k,v) for k, v in d.items() if v is not False and k.startswith('parameter')]
>>> [v for _, v in sorted(selection)]
['Foo', 'M', 'D', 'L', 'CMAX', 'R', 0]

A: Here is one solution:
list(zip(*sorted(i for i in d.items() if i[0].startswith('parameter') and i[1])))[1]

# ('Foo', 'M', 'D', 'L', 'CMAX', 'R')

Explanation

*

*We filter for 2 conditions: key starts with 'parameter' and value is Truthy.

*sorted on d.items() returns a list of tuples sorted by dictionary key.

*list(zip(*..))[0] returns a tuple of values after the previous filtering and sorting.

*I haven't dealt with  as I have no idea where this is from and what logic should be applied to remove this (and other?) tagging.

A: import collections

dicty = {
  "parameter_010": False,
  "parameter_009": False,
  "parameter_008": False,
  "parameter_005": "CMAX",
  "parameter_004": "L",
  "parameter_007": False,
  "parameter_006": "R",
  "parameter_001": "Foo",
  "id": 7542,
  "parameter_003": "D",
  "parameter_002": "M"
}
result = []

od = collections.OrderedDict(sorted(dicty.items()))
for k, v in od.iteritems():
    if v != False and "parameter" in k:
        result.append(v)
print(result)


text:
Q: Firestore data extraction sequence in a MVP pattern in Android JAVA I am new to MVP architect and I am implementing it in my App. I start with fetching the data from Firestore first and update an activity list to an adapter in a fragment.
I am having problem in the sequence on running the repository part in Firestore. I have set to run my Fetch data function first then do the update view to interface in the presenter. However, the result turn out it finish the update view first then Fetch the data. I am not sure what wrong is in my code.
I have my View
private ActivityAdapter ActivityAdapter;
ArrayList<Activity> ActivityList = new ArrayList<>();
private SpotDetailPresenter SpotPresenter;

@Override
public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;

}

public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
      Presenter = new Presenter(this);
      final View root = inflater.inflate(R.layout.fragment_activity_list, container, false);
      RecyclerView recyclerView = root.findViewById(R.id.rvContainer);
      Presenter.GetActivityList();
      recyclerView.setHasFixedSize(true);
      recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
      recyclerView.setAdapter(ActivityAdapter);
      return root;

}

@Override
public void UpdateActivityList(ArrayList<Activity> newActivityList) {

        for (int i = 0 ; i<newActivityList.size();i++){

            ActivityList.add(newActivityList.get(i));

        }
        ActivityAdapter = new ActivityAdapter(ActivityList, mContext);
        ActivityAdapter.notifyDataSetChanged();

}

My presenter
public class Presenter {

    private Repository Spot;
    private View view;
    public Presenter (View view) {

        this.Spot = new Repository();
        this.view = view;

    }

    public void GetActivityList(){
        Spot.getFullActivityList();
        view.UpdateActivityList(Spot.toArray());

    }

    public interface View{

        void UpdateActivityList(ArrayList<Activity> ActivityList);

    }

}

My Repository
public class Repository_Spot {

    private CollectionReference Ref = Helper.getCheckinCollection();

    private ArrayList<Activity> ActivityList = new ArrayList<>();

    public Repository (){

    }

    public Repository(ArrayList<Activity> ActivityList){
        this.ActivityList = ActivityList;

    }

    public void getFullActivityList(){

        Ref.document("uid").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                if (task.isSuccessful()) {

                    DocumentSnapshot document = task.getResult();
                    Map<String, HashMap> root = (Map<String, HashMap>) document.get(Root);
                    this.ActivityList.add(new Activity(root.getValue()));

                }
            }

        });

    }

    public ArrayList<Activity> toArray(){

        return ActivityList;

    }

}

Based on above coding, it run the "Ref.document("uid").get()" part at last. As the result, I cannot refresh the view with the data. Any idea on what I do change? Am I having something wrong on my "Adapter.notifyDataSetChanged();"?

A: You are doing the callback wrong. Your firebase callback is basically another thread. Then it update data AFTER you call view.UpdateActivityList(). To fix this, you have to create a way to notify your Presenter that your Repo have the updated data. Then Presenter will update the View.

*

*public void GetActivityList(){
Spot.getFullActivityList();
view.UpdateActivityList(Spot.toArray()); -> Remove this.

}

*Create new interface inside your presenter to get update from your Repo:
interface onDataUpdateListener(){
void onDataUpdated(Your list);

}

*Notify your presenter when repo completed task.
 @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

        if (task.isSuccessful()) {

            DocumentSnapshot document = task.getResult();
            Map<String, HashMap> root = (Map<String, HashMap>) document.get(Root);
            this.ActivityList.add(new Activity(root.getValue()));
         yourlisener.onDataUpdated(Your list)
       }

*Set listener when u init your Repo
public Repository (Your listener){
}

*Implement the listener inside your Presenter.
Presenter implements onDataUpdateListener {
}


text:
Q: Class objects comparison - Getting wrong output for equals method I have a class hierarchy which is show below:
    public class Rectangle2
    {
        // instance variables
        private int length;
        private int width;
        /**
         * Constructor for objects of class rectangle
         */
        public Rectangle2(int l, int w)
        {
            // initialise instance variables
            length = l;
            width = w;
        }
        // return the height
        public int getLength()
        {
            return length;
        }
        public int getWidth()
        {
            return width;
        }
        public String toString()
        {
            return "Rectangle - " + length + " X " + width;
        }
public boolean equals( Object b )
           {
               if ( ! (b instanceof Rectangle2) )
               return false;
               Box2 t = (Box2)b;
               Cube c = (Cube)b;
               return t.getLength() == getLength()
                       && t.getWidth() == getWidth()
                       && c.getLength() == getLength()
                       && c.getWidth() == getWidth() ;
}

    }

.
public class Box2 extends Rectangle2
{
    // instance variables
    private int height;
    /**
     * Constructor for objects of class box
     */
    public Box2(int l, int w, int h)
    {
        // call superclass
        super(l, w);
        // initialise instance variables
        height = h;
    }
    // return the height
    public int getHeight()
    {
        return height;
    }
    public String toString()
    {
        return "Box - " + getLength() + " X " + getWidth() + " X " + height;
    }
         public boolean equals( Object b )
           {
               if ( ! (b instanceof Box2) )
               return false;
               Rectangle2 t = (Rectangle2)b;
               Cube c = (Cube)b;
               return t.getLength() == getLength()
                       && t.getWidth() == getWidth()
                       && c.getLength() == getLength() ;
  }
   }

.
public class Cube extends Box2 {
            public Cube(int length)
             {
              super(length, length, length);
             }
            public String toString()
    {
        return "Cube - " + getLength() + " X " + getWidth() + " X " + getHeight();
    }

             public boolean equals( Object b )
           {
               if ( ! (b instanceof Cube) )
               return false;
               Rectangle2 t = (Rectangle2)b;
               Box2 c = (Box2)b;
               return t.getLength() == getLength()
                       && t.getWidth() == getWidth()
                       && c.getLength() == getLength()
                       && c.getWidth() == getWidth()
                       && c.getHeight() == getHeight() ;
  }
}

I created the equals() method so that when the instances of one class would equals the other it would print some like "The dimensions of this class equals the dimensions of that class." This would be an example: http://i.stack.imgur.com/Kyyau.png
The only problem is I am not getting that output. Also could I just inherit the equals() method from the Box2 class when I am doing the equals() method for the Cube class?

A: Your cast to Cube inside of Box2.equals() will fail and throw a ClassCastException whenever you pass a Box2 that is not also a Cube. You repeat this error throughout your code.
I recommend fixing the braces of your if statement, though it should work as expected.
I wouldn't expect you to get any output, actually. You don't have any print() or println() calls in your code.
Also, inside Cube.equals(), you should cast b to a Cube, and call each function from the declared Cube object. You should do the same in nearly any equals(Object) method.
In your implementation, also, since Rectangle2 and Cube do not override getWidth() or getLength(), t.getWidth() and c.getWidth() will call the same functions and thus return the same output every time. Likewise for getLength().
For example, your Rectangle2 class should look something like this.
public class Rectangle2 {

    private final int length;
    private final int width;

    public Rectangle2(int length, int width) {
        this.length = length;
        this.width = width;
    }

    private int getLength() { return length; }
    private int getWidth() { return length; }

    public String toString() {
        return "Rectangle - "+length+" X "+width;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Rectangle2)) {
            return false;
        }
        final Rectangle2 r = (Rectangle2) o;
        return this.getLength() == r.getLength() &&
               this.getWidth() == r.getWidth() &&
               this.getHeight() == r.getHeight();
    }
}

and your Box2 class should look something like this.
public class Box2 extends Rectangle2 {

    private final int height;

    public Box2(int length, int width, int height) {
        super(length, width);
        this.height = height;
    }

    private int getHeight() { return height; }

    public String toString() {
        return "Box - "+length+" X "+width"+ X "+height;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Box2)) {
            return false;
        }
        final Box2 b = (Box2) o;
        return this.getLength() == b.getLength() &&
               this.getWidth() == b.getWidth() &&
               this.getHeight() == b.getHeight();
    }
}

and your Cube class should look something like this
public class Cube extends Box2 {

    private final int height;

    public Cube(int length) {
        super(length, length, length);
    }

    public String toString() {
        return "Cube - "+length+" X "+width"+ X "+height;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Cube)) {
            return false;
        }
        final Cube c = (Cube) o;
        return this.getLength() == c.getLength(); // length == width == height
    }

}

You should then be able to add a call to System.out.println() to print the desired output to the console.
You should declare your fields as final since they are immutable.
Lastly, if you have other classes with similar names, you should find more meaningful ways to differentiate the class names than numbers. Otherwise, remove the 2 from the names Rectangle2 and Box2.

A: You can't put code after the last return statement. It won't be reachable.
You'll need to assign the "equal" return to a local variable, print it and then return it:
boolean equal = getLength() == getLength()
               && t.getWidth() == getWidth()
               && c.getLength() == getLength()
               && c.getWidth() == getWidth()
               && c.getHeight() == getHeight() ;
if (equal) {
    System.out.prinltn("equal");
}

return equal;

And the equals method is inherited, but you're overriding it. If you want to call the super class equals method in the body of the extended class, you'll nedd to call super() on the begining of the overrided method.
public boolean equals( Object b ) {
     boolean equal = super.equals(b);
  ...

A: In my opinion, your equals methods should look like this (just change classes):
public boolean equals( Object b ) {
    if (b instanceof Rectangle2) {
        Rectangle2 rectangle2 = (Rectangle2)b;
        return this.getLength() == rectangle2.getLength()
            && this.getWidth() == rectangle2.getWidth()
            && this.getHeight() == rectangle2.getHeight();
    } else {
        return false;
    }
}

If you want to print result of this method, assign value to any variable, print it and return that value.


text:
Q: Create multiple buttons with multiple functions I have 0 coding knowledge, but hoping you guys can assist with modifying this code I found online to create multiple buttons to execute different bat files. I would save it as an hta file so it can be run in a win shell environment. Thank you!!!
<html>
<head>
    <title>Batch Files</title>
    <SCRIPT type="text/jscript">
        window.moveTo(500,500);
        window.resizeTo(730,100);
    </SCRIPT>
        <HTA:APPLICATION ID="oMyApp"
        APPLICATIONNAME="Application Executer"
        SHOWINTASKBAR="yes"
        SINGLEINSTANCE="yes"
        SYSMENU="yes"
        SCROLL="no"
        WINDOWSTATE="normal">
    <script type="text/javascript" language="javascript">
        function button1() {
        RunExe
        WshShell = new ActiveXObject("WScript.Shell");
        WshShell.Run("c:/hub/dd.bat", 1, false);
        }
        function button2() {
        RunExe
        WshShell = new ActiveXObject("WScript.Shell");
        WshShell.Run("c:/hub/dd2.bat", 1, false);
        }
        </script>
</head>
<body>
    SELECT THE BATCH FILE:
    <input id="b1" type="button" value="Batch 1" onclick="button1();"/>
    <input id="b2" type="button" value="Batch 2" onclick="button2();"/>
</body>
</html>

A: You could give every button an unique id.
<input id="write_your_id_here" style="width: 170px; height:23px; color: white; background-color:    #203040;
 font-family:Book Antiqua;" type="button" Value="Start Chrome"
 onClick=RunExe()

"onClick" is for telling the button what to do when clicked.


text:
Q: I have a date/time stamp field, where I need to pull records just by date I have a date/time stamp field, where I need to pull records just by date.
Example: All data were records are >= '01/01/2016'.
The data in the field is store in the following format '9/5/2012 7:34:59 AM'
I have tried the following but either I get an error or bad results:

*

*where to_char(start_time) > '01/01/2016'  (still gives 2012 records)

*where trunc(start_time) > '01/01/2016'   (Error: Not a valid month)

A: In  mysql you should use
this is in string canonical format
select * from my_table
where start_time > '2016/01/01'

or
or converting by str_to_date using proper format
select * from my_table
where start_time > str_to_date('01/01/2016', '%d/%m/%Y')

A: Use to_date to convert the string to date and then do the comparison.
Try this:
where start_time >= to_date('01/01/2016', 'dd/mm/yyyy');

A: In Oracle (and perhaps other database products) you can use the ANSI date literal, as shown below. You could also use to_date(), but the benefit of the ANSI date literal is that it doesn't require a function call. (Function calls are overhead which consumes time and resources, although calling to_date() just once is not a concern.)
... where start_time >= date '2016-01-01'

Note that in the ANSI standard date literal, the date must be in the exact format YYYY-MM-DD (with dashes and not with slashes or any other separators), since the ANSI date literal does not take a format model.


text:
Q: How to include categories for which there are no values in an ssrs chart I've got a query that gets some data points for the last 6 months (prior to current), akin to this:
SELECT  [DataPoint], [When]
FROM    Table
WHERE
        [When] >= DATEADD(MONTH, -7, @CurrentMonth)
        [When] < @CurrentMonth

And my ssrs chart has a category like this:
=Format(DateAdd(DateInterval.Month, DateDiff(DateInterval.Month, CDate("1900/01/01"), Fields!When.Value), CDate("1900/01/01")), "MMM")

The horizontal axis is configured thusly:

*

*Number: Category = Date, Type = Jan 2000

and I've tried setting:

*

*Axis Options: Interval = 1, Interval type = Months

... but it doesn't help.
It works great when there are data points within each month, but I have some data sets that only have data for some months (ie. Dec/Jan) and it will only show those months.
Is there any way to get it to show the full 6 months of "data" (or lack thereof) without dumping empty data in the dataset?

A: The best solution I've found to this type of issue is to create a date dimension table that shows various information for dates- in this case it could simply be date and month, but other implementations I've seen include whether or not a particular day is a holiday or a day in which employees will work.
Then, apply the date criteria to this dimension table and left join the results onto it-
CREATE TABLE date_dim (Date_eval, Month)

...

SELECT  [t.DataPoint], [dd.Month]
FROM   date_dim dd
LEFT JOIN Table t
   ON t.[When] = dd.Date_Eval
WHERE
    Date_eval >= DATEADD(MONTH, -7, @CurrentMonth)
    Date_eval < @CurrentMonth

The downside of this approach is that you have to populate a table with data and that if you use a date dimension attribute that can change, such as whether or not employees work a certain day, the table is difficult to maintain automatically.
The upside is that you have a framework to build reports like this on, and one that can be reused as often as you need it.


text:
Q: Basic setup for LaTeX for Mac? I have a professor who requires me to use Latex but he mainly speaks in terms of PC. I have a Mac so I have to find appropriate alternatives. So far I have purchased "Latexian" as an editor, and see that the MikTeX distribution is mainly for PC. It seems that the alternative for Mac is Mactex.
Am I correct?
Is there any other concern I should consider?
Out of curiosity, why wouldn't Latexian have a built in installer, since it can obviously generate live PDF views anyway?

A: As others have remarked, the nearest equivalent to MikTeX on Mac OS X is MacTeX. Alternately, you could install BasicTeX for a smaller and less capable download. The Latexian FAQ addresses this in a minor note, which seems odd given the importance of TeX for a LaTeX IDE.
As to why Latexian doesn't include a built-in installer for TeX, I'd guess that the sheer size is the main reason. Latexian is under 10 MB, while BasicTeX is ~100 MB, and MacTeX is ~2.4 GB.

A: I slightly prefer TeXMaker to Latexian (have been working with both), but depends on how complicated your document gets. (Texmaker is free; it doesn't have a live preview, but I think it's more flexible as far as compilation goes.) I never had any problems with using LaTeX on a Mac. (You have to install a texmf folder into your library, where you keep the style files if any.)

A: I use Latexian + MacTex and it works great. I you are just starting out, it's the right combination. Once you get a bit more used to LaTeX, you can try something like Sublime Text + the Latexing plugin. It's more powerful but harder to use.
You can get MacTex here: https://tug.org/mactex/. Just download it and double click on the setup file. Follow the steps and that is it. This is required by Latexing otherwise you can't generate the PDF's

A: I am new as well. Mactex is the distribution and what I have used to get all the tex stuff.
For an editor I use Texpad. It is a paid for editor but it si great IMHO, super easy to use, has live preview and a good outline pane. I sure free ones do the same too.
Also think about some sort of versioning system like Github or Subversion. I use Github
Hope it helps


text:
Q: SQL - GROUPING, ID, NAME I was wondering what the answer should be for 1c. on this website:
http://sqlzoo.net/6.htm
SELECT company
FROM route WHERE stop=4
GROUP BY name, ID

this obviously isn't working, the ID and name isn't showing up no matter what. What is missing here? Thanks.

A: SELECT stops.id, stops.name
FROM route
INNER JOIN stops on route.stop = stops.id
WHERE route.num = 4 AND route.company = 'LRT'

You need to join the tables as the data you want to return is in a different table to the one which filters the data.

A: This works and does not include any unnecessary table joins. A good rule of thumb is to use EXISTS to verify values in a table that you do not need the output for. Otherwise, you would use a JOIN
SELECT stops.id, stops.name
FROM stops
WHERE EXISTS
(
    SELECT 1 FROM route
    WHERE route.stop = stops.id AND num = '4' AND company = 'LRT'
)

A: It gives you this error:

sql: Unknown column 'name' in 'group statement'

There is no name in route tabel.
The tables structure are:
stops(id, name)
route(num,company,pos, stop)

So the answer for this quiz is:
SELECT s.id, s.name
FROM   route r, stops s
WHERE  r.stop= s.id
and    r.num = 4 AND r.company = 'LRT'

A: select s.id, s.name
from stops s
inner join route r
    on s.id = r.stop
where r.num= 4
    AND r.company= 'LRT'


text:
Q: Excel - export in a new sheet only the cells values that respect a condition I'm going to explain my problem.
In the USERS column there are users ID that I have to copy into another Excel sheet only if in the REQUEST column there is the word "Creation", but if, in a later row, the same user ID has in the REQUEST column the word "Elimination", the very same user has to disappear from the second Excel sheet. I've just tried with Pivot table, INDEX, MATCH formula but I don't have success.

A: Try using FILTER() Function, assuming you are using MS365

• Formula used in cell E2
=FILTER(A2:C5,B2:B5<>"Deletion")

Or,
• Formula used in cell I2
=FILTER(A2:C5,B2:B5="Creation")

Edit --> Excluding Eliminated

• Formula used in cell E2
=FILTER(A2:C7,(B2:B7<>"Deletion")*(B2:B7<>"Eliminated"))

Or,
• Formula used in cell I2
=FILTER(A2:C7,B2:B7="Creation")


text:
Q: Ridge regression objective function gradient Considering ridge regression problem with given objective function as:
$$f (W) = \|XW - Y\|_F^2 + \lambda \|W\|_F^2$$
Having convex and twice differentiable function results into:
$$\nabla f (W) = 2 \lambda W + 2X^T(XW - Y)$$
And finding its roots. My question is: why is the gradient of $\|XW - Y\|_F^2$ equal to $2X^T(XW - Y)$?

A: Rewrite
$$||XW-Y||^2_2 = \left[XW-Y\right]^T\left[XW-Y\right]=\left[W^TX^T-Y^T\right]\left[XW-Y\right]=W^TX^TXW-Y^TXW-W^TX^TY+Y^TY$$
Hence, the total derivative on the right-hand side gives
$$dW^TX^TXW+W^TX^TXdW-2dW^TX^TY=2dW^T\left[X^TXW-X^TY \right]=dW^T\left[2X^T(XW-Y) \right].$$
The expression in the bracket is the gradient of the initial expression with respect to $W$. Note, that I used the fact that the transpose of a scalar is a scalar.


text:
Q: How to convert your Spring Mvc maven based Java Project into an app I have an Advance Java based project  prepared on Spring Mvc framework with Hibernate. My requirement is to wrap it up into an app n publish it.
So, How should I proceed with it because I have faced many issues even at creating a war of the same.

A: If your intention is to have a robust app, then you would have to create that from scratch. If the app is going to be for android, you can do that using Java, Kotlin... if it is going to be an IOS app then you would have to probably use SWIFT for this purpose. You can always use Google Flutter to create a beautiful responsive and robust app that would smoothly work on Android and IOS devises.
Please note: you would need to connect your app to the same server/database that your spring project connects to so they are both consistent as far as data is concerned....

A: I assume that your app serves HTML of some sort. I also assume that by "app" you mean an app on mobile phones.
You have two options:
Difficult one: build a client-server architecture by exposing an API (easiest one is REST based) then build a separate Android and iPhone client that connects to your backend.
Easy one: use a tool like https://gonative.io/ (not affiliated, just first result by googling "android webpage into app"). Those kinds of tools create an app which just loads a browser and opens your page in it.
Usually, the "easy" option is frowned upon, but it is MUCH better in terms of time to market.


text:
Q: How to detect an Iphone/Ipod volume level? Hi there I have an app that play short sound clips as the main functionality.  If the user happened to have the volume to mute or too low,  they won't be able to hear the sound clip and the app will appear to be broken.
Is there a way to detect the sound volume so that i can display a message to the user to indicate that their sound is too low or off and they need to adjust the volume?
I searched through stackoverflow and google and it seems like i can only find article on how to change the volume or detecting volume changed event.  Thank you.

A: You can use the MPMusicPlayerController
It has the property volume which will let you read the volume level.


text:
Q: How to use TRIM on encrypted home folder I've installed Ubuntu 16.04 LTS. During the installation, I've checked 'encrypted home' but home folder is in the same partition as the root (i.e in '/'). I know that the usage of TRIM on LUKS devices is different but I could not find anything about how to use it in my case. I also know that the installer uses ecryptfs for home folder encryption. The only thing I could found is this link TRIM and encrypted home folders, but it does not provide an answer. So the question is: How can I use TRIM on my encrypted home folder (not partition)? Several info you might need:
SSD: Corsair Force LS SSD
~$ lsblk
NAME           MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
sda              8:0    0 223.6G  0 disk
├─sda1           8:1    0   512M  0 part  /boot/efi
├─sda2           8:2    0 215.2G  0 part  /
└─sda3           8:3    0   7.9G  0 part
  └─cryptswap1 252:0    0   7.9G  0 crypt [SWAP]

~$ uname -r
4.4.0-21-generic

A: Encrypted home folder are virtualy mounted unencrypted.
All your files in your encrypted /home/username
folder exist real in:/home/.ecryptfs/username
in encrypted format.
So if you use "fstrim -av" you are trimming the complete disk unneeded.
~$ fstrim -av
/home/username: 271.1 GiB (291104260096 bytes) trimmed
/: 0 B (0 bytes) trimmed

After every reboot it will do the same.
So it is better to trimm only the real files written on disk:
fstrim -v /

Add a weekly scheduler:
sudo cp /usr/share/doc/util-linux/examples/fstrim.{service,timer} /etc/systemd/system
sudo systemctl enable fstrim.timer

and edit /etc/systemd/system/fstrim.service
[Unit]
Description=Discard unused blocks

[Service]
Type=oneshot
ExecStart=/sbin/fstrim -v /


text:
Q: Create HighCharts-Column type from JSON I am trying to create a column type highchart using data from json in the following format:
[{"id":7,"dateV":"2015-11-16","count":10},{"id":6,"dateV":"2015-11-15","count":3},{"id":5,"dateV":"2015-11-14","count":15},{"id":4,"dateV":"2015-11-13","count":10},{"id":3,"dateV":"2015-11-12","count":6},{"id":2,"dateV":"2015-11-11","count":8},{"id":1,"dateV":"2015-11-10","count":5}]

X axis should show the date values and the Y axis should show the count. Somehow i am not able to transform this JSON in the format required.
Here is my code.
<script type="text/javascript">
        $('#myButton').click(function() {
            var options = {
                    chart: {
                        renderTo: 'chartContainerDiv',
                        type: 'column'
                    },
                    series: [{}]
                };

                var url = "callToControllerURL";
                $.getJSON(url,  function(data) {
                    console.log(JSON.stringify(data));
                    options.series[0].data = JSON.stringify(data);
                    var chart = new Highcharts.Chart(options);
                });
            });
    </script>

console log shows the JSON in format specified above. I am guessing i have to form the x and y axis values from the options array. How do i do it?

A: You need to iterate over the json data and create category data and series by pushing values.
var jsonData = [{"id":7,"dateV":"2015-11-16","count":10},{"id":6,"dateV":"2015-11-15","count":3},{"id":5,"dateV":"2015-11-14","count":15},{"id":4,"dateV":"2015-11-13","count":10},{"id":3,"dateV":"2015-11-12","count":6},{"id":2,"dateV":"2015-11-11","count":8},{"id":1,"dateV":"2015-11-10","count":5}];

 var categoryData= [];
 var seriesData= [];
$.each(jsonData, function(i,item){
seriesData.push(jsonData[i].count);
categoryData.push(jsonData[i].dateV);
console.log("seriesData"+JSON.stringify(seriesData));
});

See Working demo with your json here


text:
Q: How do I get the attributes of a short code from a post? I am trying to preview a NextGen gallery on my main page (and category pages) to show a single image from the gallery on the main page next to the text from the post that normally shows up.  I have found examples of PHP that get the images from a gallery given a gallery ID.  In my loop I have a current post.  What I cannot figure out is how to, given a post, get the attributes of the [nggallery] short code.
In other words for each post with a NextGEN gallery I need the id value form the short code.  For example if the post contains [nggallery id=50] I need the value 50.
How can I get that information from a post?
I was hoping to find the solution in the source code of the next gen plug-in but of course that code registered a short code handler and lets WP call them back.  There are no examples in their source code where they parse a post looking for their short code.

A: Your solution has helped me find an answer to my own problem of getting the attribute of a certain shortcode, but I fear there may be an issue with your approach.
You're using preg_match to check the post_content, which will only return 1 match. If you have a post that has multiple shortcodes in it, it will only return the first one, which may not be the one you're looking for.
Instead, you should use preg_match_all, then loop through the regex_matches array to check for the shortcode you need.
Also, you don't need to use str_replace to remove the quotes from the string. Wordpress has a built-in function shortcode_parse_atts which takes that a string of parameters (in your case it would be $regex_matches[3]) as an argument and outputs an array. This would also spare you the use of wp_parse_args function.

A: I have found a solution.  After a bunch of searching around I found some code that determines if a post has a specific short code in it.
That code also has some attempt to parse the parameters to the short code.  Which is good because I want the gallery ID.  There were some issues with the code as posted so I tweaked it.  Here is code that can find a short code in a post and get its parameters:
        <?php //  Look for a NextGEN gallery
        $galleryID;
        $previewIndex = 1;
        $regex_pattern = get_shortcode_regex();
        preg_match ('/'.$regex_pattern.'/s', $post->post_content, $regex_matches);
        if ($regex_matches[2] == 'nggallery') :
            //  Found a NextGEN gallery find out what ID
            //  Turn the attributes into a URL parm string
            $attribureStr = str_replace (" ", "&", trim ($regex_matches[3]));
            $attribureStr = str_replace ('"', '', $attribureStr);

            //  Parse the attributes
            $defaults = array (
                'preview' => '1',
            );
            $attributes = wp_parse_args ($attribureStr, $defaults);

            if (isset ($attributes["id"])) :
                $galleryID = $attributes["id"];
            endif;
            if (isset($attributes["preview"])) :
                $previewIndex = $attributes["preview"];
            endif;
        endif;
        ?>

What needed to be tweaked was the handling of the parameters.  Using trim instead of some secret charter and switching to wp_parse_args to correctly handle the short code parameters.  Once the above code finishes executing in a WP loop $galleryID will hold the NextGEN gallery ID and previewIndex will be set to the preview index or 1 if no previewIndex attribute was present.
previewIndex is an attribute I "added" to indicate what thumbnail to use for the gallery preview.  NextGEN ignores it and the galleries render as normal but now I can use it for my Theme to display a specific icon in the preview entry.
Here is the code from my loop-index.php and loop-category.php that handles creating the gallery preview:
            <?php /* Enhance the content preview with an image from the NextGEN gallery */ ?>
            <?php
            global $nggdb;
            $gallery = $nggdb->get_gallery ($galleryID, 'sortorder', 'ASC', true, 0, 0);
            $image = $gallery[$previewIndex];
            $total_images = count ($gallery);
            ?>

            <?php if (isset($image)  &&  isset($image->thumbURL)) : ?>
                <?php /* Show the thumbnail */ ?>
                <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark">
                    <img class="entry-preview-image" src="<?php echo $image->thumbURL ?>" align="left" />

            <?php endif; ?>

            <?php /* Show the text excerpt */ ?>
            <?php the_excerpt(); ?>

            <?php /* Show the statement of number of images contained */ ?>
            <?php printf( _n( 'This gallery contains %2$s photo.', 'This gallery contains %2$s photos.', $total_images, 'twentyten' ),
                'href="' . get_permalink() . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
                number_format_i18n( $total_images )); ?>

        <?php endif; ?>

This makes use of information from another answer regarding accessing NextGEN gallery objects in order to get the thumbnail and the count of images in the gallery.

A: Either way you can do it very easily. First Hook a Function. I used wp_head but you can use anyone you want.
add_action( 'wp_head', 'find_shortcode_attribute' );

function find_shortcode_attribute() {
global $post;

if( has_shortcode( $post->post_content, 'nggallery' ) ) {
    preg_match_all( '/' . get_shortcode_regex() . '/', $post->post_content, $matches, PREG_SET_ORDER );

    echo "
";
    print_r( $matches );
    echo "
";

    // you will get the attribute on $matches[3]
    // do whatever you want here.

}


text:
Q: Is there a linux equivalent for fpsetmask()? I'm porting some BSD code to CentOS, and I find that the standard function fpsetmask() found in ieeefp.h has been used in the code.
I'm not yet aware of this function's behaviour, but is there a linux equivalent of this? Or should I create something that emulates this on linux?

A: I think the feraiseexcept() function is the equivalent – for details, look at the "Exception handling" subsection of its manpage.
According to the fpsetmask() manpage, the mapping of the individual flags is as follows:

*

*FP_X_INV → FE_INVALID

*FP_X_DZ → FE_DIVBYZERO

*FP_X_OFL → FE_OVERFLOW

*FP_X_UFL → FE_UNDERFLOW

*FP_X_IMP → FE_INEXACT

*FP_X_IOV → none, possibly FE_OVERFLOW too
Do remember that this is probably x87-only.


text:
Q: M -> N regression where N > M I am seeking to perform a realtime mapping of M input features to N output parameters where N > M, e.g 2 inputs to 10 outputs. In my use-case I would define regions within my input space and associate parameters in my output space in the training phase, then have the ML infer transitions between these regions in the mapping phase. I guess the opposite of dimensionality reduction!
What would be some good machine learning algorithms for achieving this?

A: Neural network can do this but it seems strange to me that you have output dimension greater than the input.
The other way can be training 10 decision trees (or something else), each for one output.


text:
Q: Parse.com PFQueryTableViewController Local datastore I have a Swift app in which I have a PFQueryTableViewController, and I'd like to use the local datastore with Parse. But, I'm getting confused about using the local datastore alongside live queries.
Here is what I'd like to do:

*

*When the PFQueryTableViewController is shown, I'd like it to always get data from the local datastore

*But, after the view is rendered with no lag (since the local data store is powering the source of the data), I want to make an asynchronous call to update the local data store with most updated data from the cloud. At this point, if there is new data, I'd like the most updated data to appear in the table seamlessly and preferably with row animation.

How do I achieve this?

A: Here's how I managed this - maybe it will put you on the right track. I'd be interested to see your solution if you have already fixed the problem.
First, I made a convenience method to create my base query:
- (PFQuery *)baseQuery
{
    PFQuery *query = [PFQuery queryWithClassName:@"MyClass"];
    [query orderByDescending:@"myParameter"];
    return query;
}

We want queryForTable to hit the local datastore consistently.
- (PFQuery *)queryForTable
{
    return [[self baseQuery] fromLocalDatastore];
}

So now all that's left to do is populate the local datastore from the network:
- (void)refreshObjects
{
    [[[self baseQuery] findObjectsInBackground] continueWithBlock:^id(BFTask *task) {
        if (task.error) {
            [self.refreshControl endRefreshing];
            return nil;
        }
        return [[PFObject unpinAllObjectsInBackgroundWithName:@"cacheLabel"] continueWithSuccessBlock:^id(BFTask *unused) {
            NSArray *objects = task.result;
            return [[PFObject pinAllInBackground:objects withName:@"cacheLabel"] continueWithSuccessBlock:^id(BFTask *unused) {
                [self.refreshControl endRefreshing];
                [self loadObjects];
                return nil;
            }];
        }];
    }];
}

We can call this whenever we want: in viewDidLoad or viewDidAppear, in response to a pull-to-refresh event (which is why I have the UIRefreshControl code in there) or whenever else it might be appropriate.

A: I find it best, for now, to override the loadObjects function, which is called every time the tableView is refreshed. Just reload objects of the query into local datastore before loadObjects(0, clear: true)(Which handles refresh behaviors and hard to override) is called. (This should work fine with internet connection, or after refresh all the objects will be void. You need to add some of your own logic for perfection.)
var firstTime : Bool = true

//MARK: Query
func basicQuery() -> PFQuery {
    let query = PFQuery(className: "CLASSNAME")
    return query.orderByAscending("params")
}

override func queryForTable() -> PFQuery {
    return basicQuery().fromLocalDatastore()
}

//MARK: - Refresh
//TODO: Should consider the condition with no internet connection
override func loadObjects() -> BFTask {
    if firstTime {
    // Load frome local data store
        firstTime = false
        return loadObjects(0, clear: true)
    }

    return queryForTable().findObjectsInBackground().continueWithBlock({ (task : BFTask!) -> AnyObject! in
        if task.error != nil { // No object in local data store
            return nil
        }
        if let objects = task.result as? [PFObject] { // Unpin local datastore objects
            return PFObject.unpinAllInBackground(objects, withName: "cacheString")
        }
        return nil
    }).continueWithSuccessBlock({ (task : BFTask!) -> AnyObject! in
        // Fetch objects from Parse
        return self.basicQuery().findObjectsInBackground()
    }).continueWithSuccessBlock({ (task : BFTask!) -> AnyObject! in
        if let objects = task.result as? [PFObject] {
            return PFObject.pinAllInBackground(objects, withName: "cacheString")
        }
        return nil
    }).continueWithSuccessBlock({ (task : BFTask!) -> AnyObject! in
        return self.loadObjects(0, clear: true)
    })
}


text:
Q: How do I use Leaf.xnet Substring recursively I am trying to retrieve password reset links with Leaf.xnet I have been using the Substring but it only loads the first substring when there a recursive amount of password reset emails, how would I be able to grab them all?
textbody.Substring("Reset", "You"));


text:
Q: AWS credentials missing when running userdata in a new EC2 Using terraform scripts, I create a new EC2, add policy to access an S3 bucket, and supply a userdata script that runs aws s3 cp s3://bucket-name/file-name . to copy a file from that S3 bucket, among other commands.
In /var/log/cloud-init-output.log I see fatal error: Unable to locate credentials, presumably caused by executing aws s3 cp ... line. When I execute the same command manually on the EC2 after it's been created, it works fine (which means the EC2 policy for bucket access is correct).
Any ideas why the aws s3 cp command doesn't work during userdata execution but works when the EC2 is already created? Could it be that the S3 access policy is only applied to the EC2 after the EC2 has been fully created (and after userdata has been run)? What should be the correct workaround?
data "aws_iam_policy_document" "ec2_assume_role" {

  statement {
    effect = "Allow"
    actions = [
      "sts:AssumeRole",
    ]
    principals {
      type        = "Service"
      identifiers = [
        "ec2.amazonaws.com",
      ]
    }
  }
}

resource "aws_iam_role" "broker" {
  name                  = "${var.env}-broker-role"
  assume_role_policy    = data.aws_iam_policy_document.ec2_assume_role.json
  force_detach_policies = true
}

resource "aws_iam_instance_profile" "broker_instance_profile" {
  name = "${var.env}-broker-instance-profile"
  role = aws_iam_role.broker.name
}

resource "aws_iam_role_policy" "rabbitmq_ec2_access_to_s3_distro" {
 name = "${env}-rabbitmq_ec2_access_to_s3_distro"
 role = aws_iam_role.broker.id
 policy = data.aws_iam_policy_document.rabbitmq_ec2_access_to_s3_distro.json
}

data "aws_iam_policy_document" "rabbitmq_ec2_access_to_s3_distro" {
 statement {
   effect = "Allow"
   actions = [
     "s3:GetObject",
     "s3:GetObjectVersion"
   ]
   resources = ["arn:aws:s3:::${var.distro_bucket}", "arn:aws:s3:::${var.distro_bucket}/*"]
 }
}

resource "aws_instance" "rabbitmq_instance" {
  iam_instance_profile   = ${aws_iam_instance_profile.broker_instance_profile.name}
  ....
}

A: This sounds like a timing issue where cloud-init is executed before the EC2 profile is set/ready to use. In your cloud-init script, I would make a loop to run a particular AWS cli command or even use the metadata server to retrieve information about the IAM credentials of the EC2 instance.
As the documentation states, you receive the following response when querying the endpoint http://169.254.169.254/latest/meta-data/iam/security-credentials/iam_role_name:
{
  "Code" : "Success",
  "LastUpdated" : "2012-04-26T16:39:16Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "ASIAIOSFODNN7EXAMPLE",
  "SecretAccessKey" : "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
  "Token" : "token",
  "Expiration" : "2017-05-17T15:09:54Z"
}

So your cloud-init/user-data script could wait until the Code attribute equals to Success and then proceed with the other operations.


text:
Q: How to update one Bezier curve as another is moved using a custom editor I am creating Bézier curves using the code below which I got from  here. I have also made a BezierPair game object which has two Bézier curves as child objects.
From the respective images below and BezierPair, where points[0]...points[3] is represented as P0...P3:

*

*I want P0 of each Bézier curve always remain the same when one is moved. In other words I want them to move together always, with the option of turning this movement off.

*Say P1 of both curves are apart. How can I make P1 of each curve move in the same direction covering the same distance?

*Say P2 of both curves are apart. How can I make P2 of one curve mirror P2 of another curve along a line joining  P0 and P3? Note that the mirror line would be taken from the curve 1 in the example below because curve1's P2 is moved. If curve2's P2 is moved, then the mirror line will be taken from curve2's P0P3.

I don't want to do this at run time. So a custom editor has to be used.
I tried solving 1. in the code below but the position for the second curve wouldn't update without my selecting BezierPair in the hierarchy window
Bezier:
public static class Bezier {

public static Vector3 GetPoint (Vector3 p0, Vector3 p1, Vector3 p2,   Vector3 p3, float t) {
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
    oneMinusT * oneMinusT * oneMinusT * p0 +
    3f * oneMinusT * oneMinusT * t * p1 +
    3f * oneMinusT * t * t * p2 +
    t * t * t * p3;
}

public static Vector3 GetFirstDerivative (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
    3f * oneMinusT * oneMinusT * (p1 - p0) +
    6f * oneMinusT * t * (p2 - p1) +
    3f * t * t * (p3 - p2);
}
}

BezierCurve:
[RequireComponent(typeof(LineRenderer))]
public class BezierCurve : MonoBehaviour {

public Vector3[] points;
LineRenderer lr;
public int numPoints = 49;
bool controlPointsChanged = false;

bool isMoving = false;

public void Reset () {
points = new Vector3[] {
    new Vector3(1f, 0f, 0f),
    new Vector3(2f, 0f, 0f),
    new Vector3(3f, 0f, 0f),
    new Vector3(4f, 0f, 0f)
};
}

void Start()    {

lr = GetComponent<LineRenderer> ();
lr.positionCount = 0;
DrawBezierCurve ();

}
public Vector3 GetPoint (float t) {
return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t));
}

public void DrawBezierCurve ()  {
lr = GetComponent<LineRenderer> ();
lr.positionCount = 1;
lr.SetPosition(0, points[0]);

for (int i = 1; i < numPoints+1; i++) {
    float t = i / (float)numPoints;
    lr.positionCount = i+1;
    lr.SetPosition(i, GetPoint(t));
}
}

public Vector3 GetVelocity (float t) {
return transform.TransformPoint(
    Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position;
}

public Vector3 GetDirection (float t) {
return GetVelocity(t).normalized;
}
}

BezierCurveEditor:
[CustomEditor(typeof(BezierCurve))]
public class BezierCurveEditor : Editor {

private BezierCurve curve;
private Transform handleTransform;
private Quaternion handleRotation;

private const int lineSteps = 10;

private const float directionScale = 0.5f;

private void OnSceneGUI () {
curve = target as BezierCurve;
handleTransform = curve.transform;
handleRotation = Tools.pivotRotation == PivotRotation.Local ?
    handleTransform.rotation : Quaternion.identity;

Vector3 p0 = ShowPoint(0);
Vector3 p1 = ShowPoint(1);
Vector3 p2 = ShowPoint(2);
Vector3 p3 = ShowPoint(3);

Handles.color = Color.gray;
Handles.DrawLine(p0, p1);
Handles.DrawLine(p2, p3);
Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);

curve.DrawBezierCurve ();

if (GUI.changed) {
    curve.DrawBezierCurve ();
    EditorUtility.SetDirty( curve );
    Repaint();
}

}

private void ShowDirections () {
Handles.color = Color.green;
Vector3 point = curve.GetPoint(0f);
Handles.DrawLine(point, point + curve.GetDirection(0f) * directionScale);
for (int i = 1; i <= lineSteps; i++) {
    point = curve.GetPoint(i / (float)lineSteps);
    Handles.DrawLine(point, point + curve.GetDirection(i / (float)lineSteps) * directionScale);
}
}

private Vector3 ShowPoint (int index) {
Vector3 point = handleTransform.TransformPoint(curve.points[index]);
EditorGUI.BeginChangeCheck();
point = Handles.DoPositionHandle(point, handleRotation);
if (EditorGUI.EndChangeCheck()) {
    Undo.RecordObject(curve, "Move Point");
    EditorUtility.SetDirty(curve);
    curve.points[index] = handleTransform.InverseTransformPoint(point);
}
return point;
}
}

BezierPair:
public class BezierPair : MonoBehaviour {

public GameObject bez1;
public GameObject bez2;

public void setupCurves()   {
    bez1 = GameObject.Find("Bez1");
    bez2 = GameObject.Find("Bez2");
}
}

BezierPairEditor:
[CustomEditor(typeof(BezierPair))]
public class BezierPairEditor : Editor {

private BezierPair bezPair;

 public override void OnInspectorGUI()
{
    bezPair = target as BezierPair;

    if (bezPair.bez1.GetComponent<BezierCurve>().points[0] != bezPair.bez2.GetComponent<BezierCurve>().points[0])
    {
        Vector3 assignPoint0 = bezPair.bez1.GetComponent<BezierCurve>().points[0];
        bezPair.bez2.GetComponent<BezierCurve>().points[0] = assignPoint0;

    }
     if (GUI.changed)
    {

        EditorUtility.SetDirty(bezPair.bez1);
        EditorUtility.SetDirty(bezPair.bez2);
        Repaint();
    }
}

A: EDITED:
I dont think you'll need your BezierPair class. I suggest you to add a reference to the other BezierCurve object you want to "pair" as a public field on the BezierCurve class (paired). That other curve will get "paired" with this curve. Once paired, the constraints on the movement may apply. You can control the desired behaviors with the 3 public bool fields behavior1, behavior2 and behavior3.
Note#1: Instead of calling the method DrawBezierCurve from the Editor, I added the [ExecuteInEditMode] to the Component Class. This way, You don't mix responsibilities between the Component and the Editor: The BezierCurve component draws itself on the scene, while the BezierCurveEditor only manages edit logic, like applying the constraints and drawing the handlers.
BezierCurve:
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
[ExecuteInEditMode] // Makes Update() being called often even in Edit Mode
public class BezierCurve : MonoBehaviour
{

  public Vector3[] points;
  public int numPoints = 50;
  // Curve that is paired with this curve
  public BezierCurve paired;
  public bool behavior1; // check on editor if you desired behavior 1 ON/OFF
  public bool behavior2; // check on editor if you desired behavior 2 ON/OFF
  public bool behavior3; // check on editor if you desired behavior 3 ON/OFF
  LineRenderer lr;

  void Reset()
  {
    points = new Vector3[]
    {
      new Vector3(1f, 0f, 0f),
      new Vector3(2f, 0f, 0f),
      new Vector3(3f, 0f, 0f),
      new Vector3(4f, 0f, 0f)
    };
  }

  void Start()
  {
    lr = GetComponent<LineRenderer>();
  }

  void Update()
  {
    // This component is the only responsible for drawing itself.
    DrawBezierCurve();
  }

  // This method is called whenever a field is changed on Editor
  void OnValidate()
  {
    // This avoids pairing with itself
    if (paired == this) paired = null;
  }

  void DrawBezierCurve()
  {
    lr.positionCount = numPoints;
    for (int i = 0; i < numPoints; i++)
    {
      // This corrects the "strange" extra point you had with your script.
      float t = i / (float)(numPoints - 1);
      lr.SetPosition(i, GetPoint(t));
    }
  }

  public Vector3 GetPoint(float t)
  {
    return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t));
  }

  public Vector3 GetVelocity(float t)
  {
    return transform.TransformPoint(Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position;
  }

  public Vector3 GetDirection(float t)
  {
    return GetVelocity(t).normalized;
  }
}

Note#2: The desired behavior were coded inside the handler drawing methods, so you have access to Undo and other features.
Note#3: EditorUtility.SetDirty is considered obsolete since Unity 5.3 for marking objects as dirty for drawing, and should no-longer be used for modifying objects in scenes. Undo.RecordObject does the job.
BezierCurveEditor:
using UnityEngine;
using UnityEditor;

// This attribute allows you to select multiple curves and manipulate them all as a whole on Scene or Inspector
[CustomEditor(typeof(BezierCurve)), CanEditMultipleObjects]
public class BezierCurveEditor : Editor
{
  BezierCurve curve;
  Transform handleTransform;
  Quaternion handleRotation;
  const int lineSteps = 10;
  const float directionScale = 0.5f;

  BezierCurve prevPartner; // Useful later.

  void OnSceneGUI()
  {
    curve = target as BezierCurve;
    if (curve == null) return;
    handleTransform = curve.transform;
    handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity;

    Vector3 p0 = ShowPoint(0);
    Vector3 p1 = ShowPoint(1);
    Vector3 p2 = ShowPoint(2);
    Vector3 p3 = ShowPoint(3);

    Handles.color = Color.gray;
    Handles.DrawLine(p0, p1);
    Handles.DrawLine(p2, p3);
    Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);

    // Handles multiple selection
    var sel = Selection.GetFiltered(typeof(BezierCurve), SelectionMode.Editable);
    if (sel.Length == 1)
    {
      // This snippet checks if you just attached or dettached another curve,
      // so it updates the attached member in the other curve too automatically
      if (prevPartner != curve.paired)
      {
        if (prevPartner != null) { prevPartner.paired = null; }
        prevPartner = curve.paired;
      }
    }
    if (curve.paired != null & curve.paired != curve)
    {
      // Pair the curves.
      var partner = curve.paired;
      partner.paired = curve;
      partner.behavior1 = curve.behavior1;
      partner.behavior2 = curve.behavior2;
      partner.behavior3 = curve.behavior3;
    }
  }

  // Constraints for a curve attached to back
  // The trick here is making the object being inspected the "master" and the attached object is adjusted to it.
  // This way, you avoid the conflict of one object trying to move the other.
  // [ExecuteInEditMode] on component class makes it posible to have real-time drawing while editing.
  // If you were calling DrawBezierCurve from here, you would only see updates on the other curve when you select it
  Vector3 ShowPoint(int index)
  {
    var thisPts = curve.points;
    Vector3 point = handleTransform.TransformPoint(thisPts[index]);
    EditorGUI.BeginChangeCheck();
    point = Handles.DoPositionHandle(point, handleRotation);
    if (EditorGUI.EndChangeCheck())
    {
      if (curve.paired != null && curve.paired != curve)
      {
        Undo.RecordObjects(new Object[] { curve, curve.paired }, "Move Point " + index.ToString());
        var pairPts = curve.paired.points;
        var pairTransform = curve.paired.transform;
        switch (index)
        {
          case 0:
            {
              if (curve.behavior1)
              {
                pairPts[0] = pairTransform.InverseTransformPoint(point);
              }
              break;
            }
          case 1:
            {
              if (curve.behavior2)
              {
                var p1 = handleTransform.TransformPoint(thisPts[1]);
                pairPts[1] += pairTransform.InverseTransformVector(point - p1);
              }
              break;
            }
          case 2:
            {
              if (curve.behavior3)
              {
                var p0 = handleTransform.TransformPoint(thisPts[0]);
                var p3 = handleTransform.TransformPoint(thisPts[3]);
                var reflect = Vector3.Reflect(p3 - point, (p3 - p0).normalized);
                pairPts[2] = pairTransform.InverseTransformPoint(p3 + reflect);
              }
              break;
            }
          default:
            break;
        }
      }
      else
      {
        Undo.RecordObject(curve, "Move Point " + index.ToString());
      }
      thisPts[index] = handleTransform.InverseTransformPoint(point);
    }
    return point;
  }
}

For have it working, reference one BezierCurve to another's paired field through inspector, and set ON/OFF the behaviors you want.
Tips: tinker the properties of the LineRenderer to get cool gradients or width variation (like a brush stroke). If you have a cusp node and want it to look continuous, increase the value of End Cap Vertices on the Line Renderer. Use Sprites-Default as Material, for 2D.

A:
I tried solving 1. in the code below but the position for the second
  curve wouldn't update without my selecting BezierPair in the hierarchy
  window

This is because you are using OnInspectorGUI() callback inside your BezierPairEditor class. It is only executed when the inspector of BezierPairEditor is shown on your editor window. Thus if you do not click on the GameObject with the BezierPair component, the BezierPair's inspector is not shown, and the callback does not trigger.
Instead, use the EditorApplication.update delegate. Inside your BezierPairEditor class:
void OnEnable() {
    EditorApplication.update += OnUpdate; //Register to the update callback
}

void OnUpdate() {
    //Implement your code to update positions here
}

Secondly, try caching your BezierCurve references. This is because you don't really want to run GetComponent inside every update loop, as it is costly. Again, inside your BezierPairEditor class (I will omit the code above for clarity, merge it yourself):
BezierCurve bez1C;
BezierCurve bez2C;

void OnEnable() {
    BezierPair pair = target as BezierPair;
    bez1C = pair.bez1.GetComponent<BezierCurve>();
    bez2C = pair.bez2.GetComponenet<BezierCurve>();
}

void OnUpdate() {
    //Do something with bez1C and bez2C here
}

Finally, to solve points 1 to 3, since you did not specify, I shall assume that you are moving bez1 manually, and bez2 should follow. In the case where either one can be moved manually and the other should follow, I would recommend you to implement an isChanged check in your BezierCurve class. Then in your BezierPairEditor class, you can check which one has moved, and update the other one accordingly.
Inside BezierPairEditor class (again, I will omit the code above for clarity, merge it yourself):
Vector2 bez1CPrev1;

void OnEnable() {
    bez1CPrev1 = bez1C.points[1];

    //Ensure that they have the same starting point
    //Either you shift just points[0] of bez2 to be the same as bez1, or you shift every point. Implement this yourself.
}

void OnUpdate() {
    Vector2 disp = bez1C.points[1] - bez1CPrev1;

    //1.
    bez2C.points[0] = bez1C.points[0];

    //2.
    bez2C.points[1] = bez2C.points[1] + disp;

    //3. Here, we are gonna use Vector2.Reflect(). Why?
    //Imagine throwing a ball from newP2(curve1) to P3(curve1).
    //If the 'surface' that the ball hits has a normal of P0(curve1)-P3(curve1), you will have the ball bounce back to reach newP2(curve2).
    //Effectively: newP2(curve2) = P3(curve1) + [newP2(curve2) - P3(curve1)]. The term in the square brackets, we will do it with Vector2.Reflect().
    bez2C.points[2] = bez1C.points[3] + Vector2.Reflect(bez1C.points[3] - bez1C.points[2], (bez1C.points[0] - bez1C.points[3]).normalized);

    //Draw your bezier curve etc. here

    bez1CPrev1 = bez1C.points[1];
}


text:
Q: convert output string to map with golang Get the output as
 {
   ARN: "arn:aws:secretsmanager:us-east-2:xxxx:secret:team_dev-Xhzkt6",
   CreatedDate: 2018-07-05 06:50:07 +0000 UTC,
   Name: "team_dev",
   SecretString: "{\"password\":\"test\"}",
   VersionId: "6b65bfe4-7908-474b-9ae6-xxxx",
   VersionStages: ["AWSCURRENT"]
 }

Try to get the value as map with the key SecretString
d.Set("secret_string", output.SecretString)

How can I get it as Schema TypeMap?
With jq, I can easily get it, but not sure how to do this in golang.
Updates
Thanks, @mkopriva
in the aws sdk (github.com/aws/aws-sdk-go/service/secretsmanager/api.go), output (GetSecretValueOutput) is defined as type:"structure"
type GetSecretValueOutput struct {
        _ struct{} `type:"structure"`

And thanks again to provide a test code, I will try it.
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    secretString := "{\"password\":\"test\"}"

    sec := map[string]interface{}{}
    if err := json.Unmarshal([]byte(secretString), &sec); err != nil {
        panic(err)
    }
    fmt.Println(sec)
}

Golang Playground Try Here

A: @mkopriva
Thanks, please answer this question, so I can vote and accept it.
With your sample code, I did fix the issue.
-       d.Set("secret_string", output.SecretString)
+       var sec map[string]interface{}
+       if err = json.Unmarshal([]byte(*output.SecretString), &sec); err != nil {
+               return err
+       }
+       d.Set("secret_string", sec)


text:
Q: SQL Query to Display Count of Total I've got a very complex query that joins eight (8) different tables.
For the sake of this question, though, I'll simplify it with this type of structure:
create table table1(PacketID int, RequestID int, EmpID int, PartNo varchar(20))

insert into table1 values
 (1 , 1, 132, 'abc123'),
 (1 , 2, 132, 'abc456'),
 (1 , 3, 132, 'def123'),
 (1 , 4, 132, 'def456'),
 (2 , 5, 228, 'xyz123'),
 (3 , 6, 239, 'xyz321'),
 (3 , 7, 239, 'aaa000')

This type of table creates the following output:
|_P_|_R_|_Emp_|_PartNo_|
|_1_|_1_|_132_|_abc123_|
|_1_|_2_|_132_|_abc465_|
|_1_|_3_|_132_|_def123_|
|_1_|_4_|_132_|_def456_|
|_2_|_5_|_228_|_xyz123_|
|_3_|_6_|_239_|_xyz321_|
|_3_|_7_|_239_|_aaa000_|

I put together a fiddle of it here: http://www.sqlfiddle.com/#!3/a3ce4/1
I was told they don't really need this PacketID or RequestID, but what they do need is something that shows how many requests are in a packet and what request number of that packet needs attention.
I will still need the PacketID and RequestID values in order to make changes to the data.
So, I want to add a column to the table above to be something like this:
|_P_|_R_|_ReadAs_|_Emp_|_PartNo_|
|_1_|_1_|_1 of 4_|_132_|_abc123_|
|_1_|_2_|_2 of 4_|_132_|_abc465_|
|_1_|_3_|_3 of 4_|_132_|_def123_|
|_1_|_4_|_4 of 4_|_132_|_def456_|
|_2_|_5_|_1 of 1_|_228_|_xyz123_|
|_3_|_6_|_1 of 2_|_239_|_xyz321_|
|_3_|_7_|_2 of 2_|_239_|_aaa000_|

How exactly would I go about doing that?
If you just want to feel my pain and see the complete view defined on my SQL Server, here it is:
SELECT P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID,
  EI.FIRSTNAME + ' ' + EI.LASTNAME AS Employee, P.DateStamp,
  RQ.Description AS RequestType, L.Description AS Line, R.PartNo,
  R.Workorder, R.Qty, RZ.Description AS ReasonType, R.MTF,
  A.StatusID, S.Description AS Status, A.EmpID AS Stator,
  A.DateStamp AS Stated
FROM dbo.Packet AS P
  LEFT OUTER JOIN dbo.Request AS R ON R.PacketID = P.ID
  INNER JOIN dbo.Action AS A ON R.ID = A.RequestID
  LEFT OUTER JOIN dbo.Action AS A2 ON A.RequestID = A2.RequestID
         AND (A.DateStamp < A2.DateStamp OR
         A.DateStamp = A2.DateStamp AND A.RequestID < A2.RequestID)
  INNER JOIN CPAPP.AIO_Test_Results.dbo.EmployeeInfo AS EI ON A.EmpID = EI.COUNT
  INNER JOIN dbo.RequestType AS RQ ON R.RequestTypeID = RQ.ID
  INNER JOIN dbo.Line AS L ON R.LineID = L.ID
  INNER JOIN dbo.ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
  INNER JOIN dbo.Status AS S ON A.StatusID = S.ID
WHERE (A2.RequestID IS NULL)

A: Rather than just giving you the entire answer, I'll try to explain how to create the answer yourself.
To get the consecutive sequence numbers have a look at ROW_NUMBER. You can provide a partition by (PacketID) and an order by (RequestId). This gets you the first number you need.
To get the counts, if you were using SQL Server 2012 you could use COUNT with a partition. On older versions of SQL Server you will have to use a JOIN and GROUP BY or a subselect.
This query demonstrates the principles using the subselect approach:
SELECT
    PacketID,
    RequestID,
    EmpID,
    PartNo,
    ROW_NUMBER() OVER (PARTITION BY PacketID ORDER BY RequestID),
    (SELECT COUNT(*) FROM table1 AS T2 WHERE T1.PacketId = T2.PacketId)
FROM table1 AS T1

http://www.sqlfiddle.com/#!3/a3ce4/8
To get the exact format you requested you just need to convert the integers to strings and concatenate them. I'll leave this for you to do, but here's a few hints.

*

*CAST and CONVERT

*+ (String Concatenation)

A: As @MarkByers mentioned, row_number() will be especially helpful here, and I've added a correlated subquery to get the count per Packet:
select PacketID, RequestID
    , cast(RowNumber as varchar(11)) + ' of ' + cast(PacketCount as varchar(11)) as ReadAs
    , EmpID, PartNo
from (
    select PacketID, RequestID, EmpID, PartNo
        , row_number() over (partition by PacketID order by RequestID) as RowNumber
        , (select count(*) from table1 where PacketID = t.PacketID) as PacketCount
    from table1 as t
) as z


text:
Q: How to use switch case in selenium to test several web element in a page? i have a webpage with several element to be tested.
They are more than 100 and i could not write 100 code to test one element.
Is it possible to use switch case to test the element i want and not all.
For example here i have 3 tests to be executed, what i want is to test only Test1 and Test2, how can i do this using switch case in java, because i have more than 100 tests to be executed, i want to use only one code.
Thank you
 //TEST1
    try {
        driver.findElement(By.xpath(CmpList._google)).isDisplayed();
        System.out.println("Google Tab exists");
        driver.findElement(By.xpath(CmpList._google)).click();

        } catch (NoSuchElementException e) {
        System.out.println("TEST FAILED--Google Tab element does not exist");
        } finally {
        System.out.println("Continue");
        }

    //TEST2
        try {
        driver.findElement(By.xpath(CmpList._radio)).isDisplayed();
        System.out.println("Radio Tab element exists");
        driver.findElement(By.xpath(CmpList._radio)).click();

        } catch (NoSuchElementException e) {
        System.out.println("TEST FAILED--Radio Tab element does not exist");
        } finally {
        System.out.println("Continue");
        }

 //TEST3
    try {
        driver.findElement(By.xpath(CmpList._yahoo)).isDisplayed();
        System.out.println("Google Tab exists");
        driver.findElement(By.xpath(CmpList._yahoo)).click();

        } catch (NoSuchElementException e) {
        System.out.println("TEST FAILED--Yahoo Tab element does not exist");
        } finally {
        System.out.println("Continue");
        }

A: int[] testsToTest = {1,2, 45, ...};
int currentTest;
for(int i = 0; i < testsToTest; i++){
    currentTest = testsToTest[i];
    Switch (currentTest){
     case 1:
        //your first test
        break;
     case 2:
        //second test
        break;
     ...
     case 100;
        //100th test
        break;
     default: System.out.println("unknown test");
    }
}

That'll at least get you off the ground. There's definitely a nicer way to write this here, I shutter to think how long your file will become. perhaps you could use a more generic method since you're basically testing element x, and either clicking x or saying "x failed". Consider having a map of test numbers and xpaths. for example:
public boolean testElement(String xpath){
    try {
            WebElement element = driver.findElement(By.xpath(xpath)).isDisplayed();
            element.click();
    } catch (NoSuchElementException e) {
            System.out.println("TEST FAILED--element with xpath " + xpath + " does not exist");
    } finally {
            System.out.println("Continue");
    }
}

And then you could have a hashmap of testNumbers and their xpath. Then it would just be a matter of iterating over the list as above, but instead of the switch, it would just be
testElement(testMap.get(testToTest[i]))

A: As far as I can see the only thing that changes is the XPath and the message you are printing.
It's not clear from your code, but if you're not using a test framework like JUnit or TestNG, then you should be.
JUnitParams is a good candidate for this as it offers a way to pass a collection of parameters to a test method and execute it many times. Each execution is treated as a separate test, without the need to write repetitive code. If the first test fails, it will continue to run the other tests.
One example usage (there are many options):
@Test
@Parameters({
        CmpList._radio,
        CmpList._yahoo,
        .... })
public void shouldFindElement(String xpath) {
    driver.findElement(By.xpath(xpath)).isDisplayed();
    driver.findElement(By.xpath(CmpList._radio)).click();
}

Personally, I don't think you should catch the Exception as is not expected. I also think that you print statements introduce noise.


text:
Q: Complexity of Random Delaunay Triangulation in 3D My question:

Is the number of cells in a three-dimensional Poisson-Delaunay triangulation with $n$ vertices $\mathcal O(n)$ with probability one?

which is equivalent to the question

Is the number of Voronoi vertices in a three-dimensional Poisson-Voronoi tessellation with $n$ generators $\mathcal O(n)$ with probability one?

To formulate the question more mathematically, in terms of finite point configurations, denote

*

*$Del(\gamma)$ the Delaunay triangulation of the (finite) point configuration $\gamma$,

*$\#Del(\gamma)$ denotes the number of tetrahedra in $Del(\gamma)$,

*$\Phi$ homogenous Poisson point process, and

*$\Phi|_B$ its restriction to a bounded Borel set $B$.
Then the question is whether there exists a constant $C>0$ such that
$$P(\# Del(\Phi|_B) \leq C \Phi(B)) = 1 $$
Alternatively the bound could be stochastic in that
$$P(\# Del(\Phi|_B) \leq C \Phi(B)) \to 1 \text{ as } \#Del(\Phi|_B)\to \infty$$

My thoughts on the question:
On one hand, it is well known that the complexity 3d Delaunay triangulation is $\mathcal O(n^2)$ in general.
However, as noted in (1), the only know examples attaining this complexity are from point distributions on one-dimensional curves such as the moment curve. Furthermore, the expected complexity of Poisson-Delaunay distributed in a cube is $\mathcal O(n)$ (e.g. (2)). In (3), Jeff Erickson goes as far as saying that

For all practical purposes, three-dimensional Delaunay triangulations appear to have linear complexity.

This leads me to the question whether it is in fact almost surely true that a three dimensional Poisson-Delauany triangulation has $\mathcal O(n)$ cells. I haven't been able to find any reference on this fact, thought. I'll be grateful for a reference showing this statement or a counterexample.

Possible proof/counterexample strategies.
In (3) and (4), Erickson proves some bounds between the complexity of the Delaunay triangulation and the spread $\Delta$ - the ratio between the longest and shortest pairwise distance. This gives some chance for the complexity to be continuous in the sense of moving points (since spread is).
Perhaps spread could be used to prove the statement, or, perhaps we could allow the points on the moment curve to "wiggle" around, thus creating a class of configurations with have non-zero probability with respect to the Poisson process, while retaining the super-linear complexity.

References

*

*1: Nina Amenta, Dominique Attali, and Olivier Devillers. 2007.
Complexity of Delaunay triangulation for points on lower-dimensional
polyhedra

*2: R. Dwyer, The expected number of k-faces of a Voronoi
diagram, Computers Math. Applications 26 (5) (1993)

*3: Jeff Erickson. 2001. Nice point sets can have nasty Delaunay triangulations. In Proceedings of the seventeenth annual symposium on Computational geometry (SCG '01), Diane L. Souvaine (Ed.). ACM, New York, NY, USA, 96-105.

*4: Jeff Erickson. 2002. Dense point sets have sparse Delaunay triangulations: or "…but not too nasty". In Proceedings of the thirteenth annual ACM-SIAM symposium on Discrete algorithms (SODA '02). Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 125-134.

A: Yes, at least for periodic boundary conditions so we don't have to worry about what happens near the boundary. See
Dwyer, Rex A.
Higher-dimensional Voronoĭ diagrams in linear expected time.
Discrete Comput. Geom. 6 (1991), no. 4, 343–367
Dwyer counts Voronoi vertices rather than Delaunay simplices but it's the same thing. He only actually proves that the expected number is linear, not that it's linear with high probability, but it's straightforward to convert an expected value into a high probability bound via the fact that far-enough parts of the Delaunay triangulation don't affect each other. See e.g. proof of Lemma 9 in
Bern, Marshall; Eppstein, David; Yao, Frances.
The expected extremes in a Delaunay triangulation.
Internat. J. Comput. Geom. Appl. 1 (1991), no. 1, 79–91.
https://www.ics.uci.edu/~eppstein/pubs/BerEppYao-IJCGA-91.pdf

A: You may gain some empirical insight from this exploration:

Tanemura, Masaharu. "Statistical distributions of Poisson Voronoi cells in two and three dimensions." FORMA-TOKYO- 18, no. 4 (2003): 221-247.
  PDF download.


text:
Q: Add y-axis labels to each facet_grid plot I have a plot that you can simply reproduce with
library(dplyr)
library(ggplot2)

tibble(x = sample.int(3, 1000, replace = T),
       y = sample(letters[1:3], 1000, replace = T),
       k = sample(LETTERS[4:6], 1000, replace = T)) %>%
  count(x,y,k) %>%
  ggplot(aes(k, n)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  facet_grid(x ~ y)

which gives something like the plot below (depends on random sampling):

I want to add y labels to each axis, but still be able to use facet_grid layout. Mostly beacause I need labels for each row of plots and not above them. In this case it might sound weird but in my data I have a 5x6 grid of plots and there are 10 labels on y axis. This would simplify readability of the whole plot.
I want to achieve plot like this:

A: You can achieve it using facet_wrap, but it changes the layout.
library(dplyr)
library(ggplot2)

tibble(x = sample.int(3, 1000, replace = T),
       y = sample(letters[1:3], 1000, replace = T),
       k = sample(LETTERS[4:6], 1000, replace = T)) %>%
  count(x,y,k) %>%
  ggplot(aes(k, n)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  facet_wrap(~ interaction(x, y), scales = "free_y")


text:
Q: How to get a specific character from index of a string in swift I am trying to build a Binary to Decimal calculator for the Apple Watch using Swift 4.
The code I am having trouble is this:
var i = 0
var labelInputInt = 0
let labelOutputString = "10010" // Random number in binary
let reverse = String(labelOutputString.reversed()) // Reversing the original string

while i <= reverse.count {
    let indexOfString = reverse.index(reverse.startIndex, offsetBy: i)

    if reverse[indexOfString] == "1" {
        labelInputInt += 2^i * 1
    }

    i += 1
}

I am using a while loop to get the index indexOfString and check if in the string reverse at the specific index it is equal with "1".
The problem is that I get a runtime error when the if statement is executed.
The error looks like this:
2  libpthread.so.0 0x00007fc22f163390
3  libswiftCore.so 0x00007fc22afa88a0 _T0s18_fatalErrorMessages5NeverOs12Stati
cStringV_A2E4fileSu4lines6UInt32V5flagstFTfq4nnddn_n + 96
4  libswiftCore.so 0x00007fc22afb3323
5  libswiftCore.so 0x00007fc22afdf9a2
6  libswiftCore.so 0x00007fc22aedca19 _T0SS9subscripts9CharacterVSS5IndexVcfg
+ 9
7  libswiftCore.so 0x00007fc22f591294 _T0SS9subscripts9CharacterVSS5IndexVcfg
+ 74139780
8  swift           0x0000000000f2925f
9  swift           0x0000000000f2d402
10 swift           0x00000000004bf516
11 swift           0x00000000004ae461
12 swift           0x00000000004aa411
13 swift           0x0000000000465424
14 libc.so.6       0x00007fc22d88d830 __libc_start_main + 240
15 swift           0x0000000000462ce9
Stack dump:
0.    Program arguments: /home/drkameleon/swift4/usr/bin/swift -frontend -inte
rpret tmp/XfwP0oM7FJ.swift -disable-objc-interop -suppress-warnings -module-na
me XfwP0oM7FJ
Illegal instruction (core dumped)

So, how can I get a specific character of a String and compare it with another character without getting this crash?

A: Your approach to get a specific character from a string is actually correct, there are two other problems in your code:

*

*The index i should run up to and excluding reverse.count.
This is conveniently done with the "half-open range" operator (..<).

*^ is the bitwise-xor operator, not exponentiation. Exponentiation is done with the pow() function, in your case
labelInputInt += Int(pow(2.0, Double(i)))

or with the  "shift-left" operator << if the base is 2.
So this would be a working variant:
for i in 0 ..< reverse.count {
    let indexOfString = reverse.index(reverse.startIndex, offsetBy: i)
    if reverse[indexOfString] == "1" {
        labelInputInt += 1 << i
    }
    i += 1
}

But you can simply enumerate the characters of a string in reverse order instead of subscripting (which is also more efficient):
let binaryString = "10010"
var result = 0
for (i, char) in binaryString.reversed().enumerated() {
    if char == "1" {
        result += 1 << i
    }
}
print(result)

Even simpler with forward iteration, no reversed() or << needed:
let binaryString = "10010"
var result = 0
for char in binaryString {
    result = 2 * result
    if char == "1" {
        result += 1
    }
}
print(result)

Which suggests to use reduce():
let binaryString = "10010"
let result = binaryString.reduce(0) { 2 * $0 + ($1 == "1" ? 1 : 0) }
print(result)

But why reinvent the wheel? Just use init?(_:radix:) from the Swift standard library (with error-checking for free):
let binaryString = "10010"
if let result = Int(binaryString, radix: 2) {
    print(result)
} else {
    print("invalid input")
}


text:
Q: String representation of matplotlib figure for doctests I am writing doctests for my code that generates some matplotlib figure, I was wondering if there is a way to print the figure in a string representation -- something that displays elements in the figure (lines, points, etc). For example, something like the following:
>>> plt.plot([1,2,3], label="line 1")
>>> plt.plot([3,2,1], label="line 2")
>>> fig = plt.gcf()
>>> print fig
<Figure>
    <Line label='line 1'>
    <Line label='line 2'>


text:
Q: ¿Porque solo se ejecuta una vez mi consulta la hora de recorrer una tabla? php mysql Estoy armando una pagina que administra alumnos y sus asistencias, ambos asociados por una id idéntica. Mi lógica seria recorrer la primera tabla (alumnos) como un vector y luego recorrer la segunda tabla. Con el id obtenido de alumnos + el id obtenido de asistencias, hacer un if para confirmar si las asistencias pertenece al alumno, recorriendo varias veces y mostrando el contenido. Pero mi problema viene que el recorrido de asistencias solo se hace 1 vez solo con el primer alumno, no con los demás
<?php
if (isset($_GET['id'])) {
} else {
?>

    <?php
    $que = "SELECT * FROM datos_a";
    $quer = "SELECT * FROM asistencia";
    $re2 = mysqli_query($con, $quer);

    $re = mysqli_query($con, $que);
    include("include/buscador3.php");
    if (isset($result)) {
        $re = $result;
    }
while ($row = mysqli_fetch_array($re)) {  //agarro 1 alumno
    while ($row2 = mysqli_fetch_array($re2)){  //recorro asistencias
        if ($row['id_alumno'] == $row2['id_a_asis']) {
        //compruebo si idA es igual a idAs
        ?>

                    <?php echo $row['nombre'] . " " . $row['apellido']; ?>

                    <?php echo $row['escuela']; ?>

                    <?php echo $row['grado']; ?>

                    <?php echo $row2['asis_tipo']; ?>

        <?php
        }
     }
   }
}
?>

Si pongo un echo debajo del primer while para fijarme si esta leyendo los alumnos, si lo hace (si  recorre) luego en el 2do while si pongo un echo, me aparecen las veces que se ejecuta. Pero luego de la 1ra vez que se ejecuto el 2do while, no vuelve a ejecutarse mas. el 1er while sigue hasta que se termine el vector

A: Creo que tu problema radica en que id_a_asis es el indice de la segunda tabla y no su clave Foranea (FK), los indices siempre coincidirán en el primer registro y dos WHILE también es poco eficiente, el resultado de la consulta lo resuelve MySQL sin problemas al ejecutar una consulta con un LEFT JOIN
ej:
SELECT d.* FROM datos_a d LEFT JOIN ON asistencia a ON d.id_alumno=a.id_alumno;

o:
SELECT a.* FROM asistencia a LEFT JOIN ON asistencia a ON d.id_alumno=a.id_alumno;

Donde a.id_alumno es al clave foránea, esta es una columna que establece la relación lógica entre las tablas donde almacenas los datos del alumno y la tabla en donde almacenas las asistencias.


text:
Q: Is throwing an exception a legal else statement? I am currently despairing over a supposedly simple task.
        protected Entry<K, V>[] entries;

        public V getOrThrow(K k) throws UnknownKeyException
        {
            for(Entry<K, V> i : entries)
            {
                if(i.getValue() != null)
                {
                    if(i.getKey().equals(k))
                    {
                        return i.getValue();
                    }
                    else throw new UnknownKeyException();
                }
                else throw new UnknownKeyException();

            }

        }

This method should check whether a value exists, then whether the associated key matches the passed parameter and then return the value. Otherwise, an exception is to be thrown. The value is of the type V. Now I get the error: "This method must return a result of type V". So I suppose not every case of the if statement is covered. Is this because of the exceptions? Are exceptions even legal else statements? Or what else could it be? Thanks a lot in advance!

A: You throw an exception before the whole for loop has been executed. I think your code should look like that.
public V getOrThrow(K k) throws UnknownKeyException {
    for(Entry<K, V> i : entries) {
        if(i.getValue() != null && i.getKey().equals(k)) {
            return i.getValue();
        }
    }
    throw new UnknownKeyException();
}

Also, f_puras pointed in the right direction: the entries variable could be empty, so you should check it before invoking that method.


text:
Q: How to automap a list to another list using automapper in my c# wpf dekstop app.
I have these 2 models:
public class A
{
    public string Field1 {get; set;}
    public string Field2 {get; set;}
}

public class B
{
    public string Field1 {get; set;}
    public string Field2 {get; set;}
}

I create a collection of Class A by populating via a db query so:
list<A> collectionA = DB.GetQueryResults();

I now want to 'transfer' this collection to Class B by using AutoMapper..
var configJobProfile = new MapperConfiguration(cfg => cfg.CreateMap<A, B>());
var mapperJobProfile = configJobProfile.CreateMapper();
collectionB = mapperJobProfile.Map<B>(collectionA);

But i get a mapping error which doe snot tell me much. So I assuming this approach is wrong?
How should I do this?
Thanks
Screen-Shot of Deprecated function:

A: You have set up a mapping from A -> B, but the map you are trying to perform is for a List of As -> List of Bs.
Set up a mapping for the lists and that should do the trick i.e.
var configJobProfile = new MapperConfiguration(cfg => cfg.CreateMap<List<A>, List<B>>());
var mapperJobProfile = configJobProfile.CreateMapper();
List<B> collectionB = mapperJobProfile.Map<List<B>>(collectionA);

A: using System;
using AutoMapper;

public class Foo
{
    public string A { get; set; }
    public int B { get; set; }
}

public class Bar
{
    public string A { get; set; }
    public int B { get; set; }
}

public class Program
{
    public static void Main()
    {
        Mapper.CreateMap<Foo,Bar>();

        var foo = new Foo { A="test", B=100500 };

        var bar = Mapper.Map<Bar>(foo);

        Console.WriteLine("foo type is {0}", foo.GetType());
        Console.WriteLine("bar type is {0}", bar.GetType());

        Console.WriteLine("foo.A={0} foo.B={1}", foo.A, foo.B);
        Console.WriteLine("bar.A={0} bar.B={1}", bar.A, bar.B);
    }
}

Here is link to the Tutorial
About depricated warning check answer of @Romi Petrelis Automapper says Mapper.Map is obsolete, global mappings?


text:
Q: How to truncate date in postgres? I am using below condition to truncate date in postgres
to_date(to_char(trunc(appointment_date),'YYYYMMDD')||appointment_end_time,''YYYYMMDDHH24:MI:SS')AS tq

How I can use this in postgres ?

A: Strange data typing, sometimes requires strange, looking at least, queries. Try (see fiddle)
date_trunc('day',appointment_date)
       + substr(appoinment_end,12)::interval

A: As your to_char() call uses the format 'HH24:MI:SS' for the "time" column, you can cast that column directly to a time value, e.g. using the :: operator: appointment_end_time::time.
To build a new timestamp from the date part of the appointment_date and the time value, just add them:
appointment_date::date + appointment_end_time::time

So first the timestamp is converted to a date (that does not have a time), and then the time value is added to that, which yields a timestamp.

Note that to_date() returns a date so your code would remove the just added time part again. You would need to use to_timestamp() if you really want a timestamp as the result.

To answer the question's title "how to truncate date in Postgres?" (which in reality refers to a timestamp not a date): you can either cast it to a date (see above) or you can use date_trunc() (not trunc()) with a unit to which it should be truncated. However, date_trunc returns a timestamp not a date value, so you couldn't add a time to the result.