text:
Q: Android alphabets section Listview like contacts app listview now can any one help me how to look my view something like this. please help me i am too confusing.

here my code:-------
phonebooklistview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/searchTxtBox"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="65dp"
        android:hint="@string/searchHintTxt"
        android:singleLine="true"
        android:drawableLeft="@android:drawable/ic_search_category_default"
        android:drawablePadding="0dp"
        android:text="" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fadingEdge="vertical"
        android:fastScrollEnabled="true"
        android:padding="2dp"
        android:layout_below="@+id/searchTxtBox" >
    </ListView>

    <TextView
        android:id="@+id/phoneBookEmptyView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:text="@string/phoneBookEmptyMsg"
        android:textColor="@color/white"
        android:layout_below="@+id/searchTxtBox"
        android:layout_marginTop="5dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

and in PhoneBookList.java file
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.phonebooklistview);

    listView = getListView();
    adapter = new ItemsAdapter(this);
    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);
    listView.setTextFilterEnabled(true);
    //listView.setFastScrollEnabled(true);
    listView.setOnItemLongClickListener(this);
    listView.setItemsCanFocus(false);
    listView.setEmptyView(findViewById(R.id.phoneBookEmptyView));
    registerForContextMenu(listView);

}

private class ItemsAdapter extends BaseAdapter implements SectionIndexer
{
    HashMap<String, Integer> alphaIndexer;
    String[] sections;
      private LayoutInflater inflater;
      String[][] items;

      public ItemsAdapter(Context context)
      {
          inflater = LayoutInflater.from(context);
          this.items = phoneBookDataArr;

            alphaIndexer = new HashMap<String, Integer>();
            int size = items.length;

            for (int x = 0; x < size; x++)
            {
                String name=items[x][2];
                String ch =  name.substring(0, 1);
                ch = ch.toUpperCase();
                alphaIndexer.put(ch, x);

                Log.e(TAG,"alphaIndexer="+ch);
            }

            Set<String> sectionLetters = alphaIndexer.keySet();
            ArrayList<String> sectionList = new ArrayList<String>(sectionLetters);
            Collections.sort(sectionList);
            sections = new String[sectionList.size()];
            sectionList.toArray(sections);
      }

      //@Override
      public View getView(final int position, View convertView, ViewGroup parent)
      {
    // here my custom listviewcontentview goes.
      }

      public int getCount()
      {
          return items.length;
      }

      public Object getItem(int position)
      {
          return position;
      }

      public long getItemId(int position)
      {
          return 0;
      }

      public int getPositionForSection(int section)
      {
          Log.e(TAG,"getPositionForSection="+section);
          return alphaIndexer.get(sections[section]);
      }

      public int getSectionForPosition(int position)
      {
          Log.e(TAG,"getSectionForPosition="+position);
          return 1;
      }

      public Object[] getSections()
      {
          Log.e(TAG,"getSections="+sections.length);
          for (String str : sections)
          {
            Log.e(TAG,str);
          }
          return sections;
      }
}

A: Adding a searchbar
1: Use EditText for the search bar
2: Register it to addTextChangedListener
3: Implement onTextChanged(...) method to keep track of the character sequence entered by the user   4: Fetch the currentSearchName using getText() method. Iterate over the contact list to find the matching searches. Store the matched results in a list and use Content Adapter to display the list.
Detailed implementation is provided in the following link
http://www.androidpeople.com/android-listview-searchbox-sort-items
Adding labels and sidebar:
1: To add a sidebar implement SectionIndexer in your ContentAdapter class
2: Iterate over the Contacts list to fetch the initials of all the names
3: Implement setSection(..) method to the set the labels
4: Implement getPositionForSection(..) to go the label corresponding to initials when user clicks on the sidebar.
Implementation of the SideBar can be found on the following link.
http://codelikes.blogspot.com/2012/04/android-alphabet-listview-like-contacts.html?


text:
Q: How to load the value from a nested_attribute's attached_file into an edit form so that the attachment is not deleted on update? I have a Paperclip attachment (a .gpx) on a Track, which belongs_to a Route.
My Route accepts_nested_attributes_for :track, and the Route new form receives the user's .gpx to create the Track model. This all works great for #create. However, if I go to the edit action, the form shows no file selected, and #update will delete the Track's attachment unless a file is reselected.
I think I need the form to reference the attached file when #edit is called, but I don't know how to do this. Help would be greatly appreciated!
The form partial looks like this:
= simple_form_for @route do |r|
  = r.simple_fields_for :track do |t|
    = t.input :gpx
  = r.input :title
  = r.input :description
  = r.button :submit

which produces this beneath the file field in the edit view
<input id="route_track_attributes_id" name="route[track_attributes][id]" type="hidden" value="33">

Inside the RoutesController
def route_params
  params.require(:route).permit(:title, :description, :distance, :total_ascent, track_attributes: [:gpx])
end

A: add :id and ':_destroy' in your permit params.
def route_params
  params.require(:route).permit(:title, :description, :distance, :total_ascent, track_attributes: [:gpx, :id, :_destroy])
end

Also you are input instead of file in your form.
= simple_form_for @route do |r|
  = r.simple_fields_for :track do |t|
  = t.file :gpx, as: :file
  = r.input :title
  = r.input :description
  = r.button :submit

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make the datetime column shown correctly on the ms excel? I was using below api to generate the excel file.
var ws2 = XLSX.utils.json_to_sheet(dataForSheet, {skipHeader: true});

In the createtime column, only the date was displayed by default. Only when I click the cell, the datetime will be displayed. How can I resolve this issue? I hope the time displayed as well.
I just tried dateNF property like below.
  var ws2 = XLSX.utils.json_to_sheet(dataForSheet, {skipHeader: true,dateNF: 'YYYYMMDD HH:mm:ss'});

I will make my date type column incorrectly like below. The date column should not include the 00:00:00.

A: All i did was looping through my DATA, and cast my date variable using the popular library Moment.js.
    const fileName = 'MyFile_' + moment().format("YYYY-MM-DD")+ '.xlsx';

    // FORMATING DATES
    for( var k of this.myJsonArray)
    {
        k.myDateVariable= moment(k.myDateVariable).lang('fr').format("YYYY-MM-DD")
    }
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.myJsonArray);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'test');
    XLSX.writeFile(wb, fileName);


text:
Q: How to remove part of URL Let's say my URL is this:
http://example.com/forum/index.php?topic=53.msg251#msg251

This part here, I can't figure out how to remove:
.msg251#msg251

I did try though, I'm not sure if I am even close to doing it right.
 $linkraw = $items->link;
 $linkpattern = '/^.msg247#msg247/';
 $link = preg_match($linkpattern, $linkraw);

What is the correct way of doing this? I am trying to learn.

A: String functions strrpos and substr are enough for this task. And its surely faster.
 $link = substr($linkraw, 0, strrpos($linkraw, "."))

Explanation:

*

*strrpos finds the position of . from the end of the string.

*substr extracts a sub string till the position of . found in previous step.

When this will work?
Works on http://example.com/forum/index.php?topic=53.msg251#msg251
Works on http://example.com/forum/index.php?topic=53.new#new
But not on http://example.com/forum/index.php?topic=53.msg251#msg251.new#new

A: If you want to remove, use preg_replace:
$link = preg_replace('/\..*?$/', '', $linkraw);

A: Quite simple using the http_build_url function (requires PECL pecl_http >= 0.21.0).
<?php
    $url = 'http://example/forum/index.php?topic=53.msg251#msg251';
    echo http_build_url($url, null, HTTP_URL_STRIP_FRAGMENT);
?>

A:
"preg_match() returns the number of times pattern matches. That will be
  either 0 times (no match) or 1 time because preg_match() will stop
  searching after the first match. preg_match_all() on the contrary will
  continue until it reaches the end of subject. preg_match() returns
  FALSE if an error occurred."

link
Preg_Match checks only if the pattern exists in the string. It doesn't remove something.
You can use str_replace() for replacing that part
$link = str_replace(".msg251#msg251", "", $linkraw);


text:
Q: Is there Any Way to Simplify this Function? I have a function that returns a string with coordinates and the direction that the object is looking at.
But I really don't like the length of the function and I'd like to shorten it. I don't know what I could do to shorten it. Can someone help me?
The Function looks like this:
public string Execute(string text)
{
    var letters = text.ToCharArray().ToList();

    foreach (var letter in letters)
    {
        if (letter == 'R')
        {
            switch(direction)
            {
                case "N":
                    direction = "E";
                    break;
                case "E":
                    direction = "S";
                    break;
                case "S":
                    direction = "W";
                    break;
                case "W":
                    direction = "N";
                    break;
            }
        }

        if (letter == 'L')
        {
            switch (direction)
            {
                case "N":
                    direction = "W";
                    break;
                case "E":
                    direction = "N";
                    break;
                case "S":
                    direction = "E";
                    break;
                case "W":
                    direction = "S";
                    break;
            }
        }

        if (letter == 'M')
        {
            switch (direction)
            {
                case "N":
                    positionY++;
                    break;
                case "E":
                    positionX++;
                    break;
                case "S":
                    positionY--;
                    break;
                case "W":
                    positionX--;
                    break;
            }
        }

        if (letter == 'B')
        {
            switch (direction)
            {
                case "N":
                    positionY--;
                    break;
                case "E":
                    positionX--;
                    break;
                case "S":
                    positionY++;
                    break;
                case "W":
                    positionX++;
                    break;
            }
        }
    }

    return $"{positionX}:{positionY}:{direction}";
}

This Text Down here is just a useless text so I can submit my Question because my code is too long and Stackoverflow recognizes the Question as mostly code so I have to write more text without the Code Brackets to be able to submit the Question. You don't have to read this Text because it has no purpose.

