text:
Q: how to change values of csv while exporting in php I have been working on a database. Now its the final step to export the data to a csv file. I have created the file and it works perfectly. But now the requirement is that the values that are saving in the database can be changed. I have no idea how to approach this. Bellow is the code that I wrote with custom column name. But just say if gender is M, it should export Male in the csv not M. I cannot change the value how it is saved in the MySQL database because the second type of export requires it to be M not Male. and there are many more columns like this.
So please someone who can help me solve this and tell me how can I modify this code to change the values of the columns according to the requirements.
$host = 'localhost'; // MYSQL database host adress
$db = 'db_eschool'; // MYSQL database name
$user = 'admin'; // Mysql Datbase user
$pass = 'secretdatabase'; // Mysql Datbase password
$link = mysql_connect($host, $user, $pass); // Connect to the database
mysql_select_db($db);

function cleanData(&$str) {
    if (strstr($str, '"'))
        $str = '"' . str_replace('"', '""', $str) . '"'; // escape fields that include double quotes
}

$colnames = array(
        'oen' => "OEN",
        'first_name' => "Legal First name",
        'second_name' => "Legal Second Name",
        'last_name' => "Legal Last name",
        'native_language' => "Language First Spoken",
        'birth_date' => "Birth Date",
        'gender' => "Gender",
        'school_number' => "School Number",
        'osr' => "Main School",
        'postal_code' => "Postal Code",
        'canadian_citizen' => "Status in Canada",
        'date_entry' => "Year of Entry",
        'start_date' => "Enrolment Start Date",
        'end_date' => "Enrolment End Date",
        'literacy_status' => "Literacy Status",
        'com_inv_hours' => "Community Involvement Hours to Date",
        'oces_course' => "Ministry Course Code",
        'start_date' => "Course Start Date",
        'end_date' => "Course End Date",
        'credit_earned' => "Earned Credit Value",
        'ft_marks' => "Final Mark",
        'course_status' => "Course Complete",
        'repeated_course' => "Repeated Course",
        'oces_dip' => "Diploma Issued",
        'issue_date' => "Date Issue");

function map_colnames($input) {
    global $colnames;
    return isset($colnames[$input]) ? $colnames[$input] : $input;
}

$flag = false;
$result = mysql_query("SELECT student_information.oen, student_information.first_name, student_information.second_name, student_information.last_name, student_information.native_language, student_information.birth_date, student_information.gender, student_information.school_number, student_information.osr, student_information.postal_code, student_information.canadian_citizen, student_information.date_entry, course_information.start_date, course_information.end_date, student_information.literacy_status, student_information.com_inv_hours, course_information.oces_course, course_information.credit_earned, course_information.ft_marks, course_information.course_status, course_information.repeated_course, course_information.cr_language, student_information.oces_dip, student_information.issue_date FROM student_information, course_information WHERE student_information.searcher = 'y' AND student_information.student_number = course_information.student_number ") or die('Query failed!');
$filename = 'OnSIS_export.csv';
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
$out = fopen("php://output", 'w');

// filename for download
while (false !== ($row = mysql_fetch_assoc($result))) {
    if (!$flag) { // display field/column names as first row
        $firstline = array_map("map_colnames", array_keys($row));
        fputcsv($out, $firstline, ',', '"');
        $flag = true;
    }
    array_walk($row, 'cleanData');
    fputcsv($out, array_values($row), ',', '"');
}

fclose($out);

A: In your query, something like:
SELECT IF(student_information.gender = 'M' then 'Male' else 'Female') .....

Alternately you could create a join table with M and Male row and F and Female row, but that might be overkill.
I'm old fashioned and assuming only two genders.
EDIT: SELECT IF(gender='M','Male','Female') ... FROM student_information ...

A: array_walk can actually give you the key of the item in the array as well as its value. So you could do something like this in your cleanData function where you check the array index and if it's one where the value needs changing update $str:
function cleanData(&$str, $key) {
    switch($key) {
        case 'gender':
            if ($str=='M') $str= 'Male';
            elseif($str=='F') $str= 'Female';
            break;
        // ... other cases
    }

    if (strstr($str, '"'))
        $str = '"' . str_replace('"', '""', $str) . '"'; // escape fields that include double quotes

}


text:
Q: Reviving an obsolete Fox Pro application I am working with a client to revive his old software which was developed around 14 years ago using Foxpro2.6.
My problem is that client just have the source code (in the form of .prg files)and database files with him but there is neither any documentation nor comments in source code to guide me what does what...even the database files are not correctly named.
My only option in this scenario seems to go through the .prg files and understand which command updates which database record and how....but there are around 300 .prg files and I don't know Fox Pro at all (I mean I was in 9th standard when this thing became obsolete!!).
Any suggestion or idea to make this work easy, perhaps a .prg to C converter which can help me a lot.
Please help....it is becoming a nightmare
PS : I dont have problem with the database conversion but the front end and functional source code which too is written in the FoxPro2.6 and saved as .prg extension is the problem as I dont know the language and there is no documentation.

A: In reality, you will need to rewrite the application from scratch.
The first thing I would advise to do is to convert a copy of the project to the last version of Visual FoxPro (9 SP2), then at least you have an IDE to work in and some basic tools like search / replace, and reformatting source code to make it more readable.
See http://www.alvechurchdata.co.uk/foxconvert.htm for basic details on conversion. Note that if the original program used third-party or custom libraries (e.g. .fll files) then you won't
be able to run the converted program.
FoxPro 2.6 is a straightforward enough procedural language: unfortunately it is (almost) inevitable that the program logic will be mixed in with the window (screen) definitions and behaviour, and as SQL is built into the language then the data access will all be mixed in there as well.
If contracting someone with more experience to do the conversion is no option, then you might as well just dive in - there are still plenty of people who know FoxPro2.6 to help out when you get stuck: start from the main program and see where it goes from there.

A: As Stuart mentioned, conversions and such...  I actually do Foxpro / Visual Foxpro and work with another individual who would be able to contract with you to help jump-start and wrap your head around the conversion and quick analysis of what's really going on.
Yes, old .prg files are somewhat simple, but even back in the old FoxBase, FoxPlus, Foxpro Windows days, there were a lot of ugly coders out there.  If you are interested, let me know.  I've been doing Fox since before Microsoft bought it...

A: There's an foxdoc.exe in FP2.6, when run, you will have full documentation which prg it calls and which dbf it uses. Hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dev c++ no da el resultado correcto Tardes o Noches tengo un problema al hacer este problema en Dev c++ que cuando ejecuto el programa me arroja un resultado ilogico y no se a que se debe este error agradecería una respuesta de su parte.
Gracias

A: El error está en la línea número 19, no le estás pasando qué variables quiere que muestre con el %i.
Es decir, si tú tienes que mostarar cuánto vale n, lo que haces es: printf("%i", n), acuérdate siempre de pasar la variable, porque sino mostrará cualquier cosa.
Este sería tu código arreglado:
#include <stdio.h>

int main(){
    int i,n,in;
    printf(" Ingrese n: ");
    scanf("%i", &n);
    i=0;
    in=1;
    while(i<n){ // no es menor igual a n, porque sino mostrara n+1 numeros pares
        if(in%2==0){
            printf(" %i.\n",in); // paso in porque in es par
            i++;
        }
        in++;
    }
    system("pause");
    return 0;
}

La ejecución con n=2, te dará:

Ingrese n: 2
2.
4.

Aclaración:
No te arreglé el in=1; porque supuse que estás trabajando con números pares naturales, no enteros positivos o iguales a 0.


text:
Q: "Gridview Images" and "Full screen" fragments in multi pane(android) I'm new android..my english little bit:(
I want develop multi pane app.
Two fragments "Gridview" and "Full screen"
I know multi pane, but i dont know Gridview and Full screen in multi pane.
Because all samples for ListView.
help me please
this app good for me but too complex=
http://www.codeproject.com/Articles/779293/Building-Dynamic-UI-for-Android-Devices

A: Its a simple implementation if i understand your question correctly
------------- Creating GridView ------------

*

*For GridView you need an adapter for your GridView Object and images for columns, an example using country list and flag images,

Create drawable folder inside res and add country flag images inside drawable folder

*Create gridlayout.xml in res/layout
   <RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/border"
    android:padding="5dp">

    <ImageView
    android:id="@+id/gridimage"
    android:layout_height="65dp"
        android:layout_width="65dp"
        android:src="@drawable/icon"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">
    </ImageView>

    <TextView
        android:id="@+id/gridtext"
        android:text="TextView"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="2dp"
        android:layout_centerHorizontal="true"
        android:textSize="18sp"
        android:ellipsize="marquee"></TextView>

</RelativeLayout>

*Create gridrow.xml in res/Layout folder

<GridView
    android:id="@+id/gridView1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:numColumns="auto_fit"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp">
</GridView>

*Create GridAdapter.java class
public class GridAdapter extends BaseAdapter {
    private ArrayList<String> CountryList;
            private ArrayList<Integer> CountryFlag;
            private Activity activity;
            public GridAdapter(Activity activity,ArrayList<String> CountryList, ArrayList<Integer> CountryFlag){
super();this.CountryList = CountryList;
            this.CountryFlag = CountryFlag;
            this.activity = activity;}
    @Override
        public int getCount() {
            return CountryList.size();
        }

        @Override
        public String getItem(int position) {
            return CountryList.get(position);
        }

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

        public static class ViewHolder
        {
            public ImageView imgViewFlag;
            public TextView txtViewTitle;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder view;
            LayoutInflater inflator = activity.getLayoutInflater();

            if(convertView==null)
            {
                view = new ViewHolder();
                convertView = inflator.inflate(R.layout.gridview_row, null);

                view.txtViewTitle = (TextView) convertView.findViewById(R.id.gridtext);
                view.imgViewFlag = (ImageView) convertView.findViewById(R.id.gridimage);

                convertView.setTag(view);
            }
            else
            {
                view = (ViewHolder) convertView.getTag();
            }

            view.txtViewTitle.setText(CountryList.get(position));
            view.imgViewFlag.setImageResource(CountryFlag.get(position));

            return convertView;
        }

}

*Create Fragment GridViewActivty

public class GridViewActivty extends Fragment {
  private ArrayList CountryList = new ArrayList();
  private ArrayList CountryFlag = new ArrayList();
  private GridView mygrid;
  private GridAdapter adapter;
    private Context context;
    public GridViewActivty(){}
    @Override
   public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
        { View rootView = inflater.inflate(R.layout.gridlayout.xml, container, false);
          CountryList = new ArrayList<String>();
          CountryList.add("South Africa");
          CountryList.add("Spain");
          CountryList.add("Canada");
          CountryList.add("China");
          CountryList.add("France");
          CountryList.add("Germany");
          CountryList.add("Iran");
          CountryList.add("Italy");
          CountryList.add("Japan");
          CountryList.add("Korea");
          CountryList.add("Mexico");
          CountryList.add("Netherlands");
          CountryFlag = new ArrayList<Integer>();
              CountryFlag.add(R.drawable.southafrica);
              CountryFlag.add(R.drawable.spain);
              CountryFlag.add(R.drawable.canada);
              CountryFlag.add(R.drawable.china);
              CountryFlag.add(R.drawable.france);
              CountryFlag.add(R.drawable.germany);
              CountryFlag.add(R.drawable.iran);
              CountryFlag.add(R.drawable.italy);
              CountryFlag.add(R.drawable.japan);
              CountryFlag.add(R.drawable.korea);
              CountryFlag.add(R.drawable.mexico);
              CountryFlag.add(R.drawable.netherlands);
             adapter = new GridAdapter(this.getActivity(),CountryList, CountryFlag);

        mygrid = (GridView)rootView.findViewById(R.id.gridview1);

        mygrid.setAdapter(adapter);
        mygrid.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                // TODO Auto-generated method stub

            }
        }
                );
        return rootView;

        }

}

----------- Creating Full Screen --------

*Create fullscreen.xml inside Layout Folder
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</RelativeLayout>

>

*Create FullScreen.java Fragment
 public class Fullscreen extends Fragment{    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
         savedInstanceState)
{ View rootView = inflater.inflate(R.layout.fullscreen.xml, container, false);
         requestWindowFeature(Window.FEATURE_NO_TITLE);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

         WindowManager.LayoutParams.FLAG_FULLSCREEN);

            }

        return convertView; }


text:
Q: email form using vanilla JavaScript button I have code below for a contact form I created using HTML, CSS and JavaScript. Is it possible to have the submit button on the preview page send an email with all the content that was filled out on the main page? Is this possible with just vanilla JavaScript? Anything helps, cheers!

var categoryItems = document.querySelectorAll("#category-dropdown > a"),
    locationItems = document.querySelectorAll("#location-dropdown > a");

addDropdownEventListeners(categoryItems, 'Category');
addDropdownEventListeners(locationItems, 'Location');

function addDropdownEventListeners(items, labelName) {
    for (var i = 0; i < items.length; i++) {
        items[i].addEventListener("click", function(e) {
            document.getElementById("label" + labelName + "1").innerHTML = e.target.innerHTML;
            document.getElementById("label" + labelName).innerHTML = e.target.innerHTML;
        });
    }
}

function openNav() {

       document.getElementById("myNav").classList.remove("collapsed");
        var input = document.getElementById("txtDetail");
        var value = input.value;
        var label = document.getElementById("labelDetail");
        label.innerHTML = value;

        var input = document.getElementById("txtName");
        var value = input.value;
        var label = document.getElementById("labelName");
        label.innerHTML = value;

        var input = document.getElementById("txtNumber");
        var value = input.value;
        var label = document.getElementById("labelNumber");
        label.innerHTML = value;

        var input = document.getElementById("txtEmail");
        var value = input.value;
        var label = document.getElementById("labelEmail");
        label.innerHTML = value;

        document.getElementById("myNav").style.width = "100%";
    }
    function closeNav() {
        document.getElementById("myNav").style.width = "0%";
        document.getElementById("myNav").classList.add("collapsed");
    }

document.getElementById('file-upload').onchange = uploadOnChange;

function uploadOnChange() {
  var filename = this.value;
  var lastIndex = filename.lastIndexOf("\\");
  if (lastIndex >= 0) {
    filename = filename.substring(lastIndex + 1);
  }
  document.getElementById('filename').innerText = filename;

  var labelFile = this.value;
  var lastIndex = labelFile.lastIndexOf("\\");
  if (lastIndex >= 0) {
    labelFile = labelFile.substring(lastIndex + 1);
  }
  document.getElementById('labelFile').innerText = labelFile;
}
 * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      -webkit-font-smoothing: antialiased;
      -moz-font-smoothing: antialiased;
      -o-font-smoothing: antialiased;
      font-smoothing: antialiased;
      text-rendering: optimizeLegibility;
    }

    .container {
      width: 100%;
      margin: 0 auto;
      position: relative;
    }

    #contact input[type="text"],
    #contact input[type="email"],
    #contact input[type="tel"],
    #contact textarea,
    #contact button[type="submit"] {
      font: 400 12px/16px "Verdana", Verdana;
    }

    #contact {
      background: #F9F9F9;
      padding: 25px;
      box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
      height:525px;
    }

    #contact h3 {
      display: block;
      font-family:Verdana;
      font-size: 24px;
      font-weight: 300;
      margin-bottom: 10px;
    }

    #contact h4 {
      margin: 5px 0 15px;
      display: block;
      font-family:Verdana;
      font-size: 13px;
      font-weight: 400;
    }

    #contact h5 {
      text-decoration:underline;
      display: block;
      color:#4CAF50;
      font-family:Verdana;
      font-size: 19px;
      font-weight: normal;
      margin-bottom: 10px;
    }

    #contact h6 {
      text-decoration:underline;
      display: block;
      text-align:left;
      color:#4CAF50;
      font-family:Verdana;
      font-size: 15px;
      font-weight: normal;
      margin-bottom: 10px;
    }

    .fieldset {
      border: medium none !important;
      margin: 0 0 10px;
      min-width: 100%;
      padding: 0;
      width: 100%;
    }

    #contact input[type="text"],
    #contact input[type="email"],
    #contact input[type="tel"],
    #contact textarea {
      width: 100%;
      border: 1px solid #ccc;
      background: #FFF;
      margin: 0 0 5px;
      padding: 10px;
    }

    #contact input[type="text"]:hover,
    #contact input[type="email"]:hover,
    #contact input[type="tel"]:hover,
    #contact textarea:hover {
      -webkit-transition: border-color 0.3s ease-in-out;
      -moz-transition: border-color 0.3s ease-in-out;
      transition: border-color 0.3s ease-in-out;
      border: 1px solid #aaa;
    }

    #contact textarea {
      height: 100px;
      max-width: 100%;
      resize: none;
    }

    #button{
      float:right;
      cursor: pointer;
      padding: 13px 32px;
      width:125px;
      height:45px;
      border: none;
      font-family:Verdana;
      background: #4CAF50;
      color: #FFF;
      margin: 0 0 5px;
      font-size: 15px;
    }

    #button:hover{
      background: #43A047;
      -webkit-transition: background 0.3s ease-in-out;
      -moz-transition: background 0.3s ease-in-out;
      transition: background-color 0.3s ease-in-out;
    }

    #button:active {
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5);
    }

    #contact input:focus,
    #contact textarea:focus {
      outline: 0;
      border: 1px solid #aaa;
    }

    ::-webkit-input-placeholder {
      color: #888;
    }

    :-moz-placeholder {
      color: #888;
    }

    ::-moz-placeholder {
      color: #888;
    }

    :-ms-input-placeholder {
      color: #888;
    }

    .dropbtn {
        background-color: #4CAF50;
        color: white;
        padding: 13px;
        font-size: 16px;
        width:125px;
        height:45px;
        border: none;
        cursor: pointer;
    }

    .dropdown {
        position: relative;
        display: inline-block;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 160px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1;
      max-height:150px;/* you can change as you need it */
   overflow:auto;/* to get scroll */
    }

    .dropdown-content a {
        color: black;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
    }

    .dropdown-content a:hover {background-color: #f1f1f1}

    .dropdown:hover .dropdown-content {
        display: block;
    }

    .dropdown:hover .dropbtn {
        background-color: #3e8e41;
    }
    input[type="file"]{
        display: none;
    }
    .custom-file-upload {
      cursor: pointer;
      padding: 13px 16px;
      width:125px;
      height:45px;
      border: none;
      font-family:Verdana;
      background: #4CAF50;
      color: #FFF;
      margin: 0 0 5px;
      font-size: 15px;
      display: inline-block;
      vertical-align: top;
      text-align: center;
    }
    .custom-file-upload:hover{
        background: #43A047;
      -webkit-transition: background 0.3s ease-in-out;
      -moz-transition: background 0.3s ease-in-out;
      transition: background-color 0.3s ease-in-out;
    }
    .custom-file-upload:active{
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5);
    }
    .overlay {
        height: 525px;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: #F9F9F9;
        overflow-x: hidden;
        transition: 0.5s;
        padding-top: 25px;
        padding-bottom: 25px;
        padding-left: 25px;
        padding-right: 25px;
    }

    .overlay.collapsed {
        padding-top: 25px;
        padding-bottom: 25px;
        padding-left: 0;
        padding-right: 0;
    }

    .overlay-content {
        position: relative;
        /*top: 5%;*/
        width: 100%;
        height: 100%;
        text-align: center;
        /*margin-top: 25px;*/
    }

    .overlay-content .container {
        height: 100%;
    }

    .overlay-content fieldset:last-child {
        position: absolute;
        bottom: 0;
        margin-bottom: 0;
    }

    .overlay a {
        padding: 5px;
        margin-top:-15px;
        text-decoration: none;
        font-size: 36px;
        color: #818181;
        display: block;
        transition: 0.3s;
        z-index: 100;
    }

    .overlay a:hover, .overlay a:focus {
        color: #bababa;
    }

    .overlay .closebtn {
        position: absolute;
        top: 15px;
        right: 15px;
        font-size: 40px;
    }

    @media screen and (max-height: 450px) {
      .overlay a {font-size: 20px}
      .overlay .closebtn {
        font-size: 40px;
        top: 15px;
        right: 35px;
      }
    }
    #contact-submit{
      float:right;
      cursor: pointer;
      font-size:15px;
      padding: 13px 32px;
      width:125px;
      height:45px;
      border: none;
      font-family:Verdana;
      background: #4CAF50;
      color: #FFF;
      margin: 0 0 5px;
    }

    #contact-submit:hover{
      background: #43A047;
      -webkit-transition: background 0.3s ease-in-out;
      -moz-transition: background 0.3s ease-in-out;
      transition: background-color 0.3s ease-in-out;
    }

    #contact-submit:active {
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5);
    }
    #label{
      float:left;
      text-decoration:underline;
      font-family:Verdana;
      font-size:13px;
    }
    #labelDetail{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
      text-align:left;
      max-height: 115px;
      overflow: auto;
    }
    #labelName{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
    #labelNumber{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
    #labelEmail{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