A: I realize OP may not be interested in an answer to this anymore, but I'll share my thoughts nonetheless.
Switch expressions were introduced in C# 8.0, and they may be used to simplify/shorten (parts of) your code.
The switch statements in the first two if loops of your function may be directly replaced with switch expressions. The replacement for the switch statement in the first if loop would be as follows:
if (letter == 'R')
{
    direction = direction switch
    {
        "N" => "E", // interpretation: if the current direction is "N", assign "E"
        "E" => "S",
        "S" => "W",
        "W" => "N",
        _ => direction // discard pattern to provide a default value in case there is no match
    };
}

The switch statement in the second if loop may be replaced in a similar fashion.

To shorten your code further, you could consider including case guards in your switch expressions.
But: When introducing case guards, reading and interpreting the switch expression generally requires more effort. As @Heinz Kessler comments above, "smart" coding for the sake of having fewer code lines is not worth sacrificing the readability and maintainability of the code for.
In case of interest/curiosity, here is a working DotNetFiddle example of how your code could be implemented using switch expressions with case guards. To achieve this, I have changed the logic in the Execute method. For readability (this may be a personal preference), changes such as variable renaming and introducing constants have also been made.

A: Try following :
           string text = "";
            var letters = text.ToCharArray().ToList();
            Dictionary<char, Dictionary<string, string>> dict = new Dictionary<char, Dictionary<string, string>>() {
                {'R', new Dictionary<string, string>() { { "N", "E" }, { "E", "S" }, { "S", "W" }, { "W", "N" }}},
                {'L', new Dictionary<string, string>() { { "N", "W" }, { "E", "N" }, { "S", "E" }, { "W", "S" }}},
                {'M', new Dictionary<string, string>() { { "N", "AY" }, { "E", "AX" }, { "S", "SY" }, { "W", "SX" }}},
                {'R', new Dictionary<string, string>() { { "N", "SY" }, { "E", "SX" }, { "N", "AY" }, { "N", "AX" }}}
            };
            string direction = "";
            int positionX = 0;
            int positionY = 0;

            foreach (var letter in letters)
            {
                string value = dict[letter][direction];
                switch (value)
                {
                    case "SX":
                        positionX--;
                        break;
                    case "SY":
                        positionY--;
                        break;
                    case "AX":
                        positionX++;
                        break;
                    case "AY":
                        positionY++;
                        break;
                    case "N":
                        direction = value;
                        break;
                    case "E":
                        direction = value;
                        break;
                    case "S":
                        direction = value;
                        break;
                    case "W":
                        direction = value;
                        break;
                }


text:
Q: An UU parser recognizing just the empty string input? I need a value of type Parser () which would succeed (and return ()) on empty (lenght 0) input, and fail in all other cases.
pSatisfy (const False) doesn't quite do what's required. pEnd doesn't even seem appropriate for this purpose.

pExact 0 pAscii might be the exact "by-definition" solution. Still doesn't seem to work:
ghci> runParser "<input>" (pSymbol "aaa" <|> pSymbol "bbb" <|> pExact 0 pAscii) ""
*** Exception: ambiguous parser?

A: It seems that the idea of uu-parsinglib it to be more declarative than e.g. parsec, so you just have pure ():
λ> runParser "<input>" (pSymbol "aaa" <|> pSymbol "bbb" <|> pure "") "aaa"
"aaa"
λ> runParser "<input>" (pSymbol "aaa" <|> pSymbol "bbb" <|> pure "") "bbb"
"bbb"
λ> runParser "<input>" (pSymbol "aaa" <|> pSymbol "bbb" <|> pure "") ""
""
λ> runParser "<input>" (pSymbol "aaa" <|> pSymbol "bbb" <|> pure "") "ccc"
"*** Exception: Failed parsing '<input>' :
Unexpected ''c'' at end.

And you need to structure your grammar in the way it doesn't need magical EOF symbol.


text:
Q: Using a class initiated in one method in another method I have a C# WPF app that every time the user opens a new file, the contents are displayed in a datagrid.
public partial class MainWindow : Window
{
     public TabControl tc = new TabControl();

     public MainWindow()
     {
         InitializeComponents();
     }

     private FromFile_click(object sender, RoutedEventArgs e)
     {
         //gets information from file and then...

         if (numberOfFiles == 0)
         {
             masterGrid.Children.Add(tc);
         }
         TabItem ti = new TabItem();
         tc.Items.Add(ti);

         DataGrid dg = new DataGrid();
         ti.Content = dg;

         dg.Name = "Grid"+ ++numberOfFiles;

         dg.ItemSource = data;
     }

     private otherMethod(object sender, RoutedEventArgs e)
     {

     }
}

My question is, how do I use the data in dg in the method "otherMethod"? Also, is it possible to change the parent of dg from the method "otherMethod"?

A: Assuming you're not calling otherMethod within FromFile_Click, you need to make it an instance variable - like your TabControl is, except hopefully not public. I'm assuming otherMethod is actually meant to handle an event of some kind, rather than being called directly.
Now this is assuming that you want one DataGrid per instance of MainWindow, associated with that window. If that's not the case, you'd need to provide more information.

A: You have to pass it as a parameter to the other method otherMethod or make it a member variable.

A: set the  DataGrid dg as a property instead of declaring inside the FromFile_click.
This way when you assign "dg" it will work from any other method (few restrictions apply)


text:
Q: Set selected Kendo menu item with HtmlAttributes to hiddem form field i have a kendo menu that is bound to my form by the onclick event like this
@(Html.Kendo().Menu()
    .Name("MenuCreate")
    .Items(items =>
    {
        items.Add().Text("<<").Action("Index", "BSfune");
        items.Add().Text("New").HtmlAttributes(new{onclick = "getElementById('FormCreate').submit()", @id = "New"});
        items.Add().Text("Edit").HtmlAttributes(new { onclick = "getElementById('FormCreate').submit()", @id = "Edit" });
    })
    .Events(e => e.Select("select"))
)

and in my form i have a hiden field called FormmMode
@using (Html.BeginForm("Create", "BSfune", FormMethod.Post, new { id = "FormCreate" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

        <fieldset>
            <legend>@ViewBag.Title</legend>

                   (My form code)

                @Html.HiddenFor(model => model.FormMode, new { @id = "FormMode"})

        </fieldset>

}

i want to set my field form (FormMode) with the selected menuitem text "New" or "Edit".
I noticed that the onclick overrides the selected event. So.. It would be something like this


text:
Q: Make each column have the same width I have this GridLayout:
<android.support.v7.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    app:columnCount="3"
    app:rowCount="4">

    <FrameLayout
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnSpan="2"
        app:layout_columnWeight="2"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginStart="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnSpan="2"
        app:layout_columnWeight="2"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="big text changing"
            android:textColor="@android:color/black" />

    </FrameLayout>

    <FrameLayout
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:gravity="start"
            android:padding="10dp"
            android:text="some text"
            android:textColor="@android:color/white" />

    </FrameLayout>

</android.support.v7.widget.GridLayout>

Which is producing this:

Noticed the last row? The middle column his larger because of his bigger text. This TextView layout_height is set to wrap_content, and the parent FrameLayout layout_columnWeight is set to 1. So why the FrameLayout his geting larger instead of the TextView grow in height?
I want all the columns to have the same width, despite the text inside. If the text is somehow big, than the TextView should increase his height inside the FrameLayout.
His there any way to achieve this? What is wrong with my layout?

A: Add android:layout_width="0dp" to the big text frame to bring its width in line using your defined weight. You may need to do the same for the other frame layouts.


text:
Q: Определение нативных double констант Увидел такие строки в метаданных System:
public const Double NaN = 0D / 0D;
public const Double NegativeInfinity = -1D / 0D;
public const Double PositiveInfinity = 1D / 0D;

И у меня вопрос, почему 0/0 не дает исключение, чем NaN будет отличаться от 0?
Аналогично и с инфинити.


text:
Q: How use User Delegation SAS Or Azure RBAC to grant permissions on storage account containers for azure active directory B2C users (Custom Domain)? I have created a login module using Azure AD B2C. B2C tenant have a custom login page as well as a custom domain.
I have also created an Azure Blob Storage Container for hosting HTML files of my website.
I have a requirement that only the logged-in user access HTML files, and no one else should be allowed to access the files.
Can anyone please help me understand how I can provide access to html files to the logged-in users?
[I know that a similar question has already been answered on StackOverflow. In the answer, it was mentioned to create external users on Azure Active Directory and provide access to users through Active Directory. The only issue with this method is that the custom domain can't be used for the login page of Active Directory. I wanted to add this question to the comment of the existing query, but because of low reputation, I'm not able to add a comment to that question]

A: •   You can assign the 'Reader' role for all the users who are logging in with the Azure AD credentials to read and access the contents of the blob storage. Also, if you have enabled access to the blob storage account keys via the shared key authorization, shared key access must be permitted for the storage account during its provisioning.
•   Also, you can assign the 'Reader and Data Access' role to all the users who will be accessing the login page and accessing the blob storage contents as they will be able to view storage account resources, but not modify them. It does not provide read permissions to data in Azure Storage, but only to account management resources. The Reader role is necessary so that users can navigate to blob containers in the Azure portal.
•   Thus, if you want users with increasing levels of access to the blob storage, you can assign the 'Storage account contributor', 'ARM Contributor role' and 'ARM Owner role' in increasing order respectively. Also, if you want external users to access the blob storage content for a limited time duration or continuous monitored manner, you can share the SAS URI or access keys accordingly. Also, once you assign the roles according to requirement, you can generate SAS URI access tokens also for additional security.
Please refer the below links for more information: -
https://learn.microsoft.com/en-us/azure/storage/common/shared-key-authorization-prevent?tabs=portal
https://learn.microsoft.com/en-us/azure/storage/blobs/authorize-data-operations-portal


text:
Q: Dealing with the huge number of Boost header files Is there a way to drastically reduce the number of header files needed for Boost?
Ideally, I'm asking the Boost folks to find a way to make their product smaller.  But in the meantime, is there a way to include Boost, but not have several thousand header files to deal with?
Is there a C++ mechanism to "bundle" thousands of header files into a single "package" and just check that single file into source control?
I guess the problem here is source control  Doing a diff, svn status and svn checkout is so slow with all these files to deal with.

A: I'd recommend putting your third-party libraries in a separate repository. Boost is template heavy, so there is a pretty good reason for them not to bundle their headers. Trying to include bundled Boost headers would move your "wasted" time from version control into your build times. That doesn't really scale. I would refuse to use Boost if you tried to do that to my Boost headers.

A: Boost offers a tool called BCP. BCP allows you to extract subsets of Boost.
It can also analyze your source tree and extract only the Boost components that your source tree is using.

A: ccache can be a life saver for speeding up preprocessor heavy compilations.

A: There's no way to package all in one file (except versioning an archive, but it's not great practice nor practical at all). On a side note, Subversion is known to be slow at checking out thousands of small files such as Boost headers, so maybe you can consider switching to a higher-performance SCM like Git.
You'll be interested in BCP, a Boost tool that analyzes your source and copies the Boost headers you use into a separate directory. This helped a lot to reduce third-party files and was mostly right in my case (I just had to add a few ones to the list).

A: Not what you asked, but here's a way to fix you problem. As I understand it, you are adding the Boost files to your code control repository. Why? They are not part of your project per se; they are not under your control.
Here's how I structure my projects such that I don't run into that kind of problem. Everything is added to source control, except the include and lib folders, as mentioned below. (I only show the relevant parts of my directory tree.)

*

*/

*

*src — includes my own source files and headers

*ext — external dependencies (such as boost)

*

*boost-1-46-1

*

*Download.txt — includes link where you can download the correct version from

*include — this is not added to source control

*lib — this neither


text:
Q: Java GeoTools - Getting CRS from SRID I might confuse between two things, but I need to do some calculation on my polygons (distance, area etc.). Using the WKBReader, I'm getting the geo:
WKBReader wkbReader = new WKBReader();
byte[] a = results.getBytes(8);
Geometry geo = wkbReader.read(results.getBytes("st_asbinary"));

But I'm not getting it in EPSG:4326. I want to use GeoTools to do the transform. How do I get the CRS from the geo object? (look at the 3 question marks)
CoordinateReferenceSystem sourceCRS = ???
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");

MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
Geometry targetGeometry = JTS.transform(geo, transform);
Any help will be appreciated.

A: If a CRS value is set on the geo object then the appropriate method call is:
geo.getCoordinateReferenceSystem()

If it isn't set on the geometry then you'll need to find a suitable object to get it from.
The GeoTools Geometry CRS Tutorial has some examples (schema, world) and the GeoTools JavaDoc has a complete list of getCoordinateReferenceSystem() method declarations/implementations.


text:
Q: no implicit conversion of Symbol into Integer - working with param from URL Trying to convert a param included in the the URL into an integer, to operate with it within a Controller - The format of the URL is like http://localhost:3000/charges?data=149&email=email@gmail.com
The charges_controller.rb looks like:
class ChargesController < ApplicationController
  protect_from_forgery with: :null_session

  def new
  end

  def create

    @amount = {}
    @amount = params [:**data**][:email].map(&:to_i)
    @amount.save

    customer = Stripe::Customer.create(
      :email => params[:stripeEmail],
      :source  => params[:stripeToken]
    )

    charge = Stripe::Charge.create(
      :customer    => customer.id,
      :amount      =>  @amount,
      :description => 'Rails Stripe customer',
      :currency    => 'eur'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

end

And the params I can see in better_errors screen detect already the 'data' amount:
{"stripeToken"=>"asdfasdf", "stripeTokenType"=>"card", "stripeEmail"=>"email@gmail.com", "data"=>"149", "email"=>"email@gmail.com", "action"=>"create", "controller"=>"charges"}

In the live shell in better errors if I do params[:data].to_i it returns 149, but if I include it directly in the controller like:
@amount = {}
@amount = params [:data].to_i[:email]
@amount.save

it returns undefined method `to_i' for [:data]:Array
Tried also mapping them like:   @amount = params [:data][:email].map(&:to_i),same result "no implicit conversion of Symbol into Integer"

A: You should remove space while calling :data on your params hash from params [:data] to params[:data].


text:
Q: String was not recognized as Valid Datetime I have 2 textboxes where I have to add the Joining Date and Leaving Date.
Now When I add the joining date and leave the Leaving date blank and submit the form I get error as

String was not recognized as Valid Datetime

Here is my code for
cmd1.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = Convert.ToDateTime(txtdol.Text);

I dont know why this is giving error. Please help
UPDATE:
Textbox code:-
 <asp:TextBox ID="txtdol" CssClass="form-control" runat="server" ValidationGroup="AddNew" Enabled="true"></asp:TextBox>

A: Ensure you enter date in valid format in the textbox. best option is to use a date validator for the textbox and if the date formate entered is wrong you can display validation error rather than RTE.
here is the question for validation:
Date validation for a textbox
here is the available date format from MSDN:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

A: of course you get error for that . the error happening in
Convert.ToDateTime(txtdol.Text);

you are trying to convert something that is null , its like you say to compiler to compile this :
Convert.ToDateTime("");

it's emptry string and cannot be converted .
here are some options that you can consider of :

*

*Check if the textbox is not empty and the provided date is valid (client or server side)

*use DateTimePicker (like jquery ui datetimepicker)

*use this code instead of that at the end of that line
String.IsNullOrEmpty(txtdol.Text) ? DateTime.Now : Convert.ToDateTime(txtdol.Text)
if txtdol is null or empty it return the current datetime otherwise it convert the txtdol to datetime and return it .

A: Good way to input date to Textbox by user is using :
1- MaskedTextBox
  or
2- DateTimePicker.
Or
  if you want using textbox, you can use this code also to check empty values.
 DateTime? nullDateTime = null;
        cmd1.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = string.IsNullOrEmpty(txtdol.Text.Trim()) ? nullDateTime : Convert.ToDateTime(txtdol.Text.Trim())

and for validation textbox check this function:
private bool validateDate(TextBox arg1)
        {
            DateTime dt;
            bool valid1 = DateTime.TryParseExact(arg1.Text.Trim(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out dt);
            if (!string.IsNullOrEmpty(arg1.Text.Trim()) )
            {
                MessageBox.Show("Format Date is wrong! Currect format is(dd/MM/yyyy)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                arg1.Focus();
                return false;
            }
            return true;
        }

A: This error occures due to Invalid date format (empty or wrong format) enterd in textbox to fix the issue modify the code as below , use DateTime.ParsExact
cmd1.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = DateTime.ParsExact(txtdol.Text,"dd/MM/yyyy",System.Globalization.DateTimeStyles.AllowInnerWhite);

the second paramater can be changed to an array of format also.
Change the code as per your need

A: After getting so much errors, Did like this
 if (txtdol.Text == null || txtdol.Text == string.Empty)
                        {
                            cmd.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = DBNull.Value;
                        }
                        else
                        {
                            cmd.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = Convert.ToDateTime(txtdol.Text);
                        }

And it worked..!!


text:
Q: How to chain Promises and callback-style code I'm confused on how this chaining for promises work, I'm still fairly new to promises and js in general so excuse me
line three,   return user.findOne({email}).then((user) => {, i'm just confused about how returning this promise does anything since it returns a other promise inside the .then()
UserSchema.statics.findByCredentials = function(email, password){
  user = this;
  return user.findOne({email}).then((user) => {
      if (!user){
        return Promise.reject();
      }
      return new Promise((resolve, reject) => {
        bcrypt.compare(password, user.password, (err, res) => {
          if (res){
            resolve(user);
          }else{
            reject()
          }
        });
    });

  });
}

the findByCredentials model method being used in an express app
app.post("/users/login", (req, res) => {
  var body = _.pick(req.body, ["email", "password"]);
  User.findByCredentials(body.email, body.password).then((user) => {
    res.send(body)
  }).catch((e) => {
    res.send("!");
  })

A simpler example I just created, this part

return plus(1).then((res) => {

return new Promise((resolve, reject) => {
    is the problem i'm having trouble understanding

function plus(a) {
  return new Promise((resolve, reject) => {
    resolve(a + 1);
  });
}

function test() {
  return plus(1).then((res) => {
    console.log(res);
    return new Promise((resolve, reject) => {
      resolve("Test");
    });
  });
}

test().then((res) => {
  console.log(res);
});

A: As @Bergi said in the comment of your OP, the true power or Promises comes from returning them in the then of other Promises.

*

*This allows you to chain Promises in a clean way.

*To chain Promises all your operations in the chain must be Promises.

*Your bcrypt.compare function uses callbacks to signal that it's done, so you need that function convert to a Promise.

This is easy to do. Just wrap the callback-style code in a Promise and resolve the result of the callback or reject if the callback is called with an err.
const comparePassword = (a, b) => {
  return new Promise((resolve, reject) => {
    bcrypt.compare(a, b, (err, result) => {
      // Reject if there was an error
      // - rejection is `return`-ed solely for stopping further execution
      //   of this callback. No other reason for it.
      if (err) return reject(err)

      // Resolve if not.
      resolve(result)
    })
  })
}

... and then we can chain properly:
UserSchema.statics.findByCredentials = function(email, password) {
  // Outer Promise:
  // - Will eventually resolve with whatever the result it's inner
  //   promise resolves with.
  return user.findOne({ email })
    .then((user) => {
      // Inner Promise:
      // - Will eventually resolve with `user` (which is already
      //   available here), given that the password was correct,
      //   or
      //   reject with the bcrypt.compare `err` if the password was
      //   incorrect.
      return comparePassword(password, user.password)
        .then((result) => {
          // This `then` belongs to the comparePassword Promise.
          // - We use this so we can make sure we return the `user` we picked up
          //   from the previous `user.findOne` Promise.
          // - This ensures that when you chain a `then` to this Promise chain
          //   you always get the `user` and not the result of `comparePassword`
          return user
        })
    })
}

The key here is that whatever you return within a .then() is going to be passed as an argument to the next chained .then().
Additional info:

*

*bcrypt.compare already returns a Promise, so we could have avoided the whole hassle of wrapping it into a Promise. I've intentionally used it with callbacks to illustrate how you should handle callback-style code in a Promise chain.


text:
Q: Electrically conductive thermal paste I need a thermally AND electrically conductive heat sink compound for attaching power transistors to an aluminium heat sink. I've given Coollaboratory's LiquidPro a try and that oxidized the aluminium. Artic Silver 5 was completely the wrong solution, not conductive at all (I had some exploding FETs on my hands).
Any suggestions?

A: I hardly can see why you need a conductive paste? The aluminum is covered with thin insulation layer of Al-oxide and will break the electrical contact anyway with the time, regardless of the paste properties.

*

*If you need the heat sink to be electrically connected to the element - use a wire instead and screw it on the heat sink.

*Use copper heat sink and solder the element on it - this way you will get the best electrical and thermal contact possible and very effective heat sink at the same time. (Use very thin solder layer).

A: I have used such products in high current rectifiers (30+ kA) with hockey-puck type semiconductors. We used it to connect the SCRs to their heat sinks (which were water cooled chill plates and were part of the electrical circuit). I think this is the product you were looking for:
https://www.aflglobal.com/Products/Conductor-Accessories/Substation-Accessories/Compounds/AFL-No-2-Electrical-Joint-Compound.aspx#

A: Beryllium (Be) has excellent electrical and thermal characteristics (Rθ~0.25), BUT it is toxic (for your health and pocket!)
http://en.wikipedia.org/wiki/Beryllium

and
http://en.wikipedia.org/wiki/Beryllium_poisoning


text:
Q: Bootstrap is not working with Rails 4 I'm going through Michael Hartl's Ruby on Rails Tutorial, and I have problem with running bootstrap with my application. I've searched google to fix this error but I wasn't able to find anything helpful. Can some explain me why is this error occuring?
Here you can see the error:
NoMethodError in StaticPages#home

Showing /home/mateusz/Pulpit/sample_app/app/views/layouts/application.html.erb where line #5 raised:

undefined method `environment' for nil:NilClass
  (in /home/mateusz/Pulpit/sample_app/app/assets/stylesheets/custom.css.scss)

Extracted source (around line #5):

<title><%= full_title(yield(:title)) %></title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>

                    <%= link_to "sample app", '#', id: "logo" %>

<%= link_to "Home", '#' %>

<%= link_to "Help", '#' %>

<%= link_to "Sign in", '#' %>

            <%= yield %>

A: There is a known issue in sass-rails that is causing this. https://github.com/rails/sass-rails/issues/191
Try locking sass-rails to version 4.0.3, delete Gemfile.lock and run bundle install again.

A: I was having the same problem and also changed sass-rails to version 4.0.3, but did not delete Gemfile.lock. Just changing to 4.0.3 solved it for me.


text:
Q: Pre-compile textual replacement macro with arguments I am trying to create some kind of a dut_error wrapper. Something that will take some arguments and construct them in a specific way to a dut_error.
I can't use a method to replace the calls to dut_error because to my understanding after check that ... then ... else can only come a dut_error (or dut_errorf). And indeed if I try to do something like:
my_dut_error(arg1: string, arg2: string) is {
    dut_error("first argument is ", arg, " and second argument is ", arg2);
};

check that FALSE else my_dut_error("check1", "check2");

I get an error:
*** Error: Unrecognized exp
 [Unrecognized expression 'FALSE else my_dut_error("check1", "check2")']
     at line x in main.e
         check that FALSE else my_dut_error("check1", "check2");
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

So I thought about defining a macro to simply do a textual replace from my wrapper to an actual dut_error:
define <my_dut_error'exp> "my_dut_error(<arg1'name>, <arg2'name>)" as {
    dut_error("first argument is ", <arg1'name>, " and second argument is ", <arg2'name>)
};

But got the same error.
Then I read about the preprocessor directive #define so tried:
#define my_dut_error(arg1, arg2) dut_error("first argument is ", arg, " and second argument is ", arg2)

But that just gave a syntax error.
How can I define a pre-compiled textual replacement macro that takes arguments, similar to C?

The reason I want to do that is to achieve some sort of an "interface" to the dut_error so all errors have a consistent structure. This way, different people writing different errors will only pass the arguments necessary by that interface and internally an appropriate message will be created.

A: not sure i understood what you want to do in the wrapper, but perhaps you can achieve what you want by using the dut_error_struct.
it has set of api, which you can use as hooks (do something when the error is caught) and to query about the specific error.
for example:
extend dut_error_struct {
   pre_error() is also {
      if source_method_name() == "post_generate" and
         source_struct() is a BLUE packet {
         out("\nProblem in generation? ", source_location());
         // do something for error during generation
    };
    write() is first {
       if get_mesage() ~ "AHB Error..." {
           ahb_monitor::increase_errors();
       };
    };

};

A: dut_error accepts one parameter, one string. but you can decide of a "separator", that will define two parts to the message.
e.g. - instruct people to write "XXX" in the message, before "first arg" and "second arg".
check that legal else dut_error("ONE thing", "XXX", "another thing");
check that x < 7 else dut_error("failure ", "XXX", "of x not 7 but is ", x);

extend dut_error_struct {
    write() is first {
        var message_parts := str_split(get_message(), "XXX");

    if message_parts.size() == 2 {
        out ("First part of message is ", message_parts[0],
             "\nand second part of message is ", message_parts[1]
            );
    };
};

A: I could get pretty close to what I want using the dut_errorf method combined with a preprocessor directive defining the format string:
#define DUT_FORMAT "first argument is %s and second argument is %s"

check that FALSE else dut_errorf(DUT_FORMAT, "check1", "check2");

but I would still prefer a way that doesn't require this DUT_FORMAT directive and instead uses dut_error_struct or something similar.


text:
Q: Storing chars into a string with a for loop? I have this function, bits_show, which prints to stdout a 2-3 bit long code.
void bits_show(bits *a)
{
  int i;
  for (i = 0; i < a->next; i++)
    putchar(a->bits[i]);
}

where bits:
struct bits {
  int capacity;
  int next;
  char *bits;
};

I am trying to write a function, char* bits_char(bits a) that captures these characters and collects them into a single char file.
This is what I have so far, but it keeps spitting errors:
char* bits_char(bits *a)
{
  char* str = (char*) malloc( sizeof(a->next * char));
  int i;
  for (i=0; i<a->next; i++){
    str[i] = (a->bits[i]);
  }
  return str;
}

"bits.c: In function 'bits_char':
bits.c:33: error: variable-sized object may not be initialized
bits.c:37: warning: function returns address of local variable"

A: This is wrong:
sizeof(a->next * char)

I presume you meant to write:
a->next * sizeof(char)

But since sizeof(char) equals 1 by definition you would simply omit that.
But even that is wrong since you need to allow space for the null terminator which your code does not currently write. The allocation needs to be:
malloc(a->next+1)

And add the null-terminator like this:
str[a->next] = 0;

All in all, the finished product is as so:
char* bits_char(bits *a)
{
  char* str = malloc(a->next+1);
  int i;
  for (i=0; i<a->next; i++){
    str[i] = (a->bits[i]);
  }
  str[a->next] = 0;
  return str;
}

I removed the cast of the return value of malloc which is not needed in C.
And you should also ensure that you check the return value of malloc for a failed allocation. It will return the null pointer if it fails. I've not shown how to do that because I don't know your error handling policy.


text:
Q: How to check if a variable even exist after decode JSON? I have this JSON string.
[
   {
     "name": "user_title",
     "value": "Bapak."
   },
   {
     "name": "user_firstname",
     "value": "Test"
   },
   {
     "name": "user_lastname",
     "value": "XXX"
   }
]

This string generated dynamically. It may has more or less. I use JSON Decode to process it in PHP.
$json_form      = json_decode($json_string,true);

$user_title     = $json_form[0]['value'];
$user_firstname = $json_form[1]['value'];
$user_lastname  = $json_form[2]['value'];

How do I check the variable user_title even exist in the string?
If it exist I should get the value but if not that means $user_title = NULL.

A: You might want to consider mapping your JSON into a key/value array using array_column; then it is easy to check for the existence of a value. For example:
$json_form = json_decode($json_string, true);
$values = array_column($json_form, 'value', 'name');

$user_title     = $values['user_title'];
$user_firstname = $values['user_firstname'];
$user_lastname  = $values['user_lastname'];

echo "title: $user_title\nfirst name: $user_firstname\nlast name: $user_lastname\n";

Output for your sample data is:
title: Bapak.
first name: Test
last name: XXX

It's also easy to add default values when a key is missing, for example:
$user_title     = $values['user_title'] ?? '';


text:
Q: Are continuations in Kotlin usable yet? Any examples available? There is an package in Kotlin for continuations, but it's marked as experimental. There is no documentation other than the API, and no tutorial or examples anywhere that I could find. Does anyone know if it's already usable? What would be an example of its usage?

A: The Continuation interface is a part of coroutines support API in the standard library. You can start exploring the coroutines from the documentation page, or from the kotlinx.coroutines library repository, which contains an extensive coroutine programming guide.
Coroutines are experimental in Kotlin 1.1 and 1.2, but there was an announcement that they are going to stabilize in 1.3.

A: When you say "continuations", you actually mean "coroutines". Continuation is a part of that story.
kotlin-coroutines-informal by the JetBrains team is a great resource to start you off with coroutines. If you're looking to use them for async programming on Android, especially take note of the section on wrapping the callbacks which your existing async API provides, turning the existing Java function calls into Kotlin suspend funs.
About the status of experimental, check out Roman Elizarov's answer to that question. Here's a highlight:

Kotlin coroutines can and should be used in production. That was the chief reason to officially release them in Kotlin 1.1. Having released them, the JetBrains team had committed to maintain backwards compatibility with respect to any changes that are introduced to them in the minor releases as they evolve, while allowing people to safely try them in complex production applications.

There is absolutely no reason to wait for 1.3 to start using coroutines. Whatever you write today will work into the foreseeable future with no changes and, on top of that, it will be very easy to switch from kotlinx.coroutines.experimental to kotlinx.coroutines after the release. The APIs are already very stable and most of the changes are now in the area of channels and actors.


text:
Q: Awaiting multiple asynchronous object[key] = value assignments inside a forEach loop I trying to create a dictionary of dictionaries. Each item in the dictionary is assigned asynchronously. I would like to wait until all items are assigned before printing the result to the console.
Program
const dict = {};

async function placeholder (letter, number) {
    await new Promise(r => setTimeout(r, 2000));
    return 'test';
}

async function secondMethod (letter, number) {
    try {
        dict[letter][number] = await placeholder (letter, number);
    }
    catch (err) {
        console.error(err)
    }
}

async function firstMethod (letter) {
    dict[letter] = {};
    const numbers = ['1', '2', '3', '4'];
    await numbers.forEach (number => secondMethod (letter, number));
}

async function main () {
    const letters = ['a', 'b', 'c', 'd'];
    await letters.forEach (letter => firstMethod (letter));
    console.log (dict)
};

main ();

Result
{ a: {}, b: {}, c: {}, d: {} }

Desired Result
{
  a: { '1': 'test', '2': 'test', '3': 'test', '4': 'test' },
  b: { '1': 'test', '2': 'test', '3': 'test', '4': 'test' },
  c: { '1': 'test', '2': 'test', '3': 'test', '4': 'test' },
  d: { '1': 'test', '2': 'test', '3': 'test', '4': 'test' }
}

A: The problem is that Array.forEach is a synchronous function, you cannot call await on it. You'll need to restructure your code flow to use proper async loops to reach the desired result.
Using the await in every single call:

const dict = {};

async function placeholder(letter, number) {
    await new Promise(r => setTimeout(r, 200));
    return 'test';
}

async function secondMethod(letter, number) {
    try {
        dict[letter][number] = await placeholder (letter, number);
    }
    catch (err) {
        console.error(err)
    }
}

async function firstMethod(letter) {
    dict[letter] = {};
    const numbers = ['1', '2', '3', '4'];
    for (const number of numbers) {
        await secondMethod (letter, number);
    }
}

async function main() {
    const letters = ['a', 'b', 'c', 'd'];
    for (const letter of letters) {
        await firstMethod(letter);
    }
    console.log(dict)

    // pretty html result
    let resultContainer = document.getElementById("result")
    resultContainer.innerHTML = JSON.stringify(dict, null, 2)

};

main();

 Result:

Waiting results...

Using promise.all to have all the promises execute in "parallel"

const dict = {};

async function placeholder(letter, number) {
    await new Promise(r => setTimeout(r, 200));
    return 'test';
}

async function secondMethod(letter, number) {
    try {
        dict[letter][number] = await placeholder (letter, number);
    }
    catch (err) {
        console.error(err)
    }
}

async function firstMethod(letter) {
    dict[letter] = {};
    const numbers = ['1', '2', '3', '4'];
    const promises = [];
    for (const number of numbers) {
        promises.push(secondMethod (letter, number));
    }
    await Promise.all(promises);
}

async function main() {
    const letters = ['a', 'b', 'c', 'd'];
    const promises = [];

    for (const letter of letters) {
        promises.push(firstMethod(letter));
    }

    await Promise.all(promises);
    console.log(dict);

    // pretty html result
    let resultContainer = document.getElementById("result")
    resultContainer.innerHTML = JSON.stringify(dict, null, 2)

};

main();

 Result:

Waiting results...

A: I think this should solve it for you.
async function firstMethod (letter) {
    dict[letter] = {};
    const numbers = ['1', '2', '3', '4'];
    await numbers.forEach(async function (number) {
        return await secondMethod(letter, number);
    });
}

async function main () {
    const letters = ['a', 'b', 'c', 'd'];
    await letters.forEach(async function (letter) {
        return await firstMethod(letter);
    });
    console.log (dict);
}


text:
Q: I cannot import data_utils I am writing a chatbot code but after having the latest version , i am getting an error------
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
import time
import sys
import data_utils

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-6d94ab985d76> in <module>()
      4 import time
      5 import sys
----> 6 import data_utils
      7 import matplotlib.pyplot as plt

ModuleNotFoundError: No module named 'data_utils'

NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.


text:
Q: Typescript parameters - a generic array of objects and array of object's keys (partial) I want to have a method that accepts an array of objects and an array of some of the objects keys. The method will return an array of arrays of object values but only of the selected keys.
data:
[
  {"firstName": "Jane", "lastName": "Doe"},
  {"firstName": "John", "lastName": "Doe"}
]

fields:
["firstName"]

result:
[["Jane"], ["John"]]

By now I have a function that provides desired outcome but I am not sure how to handle the types better.
mapToCsvData: (data: { [key: string]: any }[], fields: string[]) => {
  return data.map((item: any) => {
    return fields.map(field => item[field]);
  });
}

I have tried some variations of the next snippet but I get an error.
mapToCsvData: <T extends object>(data: T[], fields: keyof T[]) => {

Property 'map' does not exist on type 'number'.

A: You will need an extra type parameter to capture the actual tuple of keys being passed in. You can them map this tuple to the corresponding property types in T. It all works out very nicely:
type MapKeyTupleToProps<T, P extends [keyof T] | Array<keyof T>> = {
    [K in keyof P]: P[K] extends keyof T ? T[P[K]] : never
}
const m = {
    mapToCsvData: <T, P extends [keyof T] | Array<keyof T>>(data: T[], fields: P): MapKeyTupleToProps<T, P> => {
        return data.map((item: any) => {
            return fields.map(field => item[field]);
        }) as any;
    }
}

const data = [
    {"firstName": "Jane", "lastName": "Doe", age: 0},
    {"firstName": "John", "lastName": "Doe", age: 0}
]

let r = m.mapToCsvData(data, ["firstName", "lastName"]) // [string, string]
let r2 = m.mapToCsvData(data, ["firstName", "age"]) //[string, number]


text:
Q: How can I learn how many days passed from a specific date? How can I learn how many days passed from a spesific date? Which package i need to use and how?

A: Just for the protocol - i love java.util.concurrent.TimeUnit for that things.
Date d1 = ...
Date d2 = ...
long dif = d1.getTime() - d2.getTime();
long days = TimeUnit.MILLISECONDS.toDays(dif);

So basically exactly what the answer from morja is, but using TimeUnit for calculating time things around. Having values like 24, 60 etc. directly in your code violates Java Code Conventions (which only allow -1, 0 and 1 directly in code) and is harder to read.

A: EDIT My previous answer was only valid within a year.
You can use the milliseconds difference like this:
Date date1 = // some date
Date date2 = // some other date
long difference = date2.getTime() - date1.getTime();
long differenceDays = difference / (1000 * 60 * 60 * 24);

Basically the same as timbooo answered, just a shorter way.

A: Check out this example by kodejava.org

A: Jodatime makes such calculations a lot simpler:
Date now = // some Date
Date then = // some Date
int days = Days.daysBetween(new DateTime(now), new DateTime(then)).getDays();

A: In fact, you should create instances of Calendar from both of the dates, getTimeInMillis() from both of them (that is, time in milliseconds since 1970), substract one from the other, divide by 1000/seconds-a-minute/minute-an-hour/hour-a-day. There is your answer ;)


text:
Q: How To Incorporate PayPal Subscription During Signup Does anyone have an opinion on the best approach to take when building a signup process that incorporates PayPal subscription. There are a couple of issues that I would like to take into account:
First: I have an initial form to capture the users details. I then store the detail in an MYSQL database and use the new account_id and pass it through to PayPal to reference the account that is choosing the subscription. Lets say the user then decides to cancel the payment, I now have am account in the database without any sort of subscription associated to it.
If the user was then to try and sign up again the form would indicate that the user is already signed up. Would it be worth deleting the user on cancel or should I use some sort of temporary table to store the account information up to the point where the subscription is confirmed.
Second: There is a slight delay between PayPal IPN reaching the server and and the user arriving back after signing up to a package. Should I place a holding page to ask the user to wait for the response from the PayPal IPN or is there some other standard method of dealing with this issue?
Thanks
Oliver

A: Both of your methods would work, but to get the best bang for your buck from PayPal's order management functionality, I would advise using three methods. IPN, PDT, and the TransactionSearch API.
Pro's and Con's:

*

*IPN does have a delay, PDT does not. However, IPN is pretty much guaranteed to be sent.

*PDT is not guaranteed because it depends on your buyers being redirected back to your site, which is only automatic for PayPal members. However, because of this, PDT

*TransactionSearch would need to be initiated by you; so you could put it on a timer after someone is sent to PayPal, and have it check every few minutes, or after ten minutes, or have the API call triggered upon a visitor accessing a certain page.

With all of these, and some ingenuity, there is no possible way your buyer would notice a delay in signup, but you would have a lot going in the background.
A good source for order automation can be found on PayPal's Merchant Tech support's support center here.


text:
Q: how to change sammy routes I use sammy scripts in spa template (c#, mvc 4).
Default links are the following: /#/home, /#/contacts, /#/faq, etc.
How can I change them on just /home, /contacts, /faq?

A: The hash delineates the local part of the URL, which can be modified using the location.hash method. If you modify the entire URL, i.e. location.href, the browser will load the modified URL.
It looks like what you want to do is change your local URL, used by Sammy, to #home or #contacts so you don't have the empty hash in the beginning.
Below, Sammy is capturing changes to the URL, such as the user clicking on an anchor element with href="#Home" and then sending an AJAX request to get the template:
Sammy(function () {
/* Navigation requests
*/
    this.get("#:view", function () {
        switch (this.params.view) {
            case "Home":
                $.ajax("Home/Index", {
                    type: "GET",
                    success: function (result) {
                        //Append result to page
                    },
                    cache: false
                });
                break;
            case "Search":
                $.ajax("Search/Index", {
                    type: "GET",
                    success: function (result) {
                        //Append result to page
                    },
                    cache: false
                });
                break;
        };
    });
}).run();


text:
Q: Separate lines and circles in an image using OpenCV in python I'm trying to separate the lines and circles, instead of lines some circles are connected with curves.
I tried to use contours to find circles but it is however including the lines inside the contour, so I also tried skeletoning the image so that to see if the connection between the circles and lines might break, but it is unsuccessful.
Hough_circles is not detecting circles in all cases, so the only option I've to find the circles using contours once the lines around it are eliminated.

*

*EDIT
Example 2
Input

Output :  Not desired output

In the output image, I got circles weren't got separated and lines got merged with circles and the contour gave a different shape.
Please find some way to split the circles and lines. Please try to answer it in Python instead of C++. C++ answers are allowed too.
Thanks in advance!

A: Here's a simple approach using morphological operations. The idea is to fill the contours, create an elliptical shaped structuring element, then morph open to remove the lines. From here we simply find the external contours and draw the circles. Here's the process visualized:
Filled thresholded image

Morph open

Result

Code
import cv2

# Load iamge, grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Fill contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(thresh, [c], -1, (255,255,255), -1)

# Morph open
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)

# Draw circles
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    cv2.drawContours(image, [c], -1, (36,255,12), 3)

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.waitKey()

For the other image using contour hierarchy

import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Filter using contour hierarchy
cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = hierarchy[0]
for component in zip(cnts, hierarchy):
    currentContour = component[0]
    currentHierarchy = component[1]
    x,y,w,h = cv2.boundingRect(currentContour)
    # Only select inner contours
    if currentHierarchy[3] > 0:
        cv2.drawContours(mask, [currentContour], -1, (255,255,255), -1)

# Filter contours on mask using contour approximation
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.05 * peri, True)
    if len(approx) > 5:
        cv2.drawContours(mask, [c], -1, (0,0,0), -1)
    else:
        cv2.drawContours(image, [c], -1, (36,255,12), 2)

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.imshow('mask', mask)
cv2.waitKey()

Note: For a through explanation on contour hierarchy, take a look at understanding contour hierarchy and retrieval modes


text:
Q: The function clipboard.get_selection() fails to get all the selected string I set a shortcut in order to select a piece of text and open an URL with the selection at the end.
So this is the script for AutoKey under linux:
text = clipboard.get_selection()
system.exec_command("kde-open http://www.MY_URL.com/%s" % text)

the problem is that the %s only insert the first word.
So if I select "my text is this" che URL opened is: www.MY_URL.com/my

A: You probably have to encode the text to use it in a URL:
from urllib.parse import quote # in python2 that would be: from urllib import quote

text = quote(clipboard.get_selection())
system.exec_command("kde-open http://www.MY_URL.com/%s" % text)


text:
Q: Wordpress site doens't load without index.php after migration from cpanel to plesk I have migrated wordpress site from Linux hosting to Windows hosting (cpanel to plesk). Below are the details :
Linux : http://projects.iqlas.com/ongoing-projects/2015/gogreen/03062015/
Windows : http://mangium.com/projects/ggiqatar/29082015/
However, in the windows, the site doesn't work without index.php
Tried different steps with .htaccess but of no use.
This is .htaccess file.
#Begin Wordpress

<IfModule mod_rewrite.c>
RewriteEngine On
DirectoryIndex index.php index.html index.htm
RewriteBase /projects/ggiqatar/29082015/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /projects/ggiqatar/29082015/index.php [L]
</IfModule>

AddHandler x-mapp-php5.5  .php

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

Can anyone suggest as to what has to be done. Thanks.


text:
Q: How to straighten divs lined up next to each other What is the best way to straighten up the divs right next to each other? I've tried but it all seems slightly proportion and I would like a way of keeping each column well positioned next to each other (despite any changes that may occur).
Here is my code: http://jsfiddle.net/j3cY5/2/
UPDATE: It seems jQuery datepicker isn't working in the sample :-(
HTML

Task

Item 1

Item 2

Item 3

Item 4

Item 5

Due Date

            <input type="text" id="datepicker1" style="width: 100px;
                    height: 10px;" value="" class="hasDatepicker">

            <input type="text" id="datepicker2" style="width: 100px;
                    height: 10px;" value="" class="hasDatepicker">

            <input type="text" id="datepicker3" style="width: 100px;
                    height: 10px;" value="" class="hasDatepicker">

            <input type="text" id="datepicker4" style="width: 100px;
                    height: 10px;" value="" class="hasDatepicker">

            <input type="text" id="datepicker5" style="width: 100px;
                    height: 10px;" value="" class="hasDatepicker">

Status

            <select style="height: 30px; width: 100px;">
                <option></option>
                <option>----</option>
            </select>

            <select style="height: 30px; width: 100px;">
                <option></option>
                <option>----</option>
            </select>

            <select style="height: 30px; width: 100px;">
                <option></option>
                <option>----</option>
            </select>

            <select style="height: 30px; width: 100px;">
                <option></option>
                <option>----</option>
            </select>

            <select style="height: 30px; width: 100px;">
                <option></option>
                <option>----</option>
            </select>

            <input type="submit" id="update" value="Update" style="width: 100px;">

            <input type="submit" id="update" value="Update" style="width: 100px;">

            <input type="submit" id="update" value="Update" style="width: 100px;">

            <input type="submit" id="update" value="Update" style="width: 100px;">

            <input type="submit" id="update" value="Update" style="width: 100px;">

CSS
.schedule_wrapper {
    overflow:hidden;
    margin-bottom:10px;
}
.schedule_item {
    float:left;
    margin:2px;
}
body {
font-family: Verdana;
}
input[type="submit"] {
    background: #52A8E8;
    border: 0;
    border-bottom: 2px solid #4081AF;
    color: #fff;
    padding: 9px 21px;
    text-align: center;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    width: auto;
}
input[type="submit"]:hover, input[type="submit"]:active {
    cursor: pointer;
    background: #377AD0;
    border: 0;
    border-bottom: 2px solid transparent;
}
input[type="submit"] + a {
    margin-left: 22px;
}


text:
Q: Merge two values in if both values are same except blank in EXCEL I want to merge two cells in excel that have a value like this:
'a  b  c
 1  1  11
 1  2  12
 1
 2
    1
 2  2  22
 '

I don't want to merge the number with a blank...
any help for that? I used concatenate function  but it cannot help me ...

A: You can produce column C using an if statement and the "&" operator.
=IF(LEN(B2)<1,"",A2&B2)
If you want C to be blank in the case where A is blank, then you'll need an or statement also.

A: Assuming the data are orientated in columns A and B starting at row 1, =IF(OR(ISBLANK(A1), ISBLANK(B1)),"",CONCATENATE(A1,B1)) is one way. Copy this downwards.
The returned value is a string type. A blank string is inserted into rows where either a or b are not given.

A: =IF(VALUE(A1)=VALUE(B1),CONCATENATE(A1,B1),"")

OR
=IF(A1=B1,CONCATENATE(A1,B1),"")


text:
Q: Trouble using the ^ operator in a calculator in netbeans (Java) The error i get is "bad operand types for binary operator ^ first type: float second type: float" this error happens in case 5 of the switch x y and r are floats and n is an Int
  switch (n)
         {
             case 1: r=x+y;
             case 2: r=x-y;
             case 3: r=x*y;
             case 4: r=x/y;
             case 5: r=x^y;
             default: System.out.println("Elija un numero valido");}

A: ^ is only defined for the integer-like types (byte, short, int, long, char) and booleans.
In other words: exactly what the error message says. floats are not legal operands for the ^ operator.
And that makes sense: most people wouldn't be able to tell what the binary representation of e.g. 23.42 is. Would you? (This is actually a trick question: you cannot even represent 23.42 in binary. The closest you can get is 23.4200000000000017053025658242 whose binary representation is 01000000 00110111 01101011 10000101 00011110 10111000 01010001 11101100.)
If the ^ operator did work with floats, it wouldn't be very obvious. E.g.
2.0 ^ 3.0

Would be
0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111253692925360069154511635867

(I think, if I didn't make a mistake somewhere.)


text:
Q: Orthogonality of sum of sine Define $$v_{lk}=\sqrt{\frac{2}{m+1}}\sin\left(\frac{kl\pi}{m+1}\right)$$
where $k,l=1,\ldots,m$.
My textbook claims the following statements, but I don't see how either follow.

*

*$$\sum_{l=1}^m\sin^2\left(\frac{k l \pi}{m+1}\right)=\frac{m+1}{2}$$

*$$\sum_{l=1}^m v_{lk}v_{lj}=\delta_{kj}$$

Assuming the first claim, it's easy to see that if $k=j$, then $\sum_{l=1}^m v_{lk}v_{lj}=1.$
However, after trying several trig identities, namely the product of sines, I haven't been able to work out how the sum is zero.
How exactly can I see that these two claims hold?

A: hint
Put $$\theta=\frac {2k\pi}{m+1} $$
use
$$\sin^2 (\theta/2)=\frac {1-\cos (\theta)}{2} $$
and
$$\sum_{l=1}^m \cos (l \theta)=Re (\sum_{l=1}^m (e^{i\theta})^l )$$


text:
Q: How to select a row where a col has two characters in a parentheses? SELECT * FROM t WHERE c REGEXP '.*\(..\).*';

This didn't work. It returned many rows whose c contain string that have more than two characters in ().

A: SELECT * FROM t WHERE c LIKE '%(__)%'

SQL Fiddle here

A: Your escapes are off.
http://dev.mysql.com/doc/refman/5.0/en/regexp.html#operator_regexp

Because MySQL uses the C escape syntax in strings (for example, "\n" to represent the newline character), you must double any "\" that you use in your REGEXP strings.

Use:
SELECT * FROM t WHERE c REGEXP '.*\\(..\\).*';

A: How are you running this query? If you're using it in (say) a PHP script, and writing it like this:
$sql = "SELECT ... REGEXP '.*\(..\).*';";

then the PHP interpreter will actually be stripping out those backslashes, producing the real query
... REGEXP '.*(..).*';

which would simply be any record that has at least two characters. For this to work properly, you'll have to double-escape:
$sql = "SELECT ... REGEXP '.*\\(..\\).*';";

PHP will strip off one of the backslashes from each set, leaving the second one to actually reach mysql.


text:
Q: PHP rand() vs. random_int() As php.net indicates: random_int() function Generates cryptographically secure pseudo-random integers.
But, Can someone explain whats the difference between rand() & random_int()? Can I use random_int() instead of rand() when only requiring a random integer? Which one is faster?

A: rand()
rand() is now an alias for mt_rand(). Looking at the source code of mt_rand(), it can be seen the random number is not random at all. It's a simple mathematical computation not much more complex than
return $min + suffle_bits($internal_counter++) % ($max - $min);

where suffle_bits() is some predictable binary arithmetic to make it looks like $internal_counter is not just incrementing itself.
That's why rand() is said to returns pseudo-random numbers. The returned numbers seem to be drawn at random but knowing the value of the $internal_counter lets you predict what will follow.
random_int()
random_int() doesn't suffer from this predictability issue provided the computer's entropy generator is properly primed.
Guessing the next value is not possible even if an attacker collects a huge number of values.
Which one is best
If an attacker can guess the value of the $internal_counter from the output of your code and use that knowledge to interfere with the intended purpose of your code, then use random_int().
If the random number is used to display, let's say, a random greeting, then rand() is perfectly safe.
Now, if a long list of GUID or barcodes must be generated and the end user must not be able to guess another valid value from a subset, then random_int() is better not only for security but also because it doesn't repeat itself. rand() may repeat itself as quickly as 32768 output depending on the platform.
Which one is faster
Without any doubt, rand() is simpler and, therefore, faster.
Here is a crude one-line easy to copy/paste command to count how many numbers can be drawn from rand() in 10 seconds:
php -r '$s=microtime(true);$c=0;while(microtime(true)-$s<10){rand(0,9);$c++;};echo "$c\n";'

And the same for random_int():
php -r '$s=microtime(true);$c=0;while(microtime(true)-$s<10){random_int(0,9);$c++;};echo "$c\n";'

The counters for php 7.3 are:
rand():       36665142
random_int(): 10511327

rand() is less than 4 times faster. Unless speed is an issue, random_int() is the way to go but for the most basic non critical missions.

A: Revisiting the question and seeing there's been an answer given, I find it's only fair that I submit my comments to an answer, seeing they were submitted before.
The manual on PHP 7's random_int() function states:

"Returns a cryptographically secure random integer in the range min to max, inclusive."

*

*http://php.net/manual/en/function.random-int.php
and for rand()

*This function does not generate cryptographically secure values" *

*

*http://php.net/manual/en/function.rand.php
OP's comment:

"@Fred-ii- thank you. But what does "cryptographically secure pseudo-random" mean? – NDFA"

That can be found in the following links as per my findings:

*

*https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator
Which states:

A cryptographically secure pseudo-random number generator (CSPRNG) or cryptographic pseudo-random number generator (CPRNG)[1] is a pseudo-random number generator (PRNG) with properties that make it suitable for use in cryptography.

*

*How does a cryptographically secure random number generator work?
In regards to performance, you will need to run a benchmark yourself.

A: As most number generators, using rand() is not secure because it does not generate cryptographically secure values and the output of rand() is predictable.
PHP 7.0 introduces random_bytes and random_int as core functions which are  free from the problems that most of random number generators have.

A: Starting with PHP 7.1, rand() is an alias for mt_rand(). The newer random_int() is the slowest, but only secure method of the three.
<?php

$start = microtime(true);
$sum = 0.0;
for ($i = 0; $i < 10000000; $i++) {
    $sum += rand(0, 32767);
}
printf('[rand] Time: %.3f s%s', microtime(true) - $start, PHP_EOL);

$start = microtime(true);
$sum = 0.0;
for ($i = 0; $i < 10000000; $i++) {
    $sum += mt_rand(0, 32767);
}
printf('[mt_rand] Time: %.3f s%s', microtime(true) - $start, PHP_EOL);

$start = microtime(true);
$sum = 0.0;
for ($i = 0; $i < 10000000; $i++) {
    $sum += random_int(0, 32767);
}
printf('[random_int] Time: %.3f s%s', microtime(true) - $start, PHP_EOL);

Results on PHP 7.4:
[rand] Time: 0.320 s
[mt_rand] Time: 0.326 s
[random_int] Time: 9.255 s

A: Complementing Frédéric response, in PHP 8.0.3, random_int() seems to be a lot faster than before, using his own code example.
with:
<?php
    echo "this will take 20 seconds\n\n";

    echo "generating random with 'rand' method\n";
    $s1=microtime(true);$c1=0;while(microtime(true)-$s1<10){rand(0,65535);$c1++;};
    $fc1 = number_format($c1 , 0, ',', '.');
    echo "generated: $fc1\n\n";

    echo "generating random with 'random_int' method\n";
    $s2=microtime(true);$c2=0;while(microtime(true)-$s2<10){random_int(0,65535);$c2++;};
    $fc2 = number_format($c2 , 0, ',', '.');
    echo "generated: $fc2\n\n";
?>

I got the output:
this will take 20 seconds

generating random with 'rand' method
generated: 48.423.988

generating random with 'random_int' method
generated: 30.843.067

in his tests, random_int() was more than three times slower than rand().
in these, random_int() is just about 40% slower than rand().
PS: I've incremented the maximum random value from 9 to 65535 for personal uses, which seems to have actually increased the speed of both cases.

A: I have not personally encountered any problems using random_int but it should be used with try/catch as it throws an exception if it was not possible to gather sufficient entropy.


text: Q: ModuleNotFoundError: No module named 'intersys.pythonbind31' I want to connect cache database to python, but a problem occurred to me, I can import intersys,  but I can't import intersys.pythonbind3.there's an error showed like this ModuleNotFoundError: No module named 'intersys.pythonbind31'


text:
Q: How to increase the value of a new column after 'N' number of rows I have a Dataframe which consists a thousand rows, and I want to add 1 to particular column "Level" after every 100 rows.
I am sharing a small self created sample of how the data looks like:
import pandas as pd

data  = {'displayName':['Kelsier', 'Val', 'Elend', 'Dock','Club','Renox','Sher','Breeze','Saze','Reen','Mist','Atium','Iron','Copper','Tin'],
        'pic' : ["av10", "av12", "av14", "av15", "av0", "av1", "av18", "av8", "av16", "av22", "av40", "av24", "av17", "av2", "av7"]}

df = pd.DataFrame(data)

So for example I want the level to be increased by 1 after every 5 rows, and suppose the value needs to start form 6.
As shown below:
I tried loops but I am not very good at it currently
import pandas as pd

data  = {'displayName':['Kelsier', 'Val', 'Elend', 'Dock','Club','Renox','Sher','Breeze','Saze','Reen','Mist','Atium','Iron','Copper','Tin'],
        'pic' : ["av10", "av12", "av14", "av15", "av0", "av1", "av18", "av8", "av16", "av22", "av40", "av24", "av17", "av2", "av7"],
        'level':[6,6,6,6,6,7,7,7,7,7,8,8,8,8,8]}

df = pd.DataFrame(data)

That's all. Thanks for your kind help!

A: Use integer division by 5 and add to column level - solution if default RangeIndex:
df['level'] += df.index // 5

df['level'] = df.index // 5 + 6

Or if not RangeIndex is possible create helper array:
df['level'] += np.arange(len(df)) // 5

df['level'] = np.arange(len(df)) // 5 + 6

A: Use np.arange with floor division by 5:
df['level'] += np.arange(len(df))//5

Or using a default start value:
df['level'] = np.arange(len(df))//5 + 6

Output:
   displayName   pic  level
0      Kelsier  av10      6
1          Val  av12      6
2        Elend  av14      6
3         Dock  av15      6
4         Club   av0      6
5        Renox   av1      7
6         Sher  av18      7
7       Breeze   av8      7
8         Saze  av16      7
9         Reen  av22      7
10        Mist  av40      8
11       Atium  av24      8
12        Iron  av17      8
13      Copper   av2      8
14         Tin   av7      8


text:
Q: How can I insert data into an xml file I am trying to create a simple html form that inserts data into an xml file.  I would like the files to be stored on a cloud server like google drive.  I would like the page to use jquery and possibly AJAX if necessary.  The form should be an xsl style sheet (seperate file would be nice).  My main concern is how to insert the data into the xml file.  I am looking for some tips and if someone could simply create a sample so I can see what should be done.  I would like to avoid a database if possible.
Here is a sample xml of the data I need to insert.  Thanks for all the help!!
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data-set xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <record>
        <Timestamp>01/01/2015</Timestamp>
        <Acceptance1>Y</Acceptance1>
        <Acceptance2>Y</Acceptance2>
        <Fname>Tom</Fname>
        <Lname>Smith</Lname>
        <Address>123 Smith Avenue</Address>
        <City>Nowhere</City>
        <State>CA</State>
        <Zip>90210</Zip>
        <Email>abc@yahoo.com</Email>
        <Phone>1234564561</Phone>
        <Date>01/01/2015</Date>
        <MemberAgreement>Y</MemberAgreement>
        <Acceptance3>Y</Acceptance3>
        <LibraryPolicy>Y</LibraryPolicy>
        <Acceptance4>Y</Acceptance4>
        <LendingLibrary>Y</LendingLibrary>
        <PaymentType>Check</PaymentType>
    </record>
</data-set>

A: You mean something like this:
$(xml).find("data-set").find("record").append("<SecondName>Vardens</SecondName>");


text:
Q: Else-if Block not executing The last else if block is not getting executed when the condition is satisfied please help. Thank you.

let rotatingArr = (n, arr, k) => {
  if (n == arr.length && k !== 0 && k <= arr.length) {
    let arr2 = []
    arr
    let delItems = Math.abs(arr.length - k)
    console.log(delItems)
    let modArr = arr.slice().splice(delItems)
    modArr
    arr.splice(-k)
    console.log(arr)
    let result = [...modArr, ...arr];
    return result
  } else if (k == 0) {
    return arr;
  } else if (11 > k > arr.length) {
    k = k - 5
    arr
    let delItems = Math.abs(arr.length - k)
    console.log(delItems)
    let modArr = arr.slice().splice(delItems)
    modArr
    arr.splice(-k)
    console.log(arr)
    let result = [...modArr, ...arr];
    return result
  }
}

console.log(rotatingArr(5, [1, 2, 3, 4, 5], 10))

A: JavaScript does not support that kind of infix operators. Your code is executing (11 > k) > array.length.

A: The relational operators (e.g. >) evaluate two values to a boolean.
Therefore, your condition 11 > k > arr.length will be evaluated in two steps:

*

*11 > k: This will evaluate to either true or false.

*(11 > k) > arr.length: This will compare the boolean of the previous expression with arr.length. Because true == 1 and false == 0, this expression will always evaluate to false for arr.length > 1.

You should do these comparisons (11 > k and k > arr.length) in two distinct comparisons, and combine them with a logical operator.


text:
Q: Using one variable for different text fields or no in AS3? I was wondering which way it would be better to do the stuff bellow (in order to increase performance)..
var _tfShopCoins:TextField = _mcShop.tfCoins;
_tfShopCoins.mouseEnabled = false;
_tfShopCoins.text = "";

var _tfShopMoney:TextField = _mcShop.tfMoney;
_tfShopMoney.mouseEnabled = false;
_tfShopMoney.text = "";

or
var _tfText:TextField = _mcShop.tfCoins;
_tfText.mouseEnabled = false;
_tfText.text = "";

_tfText = _mcShop.tfMoney;
_tfText.mouseEnabled = false;
_tfText.text = "";

My guess is that it's the second one as there I declare only 1 variable.

A: Go with the first one. I personally would never reassign a variable like you did in the second example because its less readable and the performance increase would be next to nothing.

A: I don't think combining them into one variable will work the way you've written it out here, since you're reassigning the _tfText variable to something else (to itself, in this case).
If you have multiple text fields with the same behavior, you could put them in an array and iterate over the items -- it might save you a few lines of code, but that's about it.

A: In your second example, did you mean to type "_tfText.mouseEnabled..." etc.?
In any case, neither of these approaches will have a measurable impact unless you're doing it millions of times, and you're better off directly addressing the text fields in the first place:
_mcShop.tfMoney.mouseEnabled = false;
_mcShop.tfMoney.text = "";

etc.


text:
Q: add and get String Array into and from Arraylist I have this code that reads from XML file. It gets five strings (groupId, groupType, filePath, author, and lineNo), and it first saves them in a String Array. Then, the String Array is saved in an ArrayList. Finally, the last "for" displays the content of the ArrayList.
The problem that when I want to display the content, I get just the last added string array. The following is the code and the output. Can anyone figure out what is the problem?
ArrayList<String[]> developerTypes = new ArrayList<String[]>();
String[] developerInfo = {null, null, null, null, null};
String[] developerInfoR = {null, null, null, null, null};

String groupId;
String groupType;
String filePath;
String author;
String lineNo;

SAXBuilder builder = new SAXBuilder();
Document doc = (Document) builder.build("A.xml");
Element clones = doc.getRootElement();

// Loop of clones' children (clone_group)
List<Element> parentElements = clones.getChildren();
for(Element parentElement:parentElements){

    // Loop of clone_group's children (clone_fragment)
    List<Element> elements = parentElement.getChildren();
    for(Element element:elements){

        // Loop of clone_fragment's children (blameInfo)
        List<Element> childelements = element.getChildren();
        for(Element childElement:childelements){

            groupId = parentElement.getAttributeValue("groupid");
            groupType = parentElement.getAttributeValue("type");
            filePath = element.getAttributeValue("file");
            author = childElement.getAttributeValue("author");
            lineNo = childElement.getAttributeValue("lineNo");
            //System.out.print(groupId + " - ");
            //System.out.print(groupType + " - ");
            //System.out.print(file + " - ");
            //System.out.println(author);
            developerInfo[0] = groupId;
            developerInfo[1] = groupType;
            developerInfo[2] = filePath.substring(1, filePath.lastIndexOf("."));;
            developerInfo[3] = author;
            developerInfo[4] = lineNo;
            developerTypes.add(developerInfo);

        }// for (blameInfo)
    }// for (clone_fragment)
}// for (clone_group)

// Display the content of the Arraylist
for(int i = 0; i< developerTypes.size(); ++i){

    developerInfoR = developerTypes.get(i);

    for(int j = 0; j< developerInfoR.length; ++j){

        System.out.print(developerInfoR[j] + " ");

    }
    System.out.print("\n");

}

The Output:
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
309 Type-3 builtin/update-index.c Jonathan Nieder 704
...

A:
The problem that when I want to display the content, I get just the last added string array.

No, you find that you've got many references to the same string array... because that's what you've added. You've only got one string array object; developerInfo is just a reference to that array. When you call developerTypes.add(developerInfo) that's copying the reference into the ArrayList, so you've got the same reference lots of times.
You should pull the declaration and instantiation of developerInfo into the loop:
String[] developerInfo = {
    groupId,
    groupType,
    filePath.substring(1, filePath.lastIndexOf(".")),
    author,
    lineNo
};
developerTypes.add(developerInfo);

Likewise your code would be cleaner if you didn't declare developerInfoR until you used it:
for(int i = 0; i< developerTypes.size(); ++i){
    String[] developerInfoR = developerTypes.get(i);
    for(int j = 0; j< developerInfoR.length; ++j){
        System.out.print(developerInfoR[j] + " ");
    }
    System.out.print("\n");
}

Or even better, use the enhanced for loop:
for (String[] developerInfoR : developerTypes) {
    for (String info : developerInfoR) {
        System.out.print(info + " ");
    }
    System.out.print("\n");
}

In general, you should declare local variables with the smallest scope you can get away with, as late as possible, ideally assigning a value at the point of declaration. Declaring all the variables at the top of the method really hurts readability.

A: You have only one instance of the developerInfo array that you keep adding over and over in the loop. You need to make a new array in each loop step.
You seem to have some misunderstanding of the semantics of the contsructs you are using. I'm deducing that from the way you are initializing developerInfoR up front, but never using that value. An array variable only contains a reference to the array, so every time you assign to it, the array referenced before gets forgotten and thrown away. So, don't initialize developerInfo up front. In fact, you don't even need to declare it until the place you are using it.
There is also a simpler way to print an array's contents: just call System.out.println(Arrays.toString(developerInfoR)). That way you don't even need the inner loop in the printing code.
You don't need any of the variables groupId, groupType, filePath, author, lineNo. Just write for example developerInfo[0] = parentElement.getAttributeValue("groupid"); and similar. That makes for more obvious code. But it will probably make sense to use a full object instead of a String[]. There are many fields and the meaning of each gets behind the integer index.
All in all, taking these suggestions plus a few additional ones, your code can be rewritten to this:
final String path = filePath.substring(1, filePath.lastIndexOf("."));
final Document doc = (Document) new SAXBuilder().build("A.xml");
final List<DeveloperInfo> developers = new ArrayList<String[]>();
for (Element parentElement : doc.getRootElement().getChildren())
  for (Element element : parentElement.getChildren())
    for (Element childElement : element.getChildren())
      developers.add(new DeveloperInfo(
          parentElement.getAttributeValue("groupid"),
          parentElement.getAttributeValue("type"),
          element.getAttributeValue("file"),
          path,
          childElement.getAttributeValue("author"),
          childElement.getAttributeValue("lineNo"),
      ));
for (DeveloperInfo d : developerTypes) System.out.println(d);

The DeveloperInfo class:
class DeveloperInfo {
  public final String groupId, groupType, filePath, author, lineNo;
  public DeveloperInfo(
      String groupId, String groupType, String filePath,
      String author, String lineNo)
  {
    this.groupId = groupId; this.groupType = groupType; this.filePath = filePath;
    this.author = author; this.lineNo = lineNo;
  }
  public String toString() {
    return "DeveloperInfo [groupId=" + groupId + ", groupType=" + groupType +
      ", filePath=" + filePath + ", author=" + author + ", lineNo=" + lineNo + "]";
  }

A: You are referencing the same array every time you add it to the ArrayList.
Instead of declaring this String[] developerInfo = {null, null, null, null, null};
at the beginning. Create a new array everytime you loop.
String[] developerInfo = new String[5];