#labelAttach{
  float:left;
  text-decoration:underline;
  font-family:Verdana;
  font-size:13px;
  padding-top:12px;
  color:#4CAF50;
}
#labelFile{
  float:left;
  font-family:Verdana;
  padding-top:16px;
  font-size:10px;
  padding-left:7px;
}
#filename{
  font-family:Verdana;
  font-size:10px;
  padding-top:16px;

}
   #labelLocation{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
   #labelLocation1{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
   #labelCategory{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
   #labelCategory1{
      padding-left:15px;
      float:left;
      font-family:Verdana;
      font-size:13px;
    }
    #locationlabel{
      float:left;
      font-family:Verdana;
      font-size:13px;
      color:#4CAF50;
    }
    #categorylabel{
      float:left;
      font-family:Verdana;
      font-size:13px;
      color:#4CAF50;
    }

      <form id="contact">

Connect With HR

        <fieldset class="fieldset">

            <button class="dropbtn" id="my-location">Location</button>

        Gibraltar House
        WLSC
        CMF
        Motorized
        Telepharmacy
        Anchorage-PAW
        ADC
        NSQM
        Bellevue-PAW
        PNW

      <button class="dropbtn" id="my-category">Category</button>

401K
Accidental Death & Dismemberment
Banking Info Change
Bereavement
Building Access
Canada Savings Bonds
Compensation
Customer Incident
Direct Deposit
Effectiveness Assessment Process
Employee and Family Assistance Program
Employee Discount
Employee History
Employee Ownership Plan
Employee Referral Program
Employee Survey
Employment Eligibility Verification
Expenses
Group Health & Dental
Group RRSP
Health & Safety
Health Savings Account
Holiday Calendar
Holidays/Leaves
Life Insurance
Medical Dental & Vision
New Hire Orientation
Other
Payroll
Pension
Personal Info change
Policy
Position Change
Record of Employment
Recruitment
Resignation/Termination
Shipment of Personal Belongings
Short Term Disability
Short Term Incentives Program (STIP)
Sick Leave
Tax Form
Temporary Disability Insurance
Time and Attendance
Training
Tuition Assistance Program (TAP)
Vacation
Work Schedule
Workers Compensation

        </fieldset>
        <fieldset class="fieldset">
          Location:

        </fieldset>
        <fieldset class="fieldset">
          Category:

        </fieldset>
        <fieldset class="fieldset">
          <textarea id="txtDetail" placeholder="Detail..." tabindex="2"></textarea>
        </fieldset>

Contact Information

        <fieldset class="fieldset">
            <input id="txtName" placeholder="Name" type="text" tabindex="4" >
            <input id="txtNumber" placeholder="Preferred Contact Number" type="tel" tabindex="5">
            <input id="txtEmail" placeholder="Preferred Email" type="email" tabindex="6">
        </fieldset>
        <fieldset class="fieldset">

         Attachment

    <input id="file-upload" type="file"/>

      ×

Summary

              <fieldset class="fieldset">
            Location:

          </fieldset>
              <fieldset class="fieldset">
            Category:

          </fieldset>
          <fieldset class="fieldset">
            Detail:

          </fieldset>

Contact Information

              <fieldset class="fieldset">
                Name:

                </fieldset>
              <fieldset class="fieldset">
                Preferred Contact Number:

                </fieldset>
              <fieldset class="fieldset">
                Preferred Email:

                </fieldset>
       <fieldset class="fieldset">
         Attachment:

          <button name="submit" id="contact-submit" data-submit="...Sending">Submit</button>
        </fieldset>

    Preview
          </fieldset>
      </form>

A: No, you can't send e-mails from Javascript. You need some server side logic to do this.
See the answers at a similar question: How to send an email from JavaScript
However, there are a few API's available which send e-mails. So basically you provide them with your e-mail and there backend sends the e-mail.

*

*https://www.emailjs.com/

*http://smtpjs.com/
I haven't tried those so I can't tell you how good they are.


text:
Q: Change "ListPlot" to 16 bit accuracy? I have (with the help of this forum) managed to plot a bifurcation diagram with the following code:
F = (r # (1 - #) &)
S = (Subdivide[3.84, 3.855, 1200])

nestedlist = Table[{r, #} & /@ NestList[F, 0.00000000001, 1000][[-100 ;;]], {r, S}];
flatlist = Flatten[nestedlist, 1];

ListPlot[flatlist, PlotRange -> {.45, .55}

I'm trying to change my plot to 16-bit accuracy, and I was told to use the code:
to16bits[#_] := Floor[2^16*#]*2.^-16

How exactly can I integrate this into the code above? I've tried many different things but I only manage to get "Options expected (instead of Null) beyond position 1" or "infinity" as an output.
Any help would be appreciated!


text:
Q: Google Maps Places API - how to get name of a place? When I change pointer on the map, I want to get name of a place.
I'm able to get lat and lng of a place on the map, but I want to get name of that place. For exampl lat: 43.669992353311635, lng: -79.4108552  is TORONTO. What is mistake in my code?
library: react-google-maps
  onDragEnd: ({ setDrag, setCenter, setUseMyLocation, onChangeMapCoords  }) => () => {
    const center = refs.map.getCenter();
    const placeName = refs.map.getPlaces();
    console.log("ACTION sp8 map center", placeName)
    // console.log("ACTION sp8 map center", { lat: center.lat(), lng: center.lng()})

    setUseMyLocation(false);
    setDrag(false);
    setCenter(({ lat: center.lat(), lng: center.lng() }));
    resetSearchBox();
  },

A: You can use this way
 val geocoder = Geocoder(requireContext(), Locale.getDefault())
  // parameter 1 is the number of results you want, a maximum of 5
 val addresses: List<Address> = geocoder.getFromLocation(lat, lng, 1)

A: You can use the Geocoding service to reverse geocode the latLng you are getting onDragEnd. This way, you can get the name of the address from the reverse geocoding.
Here is a sample code and the code snippet of Geocoding services below:
  onDragEnd(e) {
    console.log(e.latLng);
    const geocoder = new google.maps.Geocoder();
    let loc = e.latLng;
    geocoder.geocode({ location: loc }, (results, status) => {
      if (status === "OK") {
        if (results[0]) {
          console.log(results[0].formatted_address);
        } else {
          window.alert("No results found");
        }
      } else {
        window.alert("Geocoder failed due to: " + status);
      }
    });
  }


text:
Q: What would happen if I lit a candle in a room "painted" in vantablack? The title is pretty much it.
If I brought light source into a room (a space) (completely) covered in Vantablack.
How would that affect the visibility in that room (space). (if it would make any difference at all)

Title Note: Not necessarily a candle, a light of some sort (which would be sufficient enough to fully lighten a conventional room).

Related Questions:

*

*Where does the energy go in Vantablack?

*Darkest matter on Earth ("pure black")

A: Well the walls of the room wont scatter any light, but everything else will scatter light just as it normally does. It'll be like holding a candle in space.

A: You would just see the candle and nothing else. The walls would almost completely absorb all incident radiation from the candle, so there'll be no reflection from it, but the EM radiation from the candle would still enter your eyes so you would still see it.

A: The effect would be almost indistinguishable from lighting said candle in a room painted with normal black paint.  The shadows would be rather stark.
The difference would be that there would be no diffuse light coming off of the walls.  Normally some tiny fraction ( a few percent) of the light would bounce off of the walls, providing some light on the surfaces that are occluded from your light source.  However, this effect is tremendously slight.
To see how this would work, we can look at the opposite.  In 3d rendering, one famous construct is the Cornel Box

Note that the light off of the red and green walls causes the boxes to have a slight hue on the sides nearest the walls.   This is the diffuse effect that the Cornel box seeks to demonstrate.
Of importance is just how hard the Cornel box had to work to create a structure which demonstrated this effect.  Typically the effect is so slight that 3d graphics engines don't even model it.  Black walls (even non-vantablack) are especially good at not causing this effect.  You could certainly measure it with a photometer, but the human eye would not notice the difference.


text:
Q: free(): invalid next size (normal) and other errors with caret's train function I previously developed a random forest classification pipeline which was working without error on the same datasets until recently. During parameter optimization with parallelization of 8 cores, the following errors have been occurring for the classification task on execution:
free(): invalid next size (normal)
corrupted size vs. prev_size
Error in unserialize(socklist[[n]]) : error reading from connection
This error only occurs on a specific classification task, not on other classification tasks using the same input features for training. There doesn't appear to be any issues with classification labels themselves. I've increased the number of cores used to run the task from 8 to 14 and the following error occurs after a short runtime:
malloc.c:4033: _int_malloc: Assertion `(unsigned long) (size) >= (unsigned long) (nb)' failed.
These errors occur for the following line of code:
train(final[1:(dim(final)[2]-1)], final$Event, method = "rf", metric = "F1", trControl = tc, tuneGrid = tg, nodesize = i, proximity = TRUE, strata = final$Event,
sampsize = unname(c(table(final$Event)[1], table(final$Event)[1]*2)))
It looks like this may be an error relating to glibc? I am so far struggling to understand what these errors mean, how to go around fixing them, and why they have arisen when the pipeline worked recently on these datasets. I am running the analysis on a Ubuntu 18.04.


text:
Q: Java 'print *variable*' So, I just took a CS test, and one of the questions, was a for loop, and after it loops, it does...
print k;
I don't think it is possible to 'print' a variable, using just, 'print'..
Someone tell me, if it's possible or not, because one of my teammates say it is possible.

A: As 0A0D said probably pseudocode, the normal way to print in java is to do a
System.out.print(variable);

A: That looks like pseudocode to me. This is common on exams. Be sure to recognize the difference between pseucode and java code. In Java, methods require parenthesis.

A: I'm sure it was pseudocode. they do that to facilitate the exercise code

A: System.out.print(k);

I suggest at least trying to google or read a basic guide to Java before asking these kinds of questions.

A: In java code you can't use just the word print to print a variable as it is not recognized by java. You have to use the System.out.print or something of that nature for output.


text:
Q: Excel: Retrieve data from within a specific html tag on a website and insert that data into an Excel worksheet I was looking at the web queries in excel and how you can retrieve data from a html table in a website quite easily. I wish to get a single string from within a html tag:
 I WANT THIS DATA

Is this possible? If it is, how? A vbn solution would also be useful.
Thanks!

A: you can get that information from the DHTML DOM Document
see these links:

*

*MSDN Library - DOM Document Reference

*MSDN Library - getElementById Method


text:
Q: How to make the aws command available to sh when using the ansible shell module? I'm trying to run the following task by using aws cli, because of the aws_s3 module flats out all the bucket keys. However, I keep getting aws: not found error.
aws cli is correctly installed because running the exact same command from the host, works fine.
My task:
- name: Try list
  shell: aws s3 ls "{{ s3_bucket }}"

The full error:
fatal: [cassandra-node-1]: FAILED! => {
    "changed": true,
    "cmd": "aws s3 ls \"cassandra-snapshotter-test2\"",
    "delta": "0:00:00.002900",
    "end": "2019-05-12 13:48:25.705324",
    "invocation": {
        "module_args": {
            "_raw_params": "aws s3 ls \"cassandra-snapshotter-test2\"",
            "_uses_shell": true,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "warn": true
        }
    },
    "msg": "non-zero return code",
    "rc": 127,
    "start": "2019-05-12 13:48:25.702424",
    "stderr": "/bin/sh: 1: aws: not found",
    "stderr_lines": [
        "/bin/sh: 1: aws: not found"
    ],
    "stdout": "",
    "stdout_lines": []
}

Why can't I run the aws cli from the Ansible task?

A: The AWS binary is not available to the sh interpreter on this host.
From a shell session run
$ which aws
to find where the awscli is located.
Make sure this directory is included in the PATH environment variable
$ echo $PATH
If it is not you can either configure your server to include it when a shell is opened
# bash
$ echo 'export PATH=$PATH:/path/to/awscli/dir'  >> ~/.bash_profile

# KSH/sh
$ echo 'export PATH=$PATH:/path/to/awscli/dir'  >> ~/.profile

Alternately you can use the ansible environment property to set environment variables in memory for a particular play, task, etc.
environment:
  PATH: "{{ lookup('env', 'PATH) }}:/path/to/awscli/dir"

Finally, for brevity, you can modify the shell ansible is using for the shell module in your ansible.cfg using the executable key under the [defaults] section. This would allow you to change it from the sh interpreter to something else like bash.


text:
Q: Upload Json file items to sitecore Media Library using Sitecore Item Web API I would like to extract the items from Json file from my local to media library of the Sitecore Content using sitecore item Web API. Does anyone have excamples to access WebApi and upload to the media library items?
thanks,

A: This post may help you. It has a helper to upload files to Sitecore`s Media Library:
http://www.sitecoreinsight.com/how-create-media-items-using-sitecore-item-web-api/
To create regular items (not in the media library) I suggest you to use this tool:
http://sitecorecreative.wordpress.com/2013/02/28/sitecore-web-api-client-library/


text:
Q: mysql - subqueries and joins I'm not quite sure if this is the right approach, this is my situation:
I'm currently trying to select 15 galleries and then left join it with the user table through the id but I also want to select one random picture from each gallery however from what I know you can't limit the left join (picture) to only pick up one random picture without doing a subquery.
Here is what I got so far but its not working as it should:
SELECT galleries.id, galleries.name, users.username, pictures.url
FROM galleries
LEFT JOIN users ON users.id = galleries.user_id
LEFT JOIN pictures ON (
    SELECT pictures.url
    FROM pictures
    WHERE pictures.gallery_id = galleries.id
    ORDER BY RAND()
    LIMIT 1)
WHERE active = 1
ORDER BY RAND()
LIMIT 15

I also tried to do this with Active Record but I got stuck after doing two left joins, is it possible to do get a subquery in here:
$this->db->select('galleries.id, galleries.name, users.id as user_id, users.username');
$this->db->from('galleries');
$this->db->join('users', 'users.id = galleries.user_id','left');
$this->db->join('pictures','pictures.gallery_id = galleries.id AND','left');
$this->db->where('active',1);

I hope its not to messy but I'm really starting to get confusing by all the sql queries..
Edit:
Active Record with CodeIgniter

A: You could fetch a random picture in a subquery:
select
    g.name, u.username,
    (select url from pictures p where p.gallery_id = g.gallery_id
     order by rand() limit 1) as url
from galleries g
left join users u on g.user_id = u.id
where g.active = 1

Based on your comment, you could select a picture for each gallery in a subquery. This is assuming the picture table has an ID column.
select
    g.name, u.username, p.url, p.name
from (
    select id, user_id, name,
        (select id from pictures p
         where p.gallery_id = g.gallery_id
         order by rand() limit 1) as samplepictureid
    from galleries
    where g.active = 1
) g
left join users u on g.user_id = u.id
left join pictures p on p.id = g.samplepictureid

A: SELECT
    g.id,
    g.name,
    u.username,
    p.url
FROM
    galleries g
    INNER JOIN (SELECT DISTINCT
         gallery_id,
         (SELECT url FROM pictures ss WHERE ss.gallery_id = s.gallery_id
             ORDER BY RAND() LIMIT 1) AS url
     FROM
         pictures s) p ON
        g.id = p.gallery_id
    LEFT OUTER JOIN users u ON
        g.user_id = u.id
WHERE
    g.active = 1

This query will go out and select a gallery, then it will find any gallery with a picture (if you want to return galleries without a picture, change INNER JOIN to LEFT OUTER JOIN, and you'll be fine). After that, it joins it up with users. Now, of course, this puppy is going to return every frigging gallery for however many users you have (hoorah!). You may want to limit the user in the WHERE clause (e.g.-WHERE u.id = 123).  Otherwise, you're going to get more results than you'd expect.  That, or do an INNER JOIN on it.


text:
Q: How do i make whole area clickable Creating a navigation bar. How do i make the whole area around the text not just the text clickable? I put display: block; and it still does not work. Now I'm just writing anything so i could post the question. Thank you!
.containter{
    width: 80%;
    margin: 0 auto;
    }
header{
    background: deeppink;
    }
header::after{
    content:'';
    display: table;
    clear: both;
    }
.logo{
    float: left;
    padding: 10px 0;
    margin-left: 5px;
    }
nav{
    float: left;
    }
nav ul{
    margin:5px;
    padding:0;
    list-style: none;
    overflow: hidden;
    }
nav li{
    float: left;
    display: block;
    margin-left: 100px;
    padding-top: 27px;
    }
nav a{
    text-decoration: none;
    color: white;
    text-transform: uppercase;
    font-family: times new roman;
    text-align: center;
    display: block;
    }

nav a:hover{
    background-color: #C71585;
    }

A: For making the area clickable you can use pointer events property of css like
    div {
      pointer-events: none;
    }

    div{
      pointer-events: auto;
    }

    div{
      pointer-events: all;
    }

Can try it out if it works for you none will disable the mouse click where as auto and all will allow the mouse click..!!

A: try to change to these two
nav li{
    float: left;
    display: block;
    }
nav a{
    text-decoration: none;
    color: white;
    text-transform: uppercase;
    font-family: times new roman;
    text-align: center;
    display: block;
    margin-left: 100px;
    padding-top: 27px;
    }


text:
Q: How to style custom control inside a ListView in JavaFX I have created a custom control extending HBox:
FXML
<fx:root alignment="CENTER_LEFT" prefHeight="80" prefWidth="400.0" spacing="5" styleClass="email-view"
         stylesheets="stylesheet.css" type="javafx.scene.layout.HBox" xmlns="http://javafx.com/javafx/8.0.112"
         xmlns:fx="http://javafx.com/fxml/1">
    <Region fx:id="unreadIndicator" prefWidth="5.0"/>

    <Region prefWidth="10"/>
    <VBox prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
        <Region prefHeight="10"/>
        <HBox>
            Anindya Chatterjee
            <Region HBox.hgrow="ALWAYS"/>
            31st Dec 1999
            <Region prefWidth="5"/>
        </HBox>
        <Region prefHeight="5"/>
        <HBox>
            Test Mail Subject
            <Region HBox.hgrow="ALWAYS"/>
            <ImageView fx:id="attachmentLabel" styleClass="attachment-label">
                <Image requestedHeight="15" requestedWidth="15" url="@attach.svg"/>
            </ImageView>
            <Region prefWidth="5"/>
        </HBox>
        <Region prefHeight="5"/>
        <HBox>

                Here is some text for test mail just to check how does
                it look on mock ups. The final value will change

            <Region HBox.hgrow="ALWAYS"/>
            <ImageView fx:id="favoriteLabel" styleClass="favorite-label">
                <Image requestedHeight="15" requestedWidth="15" url="@favorite.svg"/>
            </ImageView>
            <Region minWidth="5"/>
        </HBox>
    </VBox>
</fx:root>

Java File
public class EmailView extends HBox {

    public Region unreadIndicator;
    public Label senderAvatar;
    public Label fromLabel;
    public Label dateLabel;
    public Label subjectLabel;
    public ImageView attachmentLabel;
    public Label contentLabel;
    public ImageView favoriteLabel;

    public EmailView() {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getClassLoader().getResource("email-view.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }
}

I am using the control as a list view item. I have made changes to the css property to change the select bar color and all as follows
.list-view, .list-view:focused, .list-view:selected {
    -fx-control-inner-background: transparent;
    -fx-control-inner-background-alt: -fx-control-inner-background;
    -fx-background-color: transparent;
    -fx-padding: 0;
    -fx-fit-to-width: true;
    -fx-effect: null;
    -fx-selection-bar: transparent;
    -fx-selection-bar-non-focused: transparent;
}

.list-view .list-cell:filled:selected:focused, .list-view .list-cell:filled:selected {
    -fx-background-color: transparent;
    -fx-effect: null;
}

.list-view .list-cell:filled:hover {
    -fx-background-color: transparent;
    -fx-effect: null;
}

.email-view {
    -fx-background-color: -color-quinary;
    -fx-effect: dropshadow(three-pass-box, -color-text-inverted, 4, 0, 0, 1);
}

Now I want to change the background color of the custom control when it is selected inside the list view. The effect I am try to achieve more or less like this

Any pointer how to achieve this effect using css preferably?

A: Theoretically this set of selectors do the trick:
// Color of the list-cell selected + unselected: transparent
.list-view .list-cell,
.list-view .list-cell:filled,
.list-view .list-cell:selected,
.list-view .list-cell:focused,
 .list-view .list-cell:hover {
    -fx-background-color: transparent;
    -fx-effect: null;
}

// Color of the custom control hover
.list-view .list-cell:hover .email-view {
    -fx-background-color: greenyellow;
}

// Color of the custom control selected
.list-view .list-cell:filled:selected:focused .email-view,
.list-view .list-cell:filled:selected .email-view {
    -fx-background-color: green;
}

// Color of the custom control unselected
.email-view { -fx-background-color: gray; }

The goal is to kep the list-cell transparent all the time, and based on the pseudo-state of the list-cell set the background color of email-view. Maybe I forgot about some state, but it could be a good starting point.


text:
Q: Passing MongoDB Block from a servlet to a JSP I have the following Block which filters the data according to the filters I have applied; i.e. it should print only those data that match with "name"
            Block<Document> printBlock = new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document.toJson());
            }
       };

       collection.find(eq("name", name)).forEach(printBlock);

I wish to send this data from the current servlet to JSP so that I can display the data. How should I go about this?
EDIT:
JSP Page:
 <form action="SearchName" method="post">
      Name:  <input name="name" size="20" />
     <input type="submit"   value="Search">
  </form>

Servlet:
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     String name= request.getParameter("name");

    // Create Mongo connection to the DB
    MongoClient mongoClient = new MongoClient( "localhost", 27017);

    // Select the DB
    MongoDatabase database = mongoClient.getDatabase("myDatabase");

    // Select the collection
    MongoCollection<Document> collection = database.getCollection("myCollection");

   Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
   };
   collection.find(eq("name", name)).forEach(printBlock);
  }

So hence I want only those records which match with "name". I get till here successfully. So next how do I pass them to jsp from servlet and how are they received at JSP?. thanks in advance for help


text:
Q: Installing QGIS in virtual environment? I have a virtual environment, (my-virtualenv) bash-3.2$, running with python 3.6.5 set up using pyenv.
I installed the modules listed on the readme (owslib, PyYaml, psycopg2, jinja2, pygments, numpy, plotly). My system has python 2.7 and python 3.7 outside the virtual environment.
How do I install QGIS just within the virt environment?


text:
Q: Border for a clipped box in css I have a clipped box, that adds a diagonal line does the end of the box. I would like to add a border to it, but the border is also clipped.
Can I added a border to the clipped area using only CSS/html?  So that the white has a black border before it meets the yellow?
.yellowclippedbox {
  background-color: #F1BE3E;
  color: #880000;
  clip-path: polygon(20% 0, 100% 0%, 100% 100%, 0% 100%);
}

A: that ?

body {
  background : lightblue;
  }
#my-div {
  width      : 200px;
  height     : 250px;
  margin     : 1em;
  background : yellow;
  position   : relative;
  border     : 5px solid green;
  }
.yellowclippedbox:before {
  position   : absolute;
  top        : 0;
  left       : 50%;
  display    : block;
  content    : '';
  width      : 50%;
  height     : 100%;
  background : crimson;
  clip-path  : polygon(20% 0, 100% 0%, 100% 100%, 0% 100%);
  }


text:
Q: Как получить реальный IP-Адрес компьютера в локальной сети (Java) Я пытаюсь получить IP-Адрес компьютера в локальной сети, используя следующий код:
try {
  hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ex) {
  //...
}

На моём ПК установлен VirtualBox, и при запуске программы получаю IP-Адрес виртуальной машины:

Как исправить? Заранее спасибо!)

A: В одной из программ я получал ип таким образом. Не помню точно почему так, но там нужно отсеивать виртуальные интерфейсы.
public static String getLocalIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                // filters out 127.0.0.1 and inactive interfaces
                if (iface.isLoopback() || !iface.isUp() || iface.isVirtual())
                    continue;

                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr instanceof Inet4Address) {
                        ip = addr.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        return ip;
    }


text:
Q: enabled select option within the row with checkbox Please help i want to enable select with checkbox if the checkbox is checked within the row. the code only works within the first row but the rest is not working. the id of my checkbox is roomCheck and name is chkbox

        <input type = "checkbox" name = "chkbox" id = "roomCheck">
        <select id = "number" disabled><option>test</option></select>

        <input type = "checkbox" name = "chkbox">
         <select id = "number" disabled><option>test</option></select>

        <input type = "checkbox" name = "chkbox" id = "roomCheck">
        <select id = "number" disabled><option>test</option></select>

        <input type = "checkbox" name = "chkbox" id = "roomCheck">
        <select id = "number" disabled><option>test</option></select>

        <input type = "checkbox" name = "chkbox" id = "roomCheck">
        <select id = "number" disabled><option>test</option></select>

        <input type = "checkbox" name = "chkbox" id = "roomCheck">
        <select id = "number" disabled><option>test</option></select>

</script>

A: When you use selectors with id you must always give a unique name to each id, this is html basics, and this is why it is only working for the first row, the next ones are not identificable.
Suggested to read about jquery selectors.
There are many ways to achieve your goal but you must first change your naming for ids, they must be unique, or you can face this problem by using class selectors, among others.

A: This is the code I ended up using that fixed the issue
$(document).ready(function() {
      // Disable select elements
      $('select').each(function() {
         $(this).attr("disabled","disabled");
      });

      // Enable them on click

       $("input[type=checkbox]").click(function(){
            if($(this).closest("tr").find("td").children("input[type=checkbox]").prop("checked"))
            {
                $(this).closest("tr").find("td").children("select").removeAttr("disabled");
            }
            else
            {
                $(this).closest("tr").find("td").children("select").attr("disabled","disabled");
            }
       });
});


text:
Q: Touch keypad buttons in calabash-android Is there any way to tap on keypad button in calabash -android (like :1,2,3,4)
Note : Tap should be physical tap , as we got with "keyboard_enter_text" command in iOS

A: For Android you can use keyboard_enter_text"1,2,3,4".
You have to have touched the field first, so that it is in focus.
Is that what you are asking for?

A: Calabash doesn't support it but you can use adb to press keyboard keys
adb shell input text "what%syou%want%stype"

In ruby you can execute terminal commands in a couple of ways but I use backticks
`adb shell input text "what%syou%want%stype"`

See here for more info - http://krazyrobot.com/2014/02/calabash-android-enter-text-from-keyboard-using-adb/
EDIT: Not too sure on the cause of the downvote but here's a bit more info on my answer in case it makes any more sense to anyone.
The equivalent function of keyboard_enter_text for calabash-android has the same name.  It is in the TextHelpers module of calabash-android.  To use it, you have to
require 'calabash-android/text_helpers'

However the implementation of keyboard_enter_text seems to be different behind the scenes for android in as far as it sets the text value in the field to the whole word/phrase like it has been pasted in, rather than with individual keypresses like it does for ios.  As far as I know you can simulate the individual keypresses using adb commands if that is what you want.
I'm not sure why you would need to click on the keyboard buttons specifically, rather than just be happy that the text is in the field, as it is slower, but if you do for some reason then the adb commands should work.


text:
Q: Ajax posting null object to the mvc controller I am trying to pass an object to the MVC controller, but at controller, I get null values to the object which I passed through the ajax.
I am able to see that my object is having some data in the view, but not able to bind them to the controller.
Controller
        [HttpPost]
        public ActionResult AddImage(ImageModel imageModel)
        {
            UploadRepo.saveImage(imageModel);
            return null;
        }

Model

namespace Fileupload.Models
{
    public class ImageModel
    {

        public int Id { get; set; }

        public string ImageData { get; set; }
    }
}

My Javscript Code
        var url = input.value;
        var imageData = '';
        var finalUrL = '';
        console.log(input.files[0])
        var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
        if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
            finalUrL = await readAsDataURL(input.files[0])
            imageData = finalUrL.replace(/^data:image\/[a-z]+;base64,/, '').trim()
            var obj = {
                Id: 1,
                ImageData: imageData
            }
            $.ajax({
                url: '/Upload/AddImage',
                type: "POST",
                data: JSON.stringify(obj),

                contentType: "application/json;",
                success: function (data) {
                    //successMessage();
                    $("form")[0].reset();
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log("textstatus", textStatus, xhr)
                    // errorMessage();-
                }
            });
            console.log("imagedata", myobj);
        } else {
            $('#img').attr('src', '/assets/no_preview.png');
        }
    }

A: Attachment file in ASP.NET MVC must be of HttpPostedFileBase type. So, change your image data property  as follow i.e.
public HttpPostedFileBase ImageData { get; set; }

then in your [HttpPost] method do following to get data from the uploaded file i.e.
// Upload File data.
byte[] fileByteData = new byte[model.ImageData.InputStream.Length];
model.ImageData.InputStream.Read(fileByteData, 0, fileByteData.Length);
string fileContentType = model.ImageData.ContentType;


text:
Q: Add pale/vivid/light/dark before the color name depending on brightness and saturation I want to get the closest color to this list:
static List<Color> clist = new List<Color>()
    {
        Color.Black, Color.Brown, Color.Blue, Color.Green, Color.Red, Color.Yellow,
        Color.Gray, Color.Indigo, Color.Orange, Color.Pink, Color.Turquoise, Color.White
    };

I am getting the closest color like this but I want to add: pale/dark/vivid/light depending on the brightness and saturation of the color:
        static string closestColor2(List<Color> colors, Color target)
        {
            var colorDiffs = colors.Select(n => ColorDiff(n, target)).Min(n => n);
            int x = colors.FindIndex(n => ColorDiff(n, target) == colorDiffs);
            return colors[x].ToString();
        }

        static int ColorDiff(Color c1, Color c2)
        {
            return (int)Math.Sqrt((c1.R - c2.R) * (c1.R - c2.R)
                                   + (c1.G - c2.G) * (c1.G - c2.G)
                                   + (c1.B - c2.B) * (c1.B - c2.B));
        }

A: There are a lot of things to consider when comparing colors.
But this question has already been answered.
Here you can find a solution:
How to compare Color object and get closest Color in an Color[]?

A: My suggestion would be to first have a list of colors. In your answer you have a small list of colors but you could also add all 141 of them if you wish later on.
So create a list of colors:
    //List of Colors
    static List<Color> clist = new List<Color>{
        Color.Black, Color.Brown, Color.Blue, Color.LightSteelBlue, Color.Green, Color.Red, Color.Yellow,
        Color.Gray, Color.Indigo, Color.Orange, Color.Pink, Color.Turquoise, Color.White
    };

And then another list with the names of the colors as you want them, with "vivid", "dark" etc..
    //List of Color Names
    static List<string> cnlist = new List<string>{
        "Black", "Brown", "Blue", "Pale Light Blue", "Green", "Red", "Yellow",
        "Gray", "Indigo", "Orange", "Pink", "Turquoise", "White"
    };

You can use these methods to find the closest color:
    int closestColor2(List<Color> colors, Color target) {
        var colorDiffs = colors.Select(n => ColorDiff(n, target)).Min(n => n);
        return colors.FindIndex(n => ColorDiff(n, target) == colorDiffs);
    }

    // distance in RGB space
    int ColorDiff(Color c1, Color c2) {
        return (int)Math.Sqrt((c1.R - c2.R) * (c1.R - c2.R)
                               + (c1.G - c2.G) * (c1.G - c2.G)
                               + (c1.B - c2.B) * (c1.B - c2.B));
    }

The method above will return the index of the closest color in the list and then you can take that same index and take the name that you specified from your list of color names. That way you can have exactly the name you want on each color and dont need to rely on an algorithm that is not 100% and since it is so few colors it would only take a small amount of time to write the names and as mentioned you would get them as you wish this way.
If you want to add all the colors that exist in Color.* you can use this method to get them:
private List<Color> GetAllColors() {
        var list = new List<Color>();
        var colorType = typeof(Color);
        var propInfos = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
        foreach (var propInfo in propInfos) {
            var color = Color.FromName(propInfo.Name);
            list.Add(color);
        }
        return list;
    }

A: I found this code:
    string ColorName(Color c)
{
    List<float> hues = new List<float>()
    { 0, 15, 35, 44, 54, 63, 80, 160, 180, 200, 244, 280, 350, 360};
    List<string> hueNames = new List<string>()
        { "red", "orange-red", "orange", "yellow-orange", "yellow",
          "yellow-green",   "green"  , "blue-green" , "cyan", "blue",
          "violet", "purple", "red" };

    float h = c.GetHue();
    float s = c.GetSaturation();
    float b = (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f;

    string name = s < 0.35f ? "pale " : s > 0.8f ? "vivid " : "";
    name += b < 0.35f ? "dark " : b > 0.8f ? "light " : "";
    for (int i = 0; i < hues.Count - 1; i++)
        if (h >= hues[i] && h <= hues[i+1] )
        {
            name += hueNames[i];
            break;
        }
    return name;
}

Here
and I tried to implement it into your code like this:
static string closestColor1(List<Color> colors, Color target)
    {
        var hue1 = target.GetHue();
        var diffs = colors.Select(n => getHueDistance(n.GetHue(), hue1));
        var diffMin = diffs.Min(n => n);
        var x = diffs.ToList().FindIndex(n => n == diffMin);

        Color c = colors[x];

        float h = c.GetHue();
        float s = c.GetSaturation();
        float b = (c.R * 0.299f + c.G * 0.587f + c.B * 0.114f) / 256f;

        string name = s < 0.35f ? "pale " : s > 0.8f ? "vivid " : "";
        name += b < 0.35f ? "dark " : b > 0.8f ? "light " : "";

        name += colors[x].ToString();

        return name;
    }

but some solutions show sometimes both, things like: "pale dark red"/"pale dark blue" etc.. which is really confusing.. and you want to show only 1 of them... you should try something similar.. or think about how to put only 1..


text:
Q: Get Controls/Views from dynamic content Tab I have created tabs and their content from a database.  Now I need help figuring out how to get the user entered values from those controls - how to get a list of the controls on the tabs (so the data can be saved).  Here is a condensed sample of how I'm populating the tabs contents:
public View createTabContent(String tag)
{
SQLiteDatabase db2 = openOrCreateDatabase(msDbFile, MODE_PRIVATE, null);
Cursor cList = db2.rawQuery("SELECT * FROM CheckList WHERE CatID=" + tag, null);
TableLayout tl = new TableLayout(FormChecklist.this);
tl.setBackgroundColor(new Color().WHITE);
while(cList.moveToNext())
{
    /* Create a new row to be added. */
    TableRow tr = new TableRow(FormChecklist.this);
    tr.setLayoutParams(new LayoutParams(
               LayoutParams.FILL_PARENT,
               LayoutParams.WRAP_CONTENT));

     /* Create the row-content. */
    TextView lblQuestion = new TextView(FormChecklist.this);
    lblQuestion.setText(cList.getString(2));
    lblQuestion.setTag(tag);
    /* Add control to row. */
    tr.addView(lblQuestion);

    CheckBox chkCompleted = new CheckBox(FormChecklist.this);
    chkCompleted.setText("Completed");
    chkCompleted.setLayoutParams(new LayoutParams(
               LayoutParams.FILL_PARENT,
               LayoutParams.WRAP_CONTENT));
    chkCompleted.setTag(tag);
    /* Add control to row. */
    tr.addView(chkCompleted);

    /* Add row to TableLayout. */
    tl.addView(tr,new TableLayout.LayoutParams(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));
}
db2.close();
return tl;
}

A: No replies, but finally figured out, hopefully someone will find this info helpful.
Approach I took was modifying my createTabContent adding an ID for the TableLayout:
tl.setId(1000 + miTlCnt);

Then in my save routine I loop through controls like so:
for (int i = 1000 + miTlCnt; i > 1000; i--)
{
    TableLayout tl = (TableLayout)findViewById(i);
    if (tl != null)
    {
        for (int j = 0; j < tl.getChildCount(); j++)
        {
            TableRow row = (TableRow)tl.getChildAt(j);
            CheckBox chkCompleted = (CheckBox)row.getChildAt(1);
        }
    }
}


text:
Q: Creating a plugin for Sublime Text 3 in a language other than Python I want to create a plugin for Sublime Text 3 in another language, say, in C++ or C or any other compiled language. Is it possible? Preferably without any Python code or libraries at all except the ones that's already installed with Sublime Text3.
If not, is there any workaround? The thing here is that I want the plugin to be a compiled language. I'm aware about Python ".pyc" files but that's not what I'm looking for.

A: No, it's impossible to make a Sublime Text plugin with absolutely zero python code. However, you can call a binary application from the python plugin and put all of your logic in there.
For example, SublimeLinter does part of its work in python, but calls out to binaries such as flake8 and ruby -wc for the actual linting of the file.


text:
Q: what is the role of VBE7.dll? The application is writing data to the excel sheet.
As per our security standards we are blocking macros related to excel and word.
McAfee antivirus is blocking the macros.
The application is in C++ and the data written to excel is done by using MFC and worksheet functions.
when i debugging the code, it is trying to write or execute VBE7.dll and VBE7.dll is blocking by McAfee.
why it is trying to write or execute to VBE7.dll?


text:
Q: MITM proxy over SSL hangs on wrap_socket with client I'm in quite a predicament and you are my last hope.  I started doing a project making a MITM proxy with ssl.  My program uses the HTTP CONNECT method.  To keep this concise my program follows the following diagram…
      Client          Proxy             Server
           +              +             +
  CONNECT  |              |             |
           +------------> |             |
           |              |             |
           |    200 Established         |
           |  <-----------+             |
           |              |             |
           | <----------> |             |
           |  Handshake   |             |
           |              | <---------> |
           |              |  Handshake  |
           |              |             |
           |              |             |
           | <----------> | <---------> |
           | Data Exchange| Data Exchange
           |              |             |

My proxy shares a certificate with the client however my client seems to be unable to connect and my proxy hangs on do_handshake() when I call wrap_socket() on the accepted socket. Here's the section of python where a client connects to the proxy…
import ssl, socket
from _thread import *
port = 8000
def run():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', port))
    sock.listen(10)
    while True:
        connection, addr = sock.accept()
        data = connection.recv(8192)
        connection.send(b"HTTP/1.0 200 OK")
        connection = ssl.wrap_socket(connection, keyfile='private.pem', certfile='cacert.pem', server_side=True)
        start_new_thread(connection_string, (connection, data, addr))  # start thread to handle CONNECT

I simulate a client with Openssl
openssl s_client -proxy 127.0.0.1:8000 -connect www.google.com:443 -state -verify 1 -CAfile cacert.pem -verify_return_error

When the client connects to the proxy they both hang.  If I kill the client I receive
Traceback (most recent call last):
  File "/mitm/mitm_proxy.py", line 100, in <module>
    run()
  File "/mitm/mitm_proxy.py", line 92, in run
    connection = ssl.wrap_socket(connection, keyfile='private.pem', certfile='cacert.pem', server_side=True)
  File "/usr/lib/python3.5/ssl.py", line 1069, in wrap_socket
    ciphers=ciphers)
  File "/usr/lib/python3.5/ssl.py", line 752, in __init__
    self.do_handshake()
  File "/usr/lib/python3.5/ssl.py", line 988, in do_handshake
    self._sslobj.do_handshake()
  File "/usr/lib/python3.5/ssl.py", line 633, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:645)

if I kill my proxy my client says
CONNECTED(00000003)
s_client: HTTP CONNECT failed
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 140709212149056 bytes and written 39 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
---

I've compared my code with others that work and they are essentially the same which is why I'm here. I can't figure out whats going wrong.

A: I'm not sure if this the main cause of your problem but this one is definitely wrong:

    connection.send(b"HTTP/1.0 200 OK")

The correct response of the server should be the status line ending with \r\n, optional key:value\r\n pairs and then the \r\n to mark the end of the HTTP header, i.e. minimally:

    connection.send(b"HTTP/1.0 200 OK\r\n\r\n")

Since the client is not receiving the missing \r\n\r\n it will probably wait for it and not start the TLS handshake (i.e. send ClientHello). The server instead will wait for the client to start the handshake and this way both will wait for each other forever.
Apart from you not following the standard openssl s_client -proxy ... seems to not follow the standard too. It actually needs the response to contain the word "established" as the following excerpt from the lazy HTTP parsing code in apps/s_client.c in OpenSSL 1.1.0c suggests:
case PROTO_CONNECT:
        ...
        BIO_printf(fbio, "CONNECT %s HTTP/1.0\r\n\r\n", connectstr);
        (void)BIO_flush(fbio);
        /* wait for multi-line response to end CONNECT response */
        do {
            mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
            if (strstr(mbuf, "200") != NULL
                && strstr(mbuf, "established") != NULL)
                foundit++;
        } while (mbuf_len > 3 && foundit == 0);

So try with the following line:

    connection.send(b"HTTP/1.0 200 established\r\n\r\n")


text:
Q: Update rows with current item index I've got this table:
+------+----------+
| id   | position |
+------+----------+
| 1    | 38       |
+------+----------+
| 5    | 102      |
+------+----------+
| 12   | 112      |
+------+----------+
| 13   | 142      |
+------+----------+

And want to 'rebalance' position column as follows
+------+----------+
| id   | position |
+------+----------+
| 1    | 0        | (i=0 * 128)
+------+----------+
| 5    | 128      | (i=1 * 128)
+------+----------+
| 12   | 256      | (i=2 * 128)
+------+----------+
| 13   | 384      | (i=3 * 128)
+------+----------+

I also have scoped positions into lists like this:
+------+---------------------+
| id   | list_id  | position |
+------+---------------------+
| 1    | 1        | 10       |
+------+---------------------+
| 5    | 1        | 22       |
+------+----------+----------+
| 12   | 2        | 8        |
+------+----------+----------+
| 13   | 2        | 18       |
+------+----------+----------+

I think I need to know the index of current item in the SQL update statement, or maybe use a sub-query?
How would you go about doing this?

A: demo: db<>fiddle
UPDATE mytable
SET position = s.new_position
FROM (
    SELECT
        id,
        (row_number() over (ORDER BY id) - 1) * 128 as new_position
    FROM mytable
) s
WHERE mytable.id = s.id;

Using the window function row_number allows you to add a row count to your data set (your "index" if you like to call it this). It starts with 1, so I subtract 1 and multiply with 128.

Updated question (added the third table with list_id):
If you want to do a separate position count per list, you have to add a window frame to the window function (PARTITION BY list_id):
UPDATE mytable
SET position = s.new_position
FROM (
    SELECT
        id,
        (row_number() over (PARTITION BY list_id ORDER BY id) - 1) * 128 as new_position
    FROM mytable
) s
WHERE mytable.id = s.id;

which results in:
id   list_id   position
1    1         0
5    1         128
12   2         0
13   2         128

demo:db<>fiddle


text:
Q: Matching Parantheses using stack Below code is to check whether the given string has balanced parantheses or not using stack.
Getting wrong output for input "[]". It should print true but the result that i am getting is false.
import java.util.*;
class Solution{
    public static void main(String[] argh) {
        Scanner sc = new Scanner(System.in);
        Stack st = new Stack();
        boolean flag = true;
        while (sc.hasNext()) {
            String input = sc.next();
            //Complete the code
            for (int i = 0; i < input.length(); i++) {
                flag = false;
                if ((input.charAt(i) == '{') || (input.charAt(i) == '(') || (input.charAt(i) == '[')) {
                    st.push(input.charAt(i));
                    continue;
                }
                if ((input.charAt(i) == '}') || (input.charAt(i) == ')') || (input.charAt(i) == ']')) {
                    if (st.isEmpty()) {
                        flag = false;
                    } else {
                        char item = (char) st.pop();
                        if ((item == '(') && (input.charAt(i) == ')'))
                            flag = true;
                        if ((item == '{') && (input.charAt(i) == '}'))
                            flag = true;
                        if ((item == '[') && (input.charAt(i) == ']'))
                            flag = true;
                    }
                }
            }
            if (!st.isEmpty())
                flag = false;
            System.out.println(flag);
        }
    }
}

A: I have reproduced your code below with a few changes (identified by comments) that should get it to work.
import java.util.*;
class Solution{
    public static void main(String[] argh) {
        Scanner sc = new Scanner(System.in);
        Stack st = new Stack();
        while (sc.hasNext()) {
            // jim - Moved this to inside the loop.
            // Assume the input is good unless proven otherwise.
            boolean flag = true;
            String input = sc.next();
            //Complete the code
            // jim - Added the "&& flag == true" to exit if the input is bad
            for (int i = 0; i < input.length() && flag == true; i++) {
                // jim - Commented this out. We'll assume it's good. If the input
                // is found to be bad, we set the flag, and the
                // "&& flag == true" condition above will exit the loop.
                // flag = false;
                if ((input.charAt(i) == '{') || (input.charAt(i) == '(') || (input.charAt(i) == '[')) {
                    st.push(input.charAt(i));
                    continue;
                }
                if ((input.charAt(i) == '}') || (input.charAt(i) == ')') || (input.charAt(i) == ']')) {
                    if (st.isEmpty()) {
                        flag = false;
                    } else {
                        char item = (char) st.pop();
                        // jim - here, check for not equal, and set to false.
                        if ((item == '(') && (input.charAt(i) != ')'))
                            flag = false;
                        if ((item == '{') && (input.charAt(i) != '}'))
                            flag = false;
                        if ((item == '[') && (input.charAt(i) != ']'))
                            flag = false;
                    }
                }
                else {
                    // jim - added this 'else' clause.
                    // If there's any character other than [{()}], then it's
                    // bad input.
                    flag = false;
                }
            }
            if (!st.isEmpty())
                flag = false;
            System.out.println(flag);
        }
    }
}

There are some improvements you could make to your code, but those few changes I documented should get it to work.


text:
Q: PromiseKit - Pass previous result to next promise in chain Im trying to follow the Documentation to pass the result of a promise to the next promise
https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#saving-previous-results
I keep getting
Contextual closure type '(_) throws -> _' expects 1 argument, but 2 were used in closure body
Here my Code
 class func loginInOrSignup() -> Promise<PFUser> {
        let lm = LoginManager()
        lm.logOut()

        return logInInBackground().then{user in
                if user.isNew{
                    return getUserInfo().map{ ($0, user) }
                }
                else{
                    user.fetchIfNeededInBackground()
                    return Promise.value(user)
                }
            }.then{(userInfo, user) -> Promise<PFUser> in

                let name = userInfo["name"] as! String
                if let email = userInfo["email"] as? String {
                    user.email = email
                }
                let username = G8FacebookLogin.generateSuggestedUsername(name: name)
                user.username = username

                return Promise.value(user)
            }
    }

    private class func logInInBackground() -> Promise<PFUser>{
        return Promise {seal in
            PFFacebookUtils.logInInBackground(withReadPermissions: ["public_profile", "email"]){user, error in
                guard let user = user else {
                    seal.reject(error ?? AuthError.msg(reason: "Some FB Error"))
                    return
                }
                seal.fulfill(user)
            }
        }
    }
    private class func getUserInfo() -> Promise<Dictionary<String,Any>> {
        return Promise {seal in
            G8FacebookLogin.getUserInfo { (userDict, error) in
                guard let userInfo = userDict else{
                    PFUser.logOut()
                    seal.reject(AuthError.loginFailed(reason: "no user Info retrieved"))
                    return
                }
                seal.fulfill(userInfo)
            }
        }
    }

It's pretty much the same as the Snippet code in the documentation. I don't understand what is the right way to do it.


text:
Q: .gitignore style fnmatch() What would be the simplest way to have .gitignore style fnmatch() with Python. Looks like that stdlib does not provide a match() function which would match a path spec against an UNIX style path regex.

*

*fnmatch() matches only pure filenames, no paths http://docs.python.org/library/fnmatch.html?highlight=fnmatch#fnmatch

*glob() will perform directory listing, and does not provide match() true/false style function http://docs.python.org/py3k/library/glob.html?highlight=glob#glob.glob
.gitignore have both paths and files with wildcards to be (black)listed

*

*https://github.com/miohtama/Krusovice/blob/master/.gitignore

*http://linux.die.net/man/5/gitignore

A: If you want to use mixed UNIX wildcard patterns as listed in your .gitignore example, why not just take each pattern and use fnmatch.translate with re.search?
import fnmatch
import re

s = '/path/eggs/foo/bar'
pattern = "eggs/*"

re.search(fnmatch.translate(pattern), s)
# <_sre.SRE_Match object at 0x10049e988>

translate turns the wildcard pattern into a re pattern
Hidden UNIX files:
s = '/path/to/hidden/.file'
isHiddenFile = re.search(fnmatch.translate('.*'), s)
if not isHiddenFile:
    # do something with it

A: There's a library called pathspec which implements the full .gitignore specification, including things like **/*.py; the documentation describes how to handle Git pattern matching (you can also see code).
>>> import pathspec
>>> spec_src = '**/*.pyc'
>>> spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, spec_src.splitlines())
>>> set(spec.match_files({"test.py", "test.pyc", "deeper/file.pyc", "even/deeper/file.pyc"}))
set(['test.pyc', 'even/deeper/file.pyc', 'deeper/file.pyc'])
>>> set(spec.match_tree("pathspec/"))
set(['__init__.pyc', 'gitignore.pyc', 'util.pyc', 'pattern.pyc', 'tests/__init__.pyc', 'tests/test_gitignore.pyc', 'compat.pyc', 'pathspec.pyc'])


text:
Q: Show UTF-8 characters in console How can I print UTF8 characters in the console?
With Console.Writeline("îăşâţ") I see îasât in console.

A: Console.OutputEncoding = Encoding.UTF8;

A: Try this :
using System.Diagnostics
...
Debug.WriteLine(..);// will output utf-8 charset

A: Using Console.OutputEncoding will be sufficient for this. All string objects in .NET are by default unicode so changing output encoding for console to UTF-8 will work as you want in modern Windows installations.
Default encoding in console depends on configuration but it will be most likely IBM437 for US language or some local codepage.

A: You can't print Unicode characters in the console, it only supports the characters that are available in the current code page. Characters that are not available are converted to the closest equivalent, or a question mark.

A: There are some hacks you can find that demonstrate how to write multibyte character sets to the Console, but they are unreliable.  They require your console font to be one that supports it, and in general, are something I would avoid.  (All of these techniques break if your user doesn't do extra work on their part... so they are not reliable.)
If you need to write Unicode output, I highly recommend making a GUI application to handle this, instead of using the Console.  It's fairly easy to make a simple GUI to just write your output to a control which supports Unicode.


text:
Q: Unable to use hive jdbc-handler with SQL Server database I would like to define an external table in Hive metastore.  This table should be external mapping to a SQL Server database table.
I'm using Dataproc in GCP to get all the hadoop stack including hive 3.1.2 (should support SQL Server).
I try using Beeline to create a table like this:
CREATE EXTERNAL TABLE Mytable
(
    ID INT,
    Name STRING,
    ts TIMESTAMP,
    IsHideSites TINYINT,
    DisplayName STRING
)
STORED BY 'org.apache.hive.storage.jdbc.JdbcStorageHandler'
TBLPROPERTIES (
"hive.sql.database.type"="MSSQL",
"hive.sql.jdbc.driver"="net.sourceforge.jtds.jdbc.Driver",
"hive.sql.jdbc.url"="jdbc:jtds:sqlserver://<MSSQL Server>/main",
"hive.sql.dbcp.username"="user",
"hive.sql.dbcp.password"="pass",
"hive.sql.dbcp.maxActive" = "1",
"hive.sql.query" = "SELECT t.ID,t.Name,t.TimeStamp,t.IsHideSites,t.DisplayName FROM Main.dbo.AdNetworks t"
);

But I get this error :

Caused by: org.apache.hadoop.hive.metastore.api.MetaException: org.apache.hadoop.hive.serde2.SerDeException
org.apache.hive.storage.jdbc.exception.HiveJdbcDatabaseAccessException: Error while trying to get column names: Unrecognized SQL escape 'limit' at line position 93.
at org.apache.hadoop.hive.metastore.HiveMetaStoreUtils.getDeserializer(HiveMetaStoreUtils.java:98) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.metastore.HiveMetaStoreUtils.getDeserializer(HiveMetaStoreUtils.java:77) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:289) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:271) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.metadata.Hive.createTable(Hive.java:901) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.metadata.Hive.createTable(Hive.java:938) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.exec.DDLTask.createTable(DDLTask.java:4954) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.exec.DDLTask.execute(DDLTask.java:428) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:205) ~[hive- exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:97) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:2664) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.Driver.execute(Driver.java:2335) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:2011) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1709) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1703) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hadoop.hive.ql.reexec.ReExecDriver.run(ReExecDriver.java:157) ~[hive-exec-3.1.2.jar:3.1.2]
at org.apache.hive.service.cli.operation.SQLOperation.runQuery(SQLOperation.java:224) ~[hive-service-3.1.2.jar:3.1.2]

Is there someone that succeeded to map an hive table with a SQL Server table and can help?
Thanks


text:
Q: Jumping Frog on even number of pads using DrRacket (Scheme) I am trying to solve this question below which first requires finding the math formula then writing code in DrRacket (Scheme dialect of Lisp):
A frog with unlimited jumping power is sitting on the first pad (pad number 0), out of N pads in a row (N is always even). The frog wants to reach the last (Nth) pad. The frog can jump any even number of pads, including N: it's possible that it will do it in 1 jump (by jumping N pads), in N/2 jumps (by jumping 2 pads at a time) or in any other combination of even jumps. For example, if N were 4, it could jump in one jump: 0th to 4th, or in 2 jumps (from 0th to 2nd and then from 2nd to 4th). The total number of ways of jumping from the 0th to the 4th pad is 2 ways.

*

*What is the math formula for finding the total number of ways the frog can reach the Nth pad?

*Using Scheme, write a procedure that, given a number of pads N, returns the total number of ways the frog can reach the Nth pad BY USING RECURSIVE CALLS ONLY. If the number of pad N is not even, the frog can't jump and the procedure returns "x".

I got a solved question which is slightly different and here is the solution for it below, but I am not sure what the math formula is for the question above, though, so would appreciate your help.
A frog with unlimited jumping power is sitting on the first pad (pad number 1), out of N pads in a row. The frog wants to reach the last (Nth) pad. The frog can jump any number of pads, including N: it's possible that it will do it in 1 jump (by jumping N pads), in N jumps (by jumping 1 pad at a time) or in any other combination. For example, if N were 4, it could jump one jump; 1 to 4th, or in 2 jumps; the first of length 1 and then 2 (from 1st to 2nd and then from 2nd to 4th), or the first of length 2 and then 1 (from 1st to 3rd and then from 3rd to 4th), or in 3 jumps (from 1st to 2nd and from 2nd to 3rd and from 3rd to 4th). The total number of ways of jumping from the 1st to the 4th pad is 4 ways. Write a procedure that, given a number of pads N, returns the total number of ways the frog can reach the Nth pad.
Solution:

*

*Total possible jumps = 2 ^ (N-2)

*DrRacket Code: (define(pad-jumps n)(power 2 (- n 2))))


text:
Q: Setting up android things using an ios device Watched this talk about setting up an android thing device. But ios devices don't support Nearby Connections so how are we supposed to setup this for ios?

A: You can just download the Android Things Setup Utility from the console and still go through the setup, so no need to use an Android Device for that.
This page tells you how to do the setup without a phone.


text:
Q: onClick handler to call Material UI dialog box, is not working properly I want the material-ui dialog-box always pop up on button click and show the target value perfectly everytime. It shows sometimes but sometimes doesn't. I am sending the value on the icon onclick event - (e) and using it on the onClick function. I'm doing it on react.js. Is there a bug in the component?
I just found out that it's not the dialog component problem I was getting.
I'm not getting the value sometimes on console.log in the openFunc function while tapping on the icon.
Had the same problem? Any help?
Having the following code:
import React, {Component} from 'react';
import Dialog from 'material-ui/Dialog';
import BorderColor from 'material-ui/svg-icons/editor/border-color';

class Mydialog extends Component {
   constructor() {
      super();
      this.state = {
         ids:['129', '105', '131', '151'],
         myid: '',
         open_dialog: false
      }
      this.openFunc = this.openFunc.bind(this);
   }
   check_today() {
      let container = [];
      let i;

      for(i=0; i<this.state.ids.length;i++) {
         container.push(
                <BorderColor onClick = {this.openFunc} data-id ={this.state.ids[i]}/>
         )
      }

      if(container.length === 0){
        return(

show none!

            )
      }
      else{
        return (

                {container}

        )
      }
   }
   openFunc(e) {
      console.log(e.target.dataset.id);
      this.setState({
         open_dialog: true,
         myid: e.target.dataset.id
      });
   }
   handleClose = () => {
      this.setState({open_dialog: false});
   };
   render() {
      return(

           {this.check_today()}

          <Dialog
           autoDetectWindowHeight={true}
           modal={false}
           open={this.state.open_dialog}
           onRequestClose={this.handleClose}
          >

             It's the dialog-box!
             My id is {this.state.myid}

          </Dialog>

      )
   }
}
export default Mydialog

A: Instead of relying on data-id for the value you can pass the value to the onClick function using the Es6 arrow function syntax as
<BorderColor onClick = {() => this.openFunc(this.state.ids[i])}/>

or the bind syntax as
<BorderColor onClick = {this.openFunc.bind(this, this.state.ids[i]} />

and use it in openFunc like
openFunc(value) {
  this.setState({
     open_dialog: true,
     myid: value
  });
}

A: A few things stand out;
First of all, items in an array of the same type require a key property to differentiate them from one another.  It is necessary to add this simply as follows;
for(i=0; i<this.state.ids.length;i++) {
     container.push(
            <BorderColor key={i} onClick={this.openFunc} data-id=this.state.ids[i]}/>
     )
  }

Also, while you certainly could use the data-id value, it's not the "react way".  I would recommend changing it to use a curried function.
Change openFunc to be this;
openFunc(id) {
    return (e) => {
        this.setState({
           open_dialog: true,
           myid: id
        });
}

Which you can then apply to the BorderColor component as such;
for(i=0; i<this.state.ids.length;i++) {
     container.push(
            <BorderColor key={i} onClick={this.openFunc(this.state.ids[i])}/>
     )
  }


text:
Q: InterceptorBinding is not working I created a custom annotation like below
@InterceptorBinding
@Retention(RUNTIME)
@Target(TYPE, METHOD)
public @interface Traceable {}

I wrote an interceptor like below
@Traceable
@Interceptor
public class EnterExitLogger {
    @AroundInvoke
    public Object aroundInvoke(InvocatiobContext c) {}
}

The interceptor and the annotation are in a module called common-utils.
I annotated a my target class with @Traceable at class level like below
@Traceable
public class CDIManagedBean {
}

I declared the interceptor entry in my beans.xml file like below
<interceptors>
    <class>my.package.EnterExitLogger</class>
</interceptors>

The target class is in a separate module. beans.xml is in META-INF directory of the target class's module.
The target class's methods are called from a rest class. When I invoke the methods the interceptor's AroundInvoke method is not called.
I read the docs and understood that the interceptor should contain a public no argument constructor. I added it. But still the interceptor was not called.
I added @Inherited on the custom annotation after reading the docs. But still the interceptor was not called.
From the docs I noticed the interceptor implementing Serializable interface. Although not mentioned I implemented Serializable also. Still did not work.
Then I removed the custom annotation from the interceptor, beans.xml file and the target class. I also removed the public no argument constructor from the interceptor and removed Serializable.
Then I annotated the target class with @Interceptors(EnterExitLogger.class) and invoked the flow. My interceptor was called.
Can anyone tell me how do I do with an InterceptorBinding?
P.S.
I am deploying my ear in WAS 8.5 server.

A: The Java EE Tutorial provides a nice explanation and a few examples about interceptors:
Create an interceptor binding annotation, which must be annotated with @Inherited and @InterceptorBinding:
@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Logged { }

Create the incerceptor class which is annotated with the interceptor binding annotation created above as well as with the @Interceptor annotation.
Every @AroundInvoke method takes an InvocationContext argument, returns an Object, and throws an Exception. The @AroundInvoke method must call the InvocationContext#proceed() method, which causes the target class method to be invoked:
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable {

    public LoggedInterceptor() {

    }

    @AroundInvoke
    public Object logMethodEntry(InvocationContext invocationContext) throws Exception {

        System.out.println("Entering method: "
                + invocationContext.getMethod().getName() + " in class "
                + invocationContext.getMethod().getDeclaringClass().getName());

        return invocationContext.proceed();
    }
}

Once an interceptor and binding type are defined, you can annotate beans and individual methods with the binding type to specify that the interceptor is to be invoked either on all methods of the bean or on specific methods.
For example, the PaymentHandler bean is annotated @Logged, which means that any invocation of its business methods will cause the interceptor's @AroundInvoke method to be invoked:
@Logged
@SessionScoped
public class PaymentHandler implements Serializable {...}

However you can intercept only a set of methods of a bean by annotating only the desired methods:
@Logged
public String pay() {...}

@Logged
public void reset() {...}

In order for an interceptor to be invoked in a CDI application, it must be specified in the beans.xml file:
<interceptors>
    <class>your.package.LoggedInterceptor</class>
</interceptors>

If an application uses more than one interceptor, the interceptors are invoked in the order specified in the beans.xml file.

A: The issue was fixed after adding an empty beans.xml file in the module where the interceptors where kept. I Thought beans.xml file is only necessary when I want to use cdi injection.