text:
Q: How to control radio button states within a custom SimpleCursorAdapter via bindView / newView for a listfragment I have a listfragment that manages row(s) of 2 radio buttons per row, where only one button is allowed to be checked, but I've not been able to manage the radio button states properly.
I'm pretty familiar with listview's recycling of views. I've tried many different avenues to no success, I realize I have to keep the states of the radio buttons, list position and probably whether the button has been initialized yet separately, which I can to with an interface.  It's where and when to set the radio button states within the adapter that I've been wrestling with.  Anything I've tried has one condition or another interfering with the other.  Like setting the radio button from the database initially, but when there is a recycled view with no radio button to be check and I do a radiogroup.clearCheck() that seems to override when the user chooses a button.
The state of the radio buttons should be controlled by 2 sources;
Database source:
1) Database column has a value I'd like to set for the radio button initially, which I'd like to show as checked (.setChecked(true)) when the user hasn't had any interaction with that row yet, besides scrolling/no clicks.  OR  the Database column is 0 and no radio button should be checked.
User Action:
2) The users selects one of the two buttons, this should override the value of the database column.
Following is the rough framework for the fragments and adapters that I have:
The listview row xml file    stackoverflow_2_radiobuttons_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:divider="@color/gray"
android:dividerHeight="5dp" >

<LinearLayout
    android:id="@+id/linear_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/default_text_left_margin"
    android:layout_marginRight="@dimen/default_text_left_margin"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/rb_1"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/radiogroup"
            android:layout_weight="1"
            android:gravity="top"
            android:paddingBottom="@dimen/default_text_top_margin"
            android:text="RadioButton 1"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textStyle="bold"
            android:checked="false" />

        <RadioButton
            android:id="@+id/rb_2"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/rb_1"
            android:layout_weight="1"
            android:gravity="top"
            android:paddingBottom="@dimen/default_text_top_margin"
            android:text="RadioBUtton 2"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textStyle="bold"
            android:checked="false"/>

    </RadioGroup>

</LinearLayout>

</RelativeLayout>

The list fragment: StackOverFlow.java
public class StackOverFlow extends ListFragment implements
    LoaderManager.LoaderCallbacks<Cursor> {

SimpleCursorAdapter adapter;
Activity activity;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    String[] columns = new String[] { Mydb.COL_RB_STATE };
    int[] viewfields = new int[] {  };

    adapter = new StackOverFlowAdapter(getActivity(),     R.layout.stackoverflow_2_radiobuttons_row.xml,
            null, columns, viewfields);
    setListAdapter(adapter);
    getLoaderManager().initLoader(0, null, this);

}

Handler handler = new Handler();

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = new String[] {
            Mydb.COL_RB_STATE };

    CursorLoader loader = new CursorLoader(getActivity(),
            MYProvider.CONTENT_URI, projection, null, null, null);
    String[] argz = new String[] { "'text'" };
    return loader;
}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    ((SimpleCursorAdapter) this.getListAdapter()).swapCursor(cursor);
}

@Override
public void onLoaderReset(Loader<Cursor> arg0) {
    ((SimpleCursorAdapter) this.getListAdapter()).swapCursor(null);
}
}

The custom list fragment adapter:   StackOverFlowAdapter.java
public class StackOverFlowAdapter extends SimpleCursorAdapter {

private Context context;
private final LayoutInflater inflater;
private int pos = 0;

RadioGroup radiogroup;
int iRowID = -1;
String row_Id;

Activity TestActivity;

protected static class ViewHolder {

    protected TextView h_rb1;
    protected TextView h_rb2;
    protected TextView h_radiogroup;
    protected int h_position;

}

public StackOverFlowAdapter(Context context, int layout, Cursor c,
        String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.context = context;
    inflater = LayoutInflater.from(context);
}

@Override
public boolean hasStableIds() {
    return true;
}

ViewHolder holder;

public View newView(Context context, Cursor cursor, ViewGroup parent) {
    holder = new ViewHolder();
    View view = inflater.inflate(R.layout.stackoverflow_2_radiobuttons_row, parent, false);
    holder.h_rb1 = (RadioButton) view.findViewById(R.id.rb_1);
    holder.h_rb2 = (RadioButton) view.findViewById(R.id.rb_2);
    holder.h_radiogroup = (RadioButton) view.findViewById(R.id.radiogroup);
    holder.h_position = (pos);

    if (cursor != null) {
        bindView(view, context, cursor);
    }
    view.setTag(holder);

    return view;
}

public void bindView(View view, final Context context, Cursor cursor) {

    holder = (ViewHolder) view.getTag();

    final RadioButton rb_1 = (RadioButton) view
            .findViewById(R.id.rb_1);
    final RadioButton rb_2 = (RadioButton) view
            .findViewById(R.id.rb_2);
    final RadioGroup radiogroup = (RadioGroup) view.findViewById(R.id.radiogroup);

    radiogroup
            .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {

                    if (checkedId == rb_1.getId()) {
                        rb_1.setChecked(true);
                    } else if (checkedId == rb_2.getId()) {
                        rb_2.setChecked(true);
                    }

                }

            });

}

}

I've seen a lot of answers using getView, but I haven't been able to find a good example or theory using bindView  and newView in a custom SimpleCursorAdapter with radio button states.  I haven't been successful manipulating anything in newView, I've been working mostly in bindView. So at this point I'm not sure how to proceed.  Any help or guidance would be appreciated.
Have a great day.


text:
Q: How to close ios app in Delphi-XE5 Firemonkey application? I do not manage to find how to end an application iOS in Delphi XE5 Firemonkey.
Application.terminate does not work.
Thank you for your help

A: In iOS it is not allowed to close an App. You can only force a crash. Apple will not allow Apps with this behavior in their AppStore.
An alternative an be to set UIApplicationExitsOnSuspend to Yes (in the info.plist file).
=> When the user presses the home button your application will be ended.

redpajama_set_name: RedPajamaStackExchange


text:
Q: command-line utility to record from microphone I am looking for command-line utility that monitors the microphone, and if you start to speak, writes the file. Recording period should be adjusted.
Solution is:
   sox -t alsa default recording.wav silence 1 0.1 5% 1 1.0 5%

A: From http://dabase.com/u/record_wav/
arecord -vv -fdat stackoverflow.wav


text:
Q: how do i change my external hard disk to NTFS? I have a toshiba external hard disk and I want to change it's file system to NTFS

How do i go about doing it? (keep it simple please i'm a computer idiot)
32-bit windows vista home premium sp2 here

A: From an elevated command prompt, use the command: convert e: /fs:ntfs
It is simple and I have never seen it fail, so very reliable. Most importantly, all of your data will remain intact.
Still, if you have any one-of-a-kind data on the drive, back it up.

A: If you have data on the drive that you need to keep, follow the advice to use the "convert" command-line if you cannot move the data elsewhere temporarily. But be sure to run chkdsk on the drive first because file system errors can cause the process to fail.
If you have no data to save, open Disk Manager (Right-click Computer > Manage > Disk Management). Right-click the contents of the drive in the image and delete. Make sure all contents are deleted. Right-click again and choose to create a new, basic volume. Follow the wizard and choose a drive letter and name for the volume when it asks. You can use the "quick" option for formatting unless you suspect there is something wrong with the drive.
You should do it this way because you get few chances to create new partition tables. Even if the tables are mildly corrupted, Windows can often still access them. But when that is so, one small error more and you lose access to the partition. So it is best to create new tables (original and backup are created) when you have the chance.
If you have data on the drive that you need to keep, follow the advice to use the "convert" command-line. But be sure to run chkdsk on the drive first because file system errors can cause the process to fail.


text:
Q: Specifying coordinates for Inset on a LogPlot If I use Epilog->Inset within a Plot, the coordinates specified within that Inset match those of the plot's axis and scale:
Plot[y = 2 x, {x, 0, 5}, Epilog -> Inset["Text", {3, 3}]]

Note that "Text" is placed at x=3, y=3. Different thing happens for when Inset is used within LogPlot:
LogPlot[y = x^x, {x, 0, 5}, Epilog -> Inset["Text", {3, 3}]]

The coordinates are still (3,3) but "Text" is positioned at what appears to be (3,20) with respect to the on-axis coordinates.
What is it about and how do I counter it?
Thanks in advance,
r.

A: This is just to get an answer on record so the question can be removed from not-answered list.
As Nasser remarked in his comment

This is because Log[20.] = 2.99573227355399 You can either use Inset["Text", {3, Log[3]}] or I think using Scaled[] is better. I do not know of a way myself to have the scaling of outer coordinates be automatically reflected in the Epilog. You have to do it your self or using Scaled[].


text:
Q: Como poner una matricula en java segura Hola tengo que hacer matrícula (estará compuesta por 4 números consecutivos seguido de 3 letras también consecutivas, sin espacios en blanco entre números y letras). Y quiero un metodo que reciba un string matricula y compruebe que tiene un formato adecuado
Yo he hecho,
 private final String matricula ="1111AAA";

¿Así estaría bien? o ¿crearíais un método?

A: Puedes usar una expresión regular:

^[0-9]{4}[A-Z]{3}$

Significa que solo admite 4 digitos ([0-9]{4}) seguidos de 3 letras ([A-Z]{3})
boolean comprobarMatricula (String matricula){

    if (matricula.toUpperCase().matches("^[0-9]{4}[A-Z]{3}$")) {
        System.out.println("Matrícula válida");
        return true;

    }else{

        System.out.println("Matrícula inválida");
        return false;
    }
}

A: Aquí tendrías un método para generar una matrícula válida:
private static String generaMatricula()
  {
    //Letras válidas para matrícula
    char[] array = {'B', 'C',
                    'D', 'F', 'G', 'H', 'J', 'K', 'L',
                    'M', 'N', 'P', 'R', 'S', 'T', 'V',
                    'W', 'X', 'Y', 'Z'};

    String matricula = "";

    for (int i=0; i<7; i++){
      Random rnd = new Random();
      int ale = (int)(rnd.nextDouble() * array.length); //Aleatorio para la letra
      int ale2 = (int)(rnd.nextDouble() * 10); //Aleatorio entre 0-9
      if (i>3) {
        matricula += array[ale];
      } else {
        matricula +=  ale2;
      }
    }

    return matricula;

  }

Pudiendo llamarlo de la siguiente manera:
System.out.println(generaMatricula());

A: Quieres comprobar si la matricula es valida? Para eso podemos crear un método que compruebe mediante expresiones regulares si la matricula es correcta.
Hay que tener en cuenta que existe el formato europeo y el Español antiguo, para ello podemos utilizar el método siguiente que comprueba ambos casos o, si sólo te interesa el método europeo, puedes hacer un return false en el else del primer if
    final String consonantes = "BCDFGHIJKLMNPQRSTUVWXYZ";
    final Pattern patternES = Pattern.compile("(["+consonantes+"]{1,2})(\\d{4})(["+consonantes+"]{0,2})");
    final Pattern patternEU = Pattern.compile("(\d{4})(["+consonantes+"]{3})");
    boolean checkMatricula(String matricula){
            matricula = matricula.toUpperCase();
            Matcher eu = patternEU.matcher(string);
            if(eu.groupCount()>1){
                 return true;
            }else {
                Matcher es = patternES.matcher(string);
                if(es.groupCount()>1){
                    return true;
                }else {
                    return false;
                }
           }
    }

Aqui tambien puedes utilizar el matcher para devolver los grupos que hay, en el caso de ES tenemos el grupo 0 (toda la matricula), el 1 (primeras letras), el 2 (numeros) y el 3 (ultimas letras) mientras que el EU tenemos el 0 (toda la matricula), 1 (numeros) y 2 (letras)


text:
Q: How to INSTALL kernel 4.4 which no longer resides on the system and then remove kernel 4.10 from ubuntu 16.04 My bluetooth audio arrangement works with 4.4.0-7x but no kernel that I've tried in between that and now 4.10.0-32 and beyond. It's an IHB-23 speaker system that shows up as a headset. On somewhere after 4.4.0-77 or so, something caused the behavior to change FROM:
pair, connect, show up as an audio device that can be set to ADP and actually have audio routed to it.
TO:
pair, connect, show up as an audio device without ADP capability (and only mono) but no audio stream is ever routed to the device. When an attempt is made to select it, the selection appears to change but actually remains at the previous setting. Crazy making. I wish to return to the older kernel.
Would the best way be to scrap the current installation altogether and try to grab a copy of Ubuntu 16.04.0 or 1 and resinstall afresh? Or is there a simple method for installing linux 4.4.0.7x which no longer resides on the system - the headers and images were removed some time ago ... before I decided to try using the system as my "sound" server, more or less.
Thanks for any assistance, this has been pushing my buttons for a while now.

A: Check that linux-image-generic is installed by running sudo apt-get install linux-image-generic, which if necessary will install the latest 4.4 kernel, currently 4.4.0.104.109.
The simplest way to reboot into the 4.4 kernel, is to reboot and press and hold Shift and select the 4.4 kernel at the grub menu. Older kernels may be listed in a sub menu as Advanced options for Ubuntu or Previous Linux Versions. Alternatively sudo nano /etc/default/grub && sudo update-grub to comment out GRUB_HIDDEN_TIMEOUT and GRUB_TIMEOUT=0, write the file Ctrl+o and exit Ctrl+x, update-grub will then run. After update-grub the grub menu should not be hidden when rebooting.
If everything works fine with the 4.4 kernel you can remove all the installed 4.10 kernel packages. See How do I remove old kernel versions to clean up the boot menu? for several methods to remove unwanted kernel packages.
Instead of removing the newer kernels you could change the GRUB_DEFAULT. grep menuentry_id_option /boot/grub/grub.cfg will provide a list of viable values to choose from. For my oldest kernel I could use GRUB_DEFAULT=gnulinux-4.8.17-galliumos-advanced-850a858b-1b7d-4451-8b00-541e3d314ee4

A: Install linux-image-generic, which will install the latest 4.4 kernel, reboot into the 4.4 kernel, and then if everything works fine you can remove all the installed 4.10 kernel packages (see for example apt list --installed | grep linux for a list).


text:
Q: Protobuf parse from char* with unknown size Is there any way to parse Protobuf object from only a char pointer in C++ ? The problem is that the serialized bytes might contain '\0' which makes it impossible to determine the end of array. And The only thing I get from a streaming API is a char pointer to serialized bytes, I cannot change the API.

A:
The only thing I get from a streaming API is a char pointer to serialized bytes, I cannot change the API.

Then you are at an impasse, and this API has never worked.
The protocol buffers documentation explicitly states that there is no framing information encoded into the messages. You must provide your own.


text:
Q: Javascript find index of missing elements of two arrays I have the following JavaScript where I have some lists:
var deleteLinks = $(".remove-button .remove-from-cart");
deleteLinks.on('click', function(ev){
    ev.preventDefault();
    console.log("registered: " + deleteLinks);
    var currentHTML = $('.product');
    var currentText = $('.product .product-details .name-header');
    var newHTML ;
        $.ajax({
        url: this.href,
        type: "GET",
        dataType: "html",
          success: function(data) {
              newHTML = $(data).find('.product .product-details .name-header');
              for(i = 0; i  < newHTML.length; i++){
                  console.log("new: " + newHTML[i].innerText);
                  console.log("old: " + currentText[i].innerText);
              }
          }
    });
});

The variable currentHTML contains an array of divs which are a container. The currentText contains an array of each container's name. The variable received in the AJAX response (newHTML) contains an array of names. This array is updated after some user interaction. One or more entries of the currentText variable may be missing and I want to find the indices of them so I can remove them from the container (currentHTML).
Can someone help me to find the indices of the missing elements between currentText and the retrieved data (newHTML)?

A: To compare two array's value's there is many different approaches to simply see if a value is in another array. You might use array.indexOf(value) to return a position of an element in another array, if the result is greater than expected -1, it is present or the opposite missing. You might also use array.includes(value), and another way is to simply see if a value is not present by using !array.includes(value).
So knowing we can use !array.includes(value) to see if an array does not include a value. We must now loop through one array to grab entries and compare against another array for items that are not in the other array. We will use array.forEach() for this. We could possibly design more recursive functions using array.some(), but I am just trying to give you some simple examples.

Example 1.

// Data
let a = [1, 2, 3, 4, 5]; // Array A
let b = [1, 0, 9, 3, 5]; // Array B

// Basic principals
function check(a, b) {
    // Loop through A using array.some() => value
    a.forEach(value => {
        // B did not include value
        if (!b.includes(value)) {
            // Output
            console.log("B doesn't have", value, "at position", a.indexOf(value), "in A")
        }
    });
    // Loop through B using array.some() => value
    b.forEach(value => {
        // A did not include value
        if (!a.includes(value)) {
            // Output
            console.log("A doesn't have", value, "at position", b.indexOf(value), "in B")
        }
    });
}

// We are checking both Arrays A and B
check([1, 2, 3, 4, 5], [1, 0, 9, 3, 5]);

Example 2

Instead of just outputting to the console for demonstration purposes let's make a prototype for an array element, and then call a comparative function against array B. We will return an array with the [value, position] if that value is not in array B but indeed in array A.

// Data
let a = [1, 2, 3, 4, 5]; // Array A
let b = [1, 0, 9, 3, 5]; // Array B

/*
    Check an array for non-duplicates against another array.
    If the value of item in array A is present in array B,
    return [false, -1]. If value of item in array A is
    not present in B, return value and position of value
    in array A.
 */

Array.prototype.check = function(b) {
    /*
    * return if true
    *   [value, position]
    * else
    *   [false, -1]
    * */
    return a.map(v => {
       return (!b.includes(v) ? [v, a.indexOf(v)] : [false, -1])
    })
};

// Array A is checking against array B
console.log(a.check(b));

/*  Output:
    (A checking against B)
    [
      [ false, -1 ], // Array element 1 found in B
      [ 2, 1 ],  // Array element 2 not found in B, and has position 1 in A
      [ false, -1 ],  // Array element 3 found in B
      [ 4, 3 ], // Array element 4 not found in B, and has position 3 in A
      [ false, -1 ] // Array element 5 found in B
    ]
*/

A: If you have access to lodash, you can use _.difference to solve this in one line.

var a = ['a', 'b', 'c'],
  b = ['b'],
  result = [];
_.difference(a, b).forEach(function(t) {result.push(a.indexOf(t))});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

A: Assuming that you have unique elements in an array A and only one occurrence in the array B. We can just use set to add all the elements of array A and remove the elements from the set when you iterate over Array B. Use findIndex to look up for elements remaining in the set.
const a = [1,2,3,4,5];
const b = [2,1,5,4];
let set = new Set();
a.forEach(ele => set.add(ele));
b.forEach(ele => {
  if(set.has(ele)){
    set.remove(ele);
  }
});
let res = [];
for(let s of set) {
  if(a.findIndex(s) !== -1) {
    res.push({
     arr:  a,
     pos: a.findeIndex(s)
    });
  }else {
    res.push({
     arr:  b,
     pos: b.findeIndex(s)
    });
  }
}

The res array contains the index and the array in which the element is present.

A: As I can see from your code, you need to compare innerText of the two objects and find the indices of missing elemnts.
var missing_indices = [];
for(var i=0;i<currentText.length;i++){
    var found = false;
    for(var j=0;j<newHTML.length;j++){
        if(currentText[i].innerText == newHTML[j].innerText){
            found = true;
            break;
        }
    }
    if(!found){
        missing_indices.push(i);
    }
}

Then use missing_indices to remove missing elements from currentHTML


text:
Q: urllib.error.URLError: I am working on this simple program to connect
import urllib.request
import urllib.request as req
import ssl

req = urllib.request.Request('ftps://ftps-xyz.com')
response = urllib.request.urlopen(req)
the_page = response.read()

I am trying to connect and open a FTPS website to be able to download some files but I get the error.
urllib.error.URLError: <urlopen error unknown url type: ftps

Didn't find many further info on this. Can anyone point me in the right direction. I am using Python 3.6 , Windows.
I am looking to understand what am I doing wrong and if there is an alternative way to implement this?


text:
Q: Splitting up an infinite sum I am playing with the following example trying to determine if $\frac{1}{n}-\frac{1}{\sqrt{n}}$ is in $\ell^2$.
Here is what I have,
\begin{align}
\sum\limits_{n=1}^\infty \left( \frac{1}{n}-\frac{1}{\sqrt{n}}\right)^2 &= \sum\limits_{n=1}^\infty \left(\frac{\sqrt{n}-n}{n\sqrt{n}}\right)^2\\
&=\sum\limits_{n=1}^\infty\frac{n-2n\sqrt{n}+n^2}{n^3}\\
&=\sum\limits_{n=1}^\infty\frac{1}{n^2}-2\sum\limits_{n=1}^\infty\frac{1}{n\sqrt{n}}+\sum\limits_{n=1}^\infty\frac{1}{n}
\end{align}
The first summand is in $\ell^2$, the second summand is in $\ell^2$, but the third summand is not. Thus the sequence $\frac{1}{n}-\frac{1}{\sqrt{n}}$ is not in $\ell^2$. I think I may be making an error when I split the sums. Allowing such splitting would result in things like,
\begin{align}
\sum\limits_{n=1}^\infty\frac{1}{n^2} &= \sum\limits_{n=1}^\infty\frac{1-n^2}{n^2}+\sum\limits_{n=1}^\infty\frac{n^2}{n^2}
\end{align}
What am I missing here?

A: You could note that$$\sum_{n=1}^\infty\frac{n-2n\sqrt n+n^2}{n^3}=\sum_{n=1}^\infty\frac{1-2\sqrt n+n}{n^2}$$and that$$\lim_{n\to\infty}\frac{\frac{1-2\sqrt n+n}{n^2}}{\frac1n}=\lim_{n\to\infty}\frac{1-2\sqrt n+n}n=1.$$Therefore, your series diveres, by the comparison test.

A: Put $a_n=\frac{1}{n}-\frac{1}{\sqrt{n}}, b_n =\frac{1}{n}$ and $c_n=\frac{1}{\sqrt{n}}$.
Suppose that $(a_n) \in \ell^2$. Since $(b_n) \in \ell^2$ and since $\ell^2$ is a vector space, we get that $(c_n)=(b_n)-(a_n) \in \ell^2$, a contradiction. Hence $(a_n) \notin \ell^2$.

A: It is not in $\ell^2$:
\begin{align}
\sum_{n=1}^\infty\frac{n-2n\sqrt n+n^2}{n^3}&=\sum_{n=1}^\infty\frac{1-2\sqrt n+n}{n^2} \\
&= \sum_{n=1}^\infty\frac{(\sqrt{n}-1)^2}{n^2} \\
&\ge \sum_{n=1}^3\frac{(\sqrt{n}-1)^2}{n^2} +  \sum_{n=4}^\infty\frac{\left(\frac12\sqrt{n}\right)^2}{n^2} \\
&= \sum_{n=1}^3\frac{(\sqrt{n}-1)^2}{n^2} + \frac14 \sum_{n=4}^\infty\frac1n \\
&= +\infty
\end{align}
because $\sqrt{n}-1 \ge \frac12 \sqrt{n}$ for all $n \ge 4$.


text:
Q: Postgresql stored procedure on .net Core() I am trying to move our current SQL Server database to PostgreSQL with .net Core 2.2.
I converted all tables (constraints, index), views and stored procedures to Postgre SQL. I have keep all Dbset configuration(except for Connection string) for data models on backend.
I have a problem about running stored procedure (in Postgres) within EF Core. Stored procedure returns a view. Try to map this view to DbSet with FromSql() method from Ef Core. It was running with SQL Server before
The stored procedure in Postgre SQL:
 CREATE OR REPLACE FUNCTION public.getbyusername_vw_sys_menu_lang()
 RETURNS SETOF "VW_SYS_MENU_LANG"
 LANGUAGE sql
AS $$

    --return query
    SELECT M.* FROM "VW_SYS_MENU_LANG" M
    where M."USERNAME" = 'Admin' -- parameters will be added
    limit 10;

$$;

I got error in .net Core :

The required column 'ID' was not present in the results of a 'FromSql' operation.

 var sql = "SELECT GETBYUSERNAME_VW_SYS_MENU_LANG()";
//var sql = "SELECT * FROM VW_SYS_MENU_LANG" //it works with view
 var result1 = dbSet.FromSql(sql) //error : The required column 'ID' was not present in the results of a 'FromSql' operation.

MyDbcontext : DbContext
   ....
   ....
 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<VW_SYS_MENU_LANG>(e => { e.HasKey(t => new { t.ID, t.LANG }); });

In postgres, I can run stored procedure without any error and it return the result as expected and ID column does exist with capital characters. I have converted all tables and column names as Capital letters.
I think something should be edited on DbContext class on EF Core or Postgres stored procedure.
------------ UPDATE  -------------
Confused a bit , I was using Dbeaver to create and test PostgreSQL tables , functions etc.
When I run SELECT GETBYUSERNAME_VW_SYS_MENU_LANG() function on Dbeaver it returns table with all columns and data:

When I run same function on Pgadmin , result is :

A: It should be
SELECT * from GETBYUSERNAME_VW_SYS_MENU_LANG()

instead of
SELECT GETBYUSERNAME_VW_SYS_MENU_LANG()

It was hard to find the differences as a rookie PostgreSQL dev.
2nd returns one column with all data, comma separated. 1st returns all columns of table(or view)


text:
Q: Data from Database to Textbox I am very new to the programming field, like 4 months new, so I think I have a very stupid question for 99% of you.
I am busy creating a very basic booking program to practice and is struggling like a mad pig.
1) I basically want to pull data from MySql to a textbox.
2) My aim for this is that I need to get a loop going for the booking id to be saved in MySql. Not sure if you all would understand what I am saying.
Current Code:
string connection = "datasource = localhost; port = 3306; username = root; password = ****";
string query = "SELECT * FROM databasename.tablename where id='"this.textbox1.Text"' ";
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = new MySqlCommand(query, conn);
MySqlDataReader reader;
conn.Open();
reader = command.ExecuteReader();
while (reader.Read())
{

}

A: Just need to proper use your query, using parameters:
string connection = "datasource = localhost; port = 3306; username = root; password = ****";

string query = "SELECT * FROM databasename.tablename where id=@ID ";

MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = new MySqlCommand(query, conn);
command.Parameters.Add("@ID",textBox1.Text);
MySqlDataReader reader;
conn.Open();

reader = command.ExecuteReader();

while (reader.Read()) {}


text:
Q: Passthrough does not return decimal values anymore Hope I don't ask an already existing question. Didn't find a solution on the internet after a couple of hours of search.
I think this issue is pretty new, maybe caused by a recent update.
In my MS Access VBA code, I am using passthrough queries to get results from SPs on my MS SQL Server.
For a few weeks now, I do not receive decimal values as results anymore, the values are just null in this case.
Here is a very easy code example:
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSQL As String

strSQL = "SELECT 'abcde' AS string, '2020-07-01' AS date, 123.45 AS decimal, 3 as int"

Set qdf = db.CreateQueryDef("")
qdf.Connect = [here is my connectiong string]
qdf.SQL = strSQL
qdf.ReturnsRecords = True
Set rs = qdf.OpenRecordset

When working with that result, e.g. by copying that into an Excel file, the string; date, and integer value are written as required. Only the decimal value is a null instead.
Hope I didn't miss any essential information here. If you have any questions, just let me know.
Thanks for the help in advance!
BR,
Martin

A: As it appears that your code was working and now isn't, it may be that you have encountered a recent bug in Microsoft Access: Access VBA/DAO code may crash or report incorrect data for Decimal columns which has now apparently been fixed.
Regards,

A: It appears that you are trying to cast/type your values.  You are actually creating calculated fields.
Surrounding your date strings with hashes indicates that the values are dates:

#2020-07-01#

Use the appriate  C function to cast all numeric values:

Cdbl(123.45)
CInt(3)


text:
Q: What is unhandled excpetion error mean? I am writing in Visual Studio,a C programm and I get this error: Unhandled exception at 0x77dd3e14 in SciComput.exe: 0xC0000005: Access violation reading location 0xff630018.
Can someone explain to a quite absolute beginner what does this mean?

A: In addition to the good answer by Eutherpy, I would add that the access violation is usually from trying to read or write NULL, which is location zero. Location 0xff630018 is definitely out of bounds, but also is definitely not zero; something strange is going on here.
Windows reserves the bottom 2GB of virtual address space for the "user" half of your process -- that is, the code you are actually running in the process. The top 2GB, which have addresses from 0x80000000 to 0xffffffff are reserved for the use of the operating system to store data associated with your process. Any attempt to access OS-owned memory from user code will immediately result in an access violation.  But why is your program trying to access operating system memory in the first place?
Like I said, something strange is going on here. Likely there is some other memory corruption that is then manifesting in this behaviour; this is likely a symptom of some completely different bug.
These are hard to track down. Good luck!

A: It means that you are trying to access a segment of memory that doesn't "belong" to your program, i.e. memory you haven't allocated, reserved.
Usually, causes for such errors are attempting to write read-only memory or dereferencing NULL-pointers.
"Unhandled exception" means that you haven't provided a way for the program to handle errors when they occur, so it simply crashes.
Note: You can handle exceptions via try...catch mechanism in C++. http://msdn.microsoft.com/en-us/library/6dekhbbc.aspx C, however, doesn't support this.


text:
Q: Remove Visual Editor and P tags from WooCommerce Taxonomy Descriptions WooCommerce: Products >  Categories/Tags/Brands > Description.

*

*By default visual editor is enabled. How do you disable that to be only a basic text area only?

Most threads here seem to be on 'adding' the editor so assuming at some point WP or WooCommerce added the editor by default.

A: Hope,  The following code solve your problem. Add this in functions.php
$tags = $_GET['taxonomy'];
$taxonomy_name = array('product_tag','product_cat');
if (in_array($tags, $taxonomy_name)) {
  add_action("{$tags}_edit_form_fields", 'form_fields', 10, 2);
}
function form_fields($term, $taxonomy){
    ?>

        Description

            <?php wp_editor(html_entity_decode($term->description), 'description', array('media_buttons' => false,'quicktags' => false)); ?>

    <?php
}


text:
Q: Using amazon s3, upload files using their servers but URL should appear to be from mine Is it possible to upload files to amazon S3, using their servers (i.e. my server shouldn't be used in the upload process)?
I also want the URL to appear to be uploading to my server, is this possible?

A: Look here for instructions on how to setup your CNAME record so that one of your subdomains can be an alias for an Amazon S3 bucket.
Depending on your needs, you might not want "s3.amazonaws.com" to appear on your web site or service. For example, if you host your web site's images on Amazon S3, you might prefer http://images.johnsmith.net/ to http://johnsmith-images.s3.amazonaws.com/


text:
Q: Problem in POST and PUT request, with axios, vuetify datatable, vuejs I'm trying to adapt a sample datatable from the vuetify website itself according to my needs by implementing axios to consume my api. The GET AND DELETE method is working perfectly, however I am very confused about the POST AND PUT method, I am using 2 models as a client and the relationship with the genre, follows part of the code:
<template>
    <v-data-table
      :headers="headers"
      :items="clients"
      sort-by="firstName"
      class="elevation-2"
    >
      <template v-slot:top>
        <v-toolbar flat color="white">
          <v-icon medium>mdi-account-supervisor</v-icon>
            <v-toolbar-title> Clients</v-toolbar-title>
          <v-divider
            class="mx-4"
            inset
            vertical
          ></v-divider>
          <v-spacer></v-spacer>
          <v-dialog v-model="dialog" max-width="600px">
            <template v-slot:activator="{ on }">
                <v-btn
                color="blue"
                dark class="mt-6 mb-4"
                v-on="on"
                rounded
                ><v-icon medium>mdi-plus</v-icon>Add new</v-btn>
            </template>
            <v-card>
              <v-card-title>
                {{ formTitle }}
              </v-card-title>

              <v-card-text>
                <v-container>
                  <v-form>
                    <v-row>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.firstName" label="First Name"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.lastName" label="Last Name"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.email" label="E-Mail"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.phone" label="Phone"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.mobilePhone" label="Mobile Phone"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">

                        <v-select
                          label='Gender'
                          v-model='editedItem.gender.name'
                          :items='genders'
                          item-value='name'
                          item-text='name'
                        >
                        </v-select>
                      </v-col>
                    </v-row>
                  </v-form>
                </v-container>
              </v-card-text>

              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" rounded @click="close">Cancel</v-btn>
                <v-btn color="primary" rounded @click="save">Save</v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-toolbar>
      </template>
      <template v-slot:item.action="{ item }">
        <v-icon
          small
          color="green"
          class="mr-2"
          @click="editItem(item)"
        >
          mdi-pencil
        </v-icon>
        <v-icon
          small
          color="red"
          @click="deleteItem(item)"
        >
          mdi-delete
        </v-icon>

      </template>
      <template v-slot:no-data>
        <v-btn color="primary" @click="initialize">Reset</v-btn>
      </template>
    </v-data-table>
</template>

When opening the modal to add item, only when opening the select and modifying the genre this error already appears before even saving, as shown in the image:
When clicking on save it is saved only on the front, and when updating the page the record disappears, could someone give me a light?
Update Edit.
After some changes, I think I am closer to the solution but I came to the following obstacle, When saving the client item, the gender is stored empty.
 of console.log and the item saved in the front end but in the database the gender is empty
The file DataTable.vue:
<template>
    <v-data-table
      :headers="headers"
      :items="clients"
      sort-by="firstName"
      class="elevation-2"
    >
      <template v-slot:top>
        <v-toolbar flat color="white">
          <v-icon medium>mdi-account-supervisor</v-icon>
            <v-toolbar-title> Clients</v-toolbar-title>
          <v-divider
            class="mx-4"
            inset
            vertical
          ></v-divider>
          <v-spacer></v-spacer>
          <v-dialog v-model="dialog" max-width="600px">
            <template v-slot:activator="{ on }">
                <v-btn
                color="blue"
                dark class="mt-6 mb-4"
                v-on="on"
                rounded
                ><v-icon medium>mdi-plus</v-icon>Add new</v-btn>
            </template>
            <v-card>
              <v-card-title>
                {{ formTitle }}
              </v-card-title>

              <v-card-text>
                <v-container>
                  <v-form>
                    <v-row>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.firstName" label="First Name"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.lastName" label="Last Name"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.email" label="E-Mail"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.phone" label="Phone"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.mobilePhone" label="Mobile Phone"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">

                        <v-select
                          label='Gender'
                          v-model='editedItem.gender'
                          :items='genders'
                          item-value='name'
                          item-text='name'
                        >
                        </v-select>
                      </v-col>
                    </v-row>
                  </v-form>
                </v-container>
              </v-card-text>

              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" rounded @click="close">Cancel</v-btn>
                <v-btn color="primary" rounded @click="save">Save</v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-toolbar>
      </template>
      <template v-slot:item.action="{ item }">
        <v-icon
          small
          color="green"
          class="mr-2"
          @click="editItem(item)"
        >
          mdi-pencil
        </v-icon>
        <v-icon
          small
          color="red"
          @click="deleteItem(item)"
        >
          mdi-delete
        </v-icon>

      </template>
      <template v-slot:no-data>
        <v-btn color="primary" @click="initialize">Reset</v-btn>
      </template>
    </v-data-table>
</template>

Please would someone help me?

A: There are a couple of issues. First, you aren't passing any data to your PUT and POST requests. They should look something like:
editItem (item) {
  // YOU NEED TO PASS AN OBJECT TO THE PUT REQUEST         ▼▼HERE▼▼
  axios.put('http://192.168.26.130:3000/client/' + item.id , item)
    .then(response => {
      // handle response...
    })
    .catch(err => { console.log(error) })
},
save () {
  if (this.editedIndex > -1) {
    // YOU NEED TO PASS AN OBJECT TO THE POST REQUEST  ▼▼HERE▼▼
    axios.post('http://192.168.26.130:3000/client/', this.editedItem)
      .then(response => {
        // handle response...
      })
      .catch(err => { console.log(error) })
  } else { /* ... */ }
},

Second, under the hood, <v-select> uses a v-for to iterate over all of the options that are supposed to go into the dropdown menu. If this were a plain HTML <select> element, it would look something like this:
<select name="gender">
  <option value="">Select a gender...</option>
  <option
    v-for="gender in genders"
    :key="gender"
    value="gender.value"
  >
    {{ gender.text }}
  </option>
</select>

Vuetify expects the array of genders to be in one of two formats, either an array of strings, or an array of objects with text and value properties:
const genders = ['male', 'female', 'other']
// OR
const genders = [
  { value: 1, text: 'male' }, // `value` can be anything you want
  { value: 2, text: 'female' },
  { value: 3, text: 'other' },
]

Alternatively, if your genders array has a different data structure, you can tell Vuetify what properties to use for the value and text properties (this is what it looks like you did). So if your genders array looks like this:
const genders = [
  { name: 'male' },
  { name: 'female' },
  { name: 'other' },
]

Your <v-select> should look like this (in your case you used the SAME property for both text and value, which is perfectly fine to do):
<v-select
  v-model="editedItem.gender"
  :items="genders"
  item-text="name"
  return-object
/>

What I'm guessing, based on the image you attached, is that the genders array is NOT in one of these formats, and this is causing an error when Vuetify tries to turn it into a dropdown. Also, I think you intend for the value selected to be assigned to editedItem.gender and not editedItem.gender.name. Here's a codepen showing how to use objects for v-select items.
If the items array is in one of the two formats I showed before, you do NOT need to specify the item-text and item-value props. They will be detected automatically.
Hope this helps!


text:
Q: Why is there no 'headers already sent' error? I wrote this code, which should cause an error, but no error is showing!
<?php
    error_reporting(-1);
    echo "s";
    header("Location: /index2.php");
?>

Because header() is after the echo, PHP should error out with headers already sent; but no error shows, and the page successfully redirects to index2.php!
How can I see the error? Why does the redirect take place?

A: Check wether Output buffering is activated.
It is the same as ob_start, but implicit.

A: Really, First time I'm seeing someone who really wants to see the header already sent error. Something that usually offends me big time. since I solve it by using ob_start() and ob_flush, I think in your case, the server is solving the buffer problem for you.
Try using PHP ob_end_flush() to turn off buffer. Or read this: https://stackoverflow.com/a/6386034/827224


text:
Q: spark - How to reduce the shuffle size of a JavaPairRDD? I have a JavaPairRDD<Integer, Integer[]> on which I want to perform a groupByKey action.
The groupByKey action gives me a:

org.apache.spark.shuffle.MetadataFetchFailedException: Missing an output location for shuffle

which is practically an OutOfMemory error, if I am not mistaken. This occurs only in big datasets (in my case when "Shuffle Write" shown in the Web UI is ~96GB).
I have set:

spark.serializer        org.apache.spark.serializer.KryoSerializer

in $SPARK_HOME/conf/spark-defaults.conf, but I am not sure if Kryo is used to serialize my JavaPairRDD.
Is there something else that I should do to use Kryo, apart from setting this conf parameter, to serialize my RDD? I can see in the serialization instructions that:

Spark automatically includes Kryo serializers for the many commonly-used core Scala classes covered in the AllScalaRegistrar from the Twitter chill library.

and that:

Since Spark 2.0.0, we internally use Kryo serializer when shuffling RDDs with simple types, arrays of simple types, or string type.

I also noticed that when I set spark.serializer to be Kryo, the Shuffle Write in the Web UI increases from ~96GB (with default serializer) to 243GB!
EDIT: In a comment, I was asked about the logic of my program, in case groupByKey can be replaced with reduceByKey. I don't think it's possible, but here it is anyway:

*

*Input has the form:

*

*key: index bucket id,

*value: Integer array of entity ids in this bucket

*The shuffle write operation produces pairs in the form:

*

*entityId

*Integer array of all entity Ids in the same bucket (call them neighbors)

*The groupByKey operation gathers all the neighbor arrays of each entity, some possibly appearing more than once (in many buckets).

*After the groupByKey operation, I keep a weight for each bucket (based on the number of negative entity ids it contains) and for each neighbor id I sum up the weights of the buckets it belongs to.

*I normalize the scores of each neighbor id with another value (let's say it's given) and emit the top-3 neighbors per entity.
The number of distinct keys that I get is around 10 million (around 5 million positive entity ids and 5 million negatives).
EDIT2: I tried using Hadoop's Writables (VIntWritable and VIntArrayWritable extending ArrayWritable) instead of Integer and Integer[], respectively, but the shuffle size was still bigger than the default JavaSerializer.
Then I increased the spark.shuffle.memoryFraction from 0.2 to 0.4 (even if deprecated in version 2.1.0, there is no description of what should be used instead) and enabled offHeap memory, and the shuffle size was reduced by ~20GB. Even if this does what the title asks, I would prefer a more algorithmic solution, or one that includes a better compression.

A: Short Answer: Use fastutil and maybe increase spark.shuffle.memoryFraction.
More details:
The problem with this RDD is that Java needs to store Object references, which consume much more space than primitive types. In this example, I need to store Integers, instead of int values. A Java Integer takes 16 bytes, while a primitive Java int takes 4 bytes. Scala's Int type, on the other hand, is a 32-bit (4-byte) type, just like Java's int, that's why people using Scala may not have faced something similar.
Apart from increasing the spark.shuffle.memoryFraction to 0.4, another nice solution was to use the fastutil library, as suggest in Spark's tuning documentation:

The first way to reduce memory consumption is to avoid the Java features that add overhead, such as pointer-based data structures and wrapper objects. There are several ways to do this: Design your data structures to prefer arrays of objects, and primitive types, instead of the standard Java or Scala collection classes (e.g. HashMap). The fastutil library provides convenient collection classes for primitive types that are compatible with the Java standard library.

This enables storing each element in int array of my RDD pair as an int type (i.e., using 4 bytes instead of 16 for each element of the array). In my case, I used IntArrayList instead of Integer[]. This made the shuffle size drop significantly and allowed my program to run in the cluster. I also used this library in other parts of the code, where I was making some temporary Map structures. Overall, by increasing spark.shuffle.memoryFraction to 0.4 and using fastutil library, shuffle size dropped from 96GB to 50GB (!) using the default Java serializer (not Kryo).
Alternative: I have also tried sorting each int array of an rdd pair and storing the deltas using Hadoop's VIntArrayWritable type (smaller numbers use less space than bigger numbers), but this also required to register VIntWritable and VIntArrayWritable in Kryo, which didn't save any space after all. In general, I think that Kryo only makes things work faster, but does not decrease the space needed, but I am not still sure about that.
I am not marking this answer as accepted yet, because someone else might have a better idea, and because I didn't use Kryo after all, as my OP was asking. I hope reading it, will help someone else with the same issue. I will update this answer, if I manage to further reduce the shuffle size.

A: Still not really sure what you want to do. However, because you use groupByKey and say that there is no way to do it by using reduceByKey, it makes me more confused.
I think you have rdd = (Integer, Integer[]) and you want something like (Integer, Iterable[Integer[]]) that's why you are using groupByKey.
Anyway, I am not really familiar with Java in Spark, but in Scala I would use reduceByKey to avoid the shuffle by
rdd.mapValues(Iterable(_)).reduceByKey(_++_) . Basically, you want to convert the value to a list of array and then combine the list together.

A: I think the best approach that can be recommended here (without more specific knowledge of the input data) in general is to use the persist API on your input RDD.
As step one, I'd try to call .persist(MEMORY_ONLY_SER) on the input, RDD to lower memory usage (albeit at a certain CPU overhead, that shouldn't be that much of a problem for ints in your case).
If that is not sufficient you can try out .persist(MEMORY_AND_DISK_SER) or if your shuffle still takes so much memory that the input dataset needs to be made easier on the memory .persist(DISK_ONLY) may be an option, but one that will strongly deteriorate performance.


text:
Q: Use addMethod in jQuery Validate plugin I want to validate a text box using jQuery Validate plugin's custom validation method (addMethod) but my code doesn't work.  Can anyone help me to find the error?  I have never used custom validation method before so it's bit hard for me to find where I went wrong in this code.
This is my code:
$(document).ready(function () {

jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod(
"selectnic"
function(value,element){
if(element.value == /^[0-9]{9}[vVxX]$/)
   return false;
   else return true;
},
"wrong nic number"
);

    $('#basicDetails').validate({ // initialize the Plugin
        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                },
                lname: {
                    required: true,
                    lettersonly: true,
                },
            },
        messages: {
           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",
            },
        },
        submitHandler: function (form) {
            alert('valid form submitted');
            return false;
        }
    });

});

..html code ....
<form action="#" method="post"  id="basicDetails" runat="server">

                                     First name
                                    :
                                    <input type="text" name="fname" id="fname" class="textbox" placeholder="Required field"/>

                                     Last name  :
                                    <input type="text" name="lname" class="textbox" id="lname" placeholder="Required field"/>

                                     NIC no
                                     :
                                    <input type="text" name="nic" id="nic"   class="textbox"  placeholder="Required field"/>

                                    Passport no   :
                                     <input type="text" name="passport" class="textbox" id="ppnu" placeholder="Required field"/>

                                    <input type="submit" name="submit"  value="Submit "class="submit"   id="submit" />
                                    <input type="submit" name="reset"  value="Reset "class="reset" />

</form>

.....after editing my code  ....
$(document).ready(function () {

jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;
    } else {
        return true;
    };
}, "wrong nic number");

    $('#basicDetails').validate({ // initialize the Plugin

        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                        },
                lname: {
                    required: true,
                    lettersonly: true,
                    },

                 nicnumber: {
                            // other rules,
                        selectnic: true // <-  declare the rule someplace!
                            }

            },

        messages: {

           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",

            },
        },

        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});

A: There are three different issues as outlined by the progressing edits below.

1)
You missed a comma just between selectnic and the function(.
Also, try this format instead when using regex...
jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;  // FAIL validation when REGEX matches
    } else {
        return true;   // PASS validation otherwise
    };
}, "wrong nic number");

EDIT:  This answer assumes your original regex and logic are both correct.  Your logic returns false when the regex is a match.  false means that validation failed and you will see the error message.

2) EDIT 2:
After creating new methods, you also have to use them.  I do not see the selectnic rule/method used anyplace in your code.
Example:
rules: {
    myFieldName: {
        // other rules,
        selectnic: true // <-  declare the rule someplace!
    }
}

3) EDIT 3:
And finally, the OP's original true/false logic was backwards.  He wanted to PASS validation upon a regex match… therefore, needs to return true.
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return true;   // PASS validation when REGEX matches
    } else {
        return false;  // FAIL validation
    };

DEMO:  http://jsfiddle.net/DzvNr/

A: This is my solution including Greek characters.
$.validator.addMethod('alphabet', function (value, element) {

        let regExName = /^[A-Za-zΑ-Ωα-ωίϊΐόάέύϋΰήώ]+$/;
        return (regExName.test(value));

    }, 'There are non alphabetic characters!');

  $("#orderForm").validate({
     rules: {
          first_name: {
             required: true,
             alphabet: true
          }
});


text:
Q: copying photos from an I phone 4s that is not on your itunes I bought a phone off E bay that had a broken screen. The person that I bought it off has asked me if I can fix it could they have the photos it had an app locker on it and have disabled that but they cannot remember what the I tunes password was so cannot access the camera role folder. Can anybody help. I need to wipe the phone as its a Christmas gift and don't want to get rid of the photos as they are all of the blokes family.

A: You can use i-Funbox to pull photos off the iPhone. It should be easy, qbut if not, please ask.
The photos would be stored in /var/mobile/Media/DCIM/.


text:
Q: Mysql database, problem with converting dates (dd/mm/yy) stored in text to Datetime I have received a Mysql table with customer data which is pretty badly structured, almost all the fields are TEXT. To prevent losing data I have created another table where I am trying to import the columns in a correct and useful manner. Splitting Full_name into name and surname columns work great but when I try to convert the field created_time containing dd/mm/yy date to DATETIME it shows wrong data eg. 10/10/18 to 2010-10-18.
I have resorted to creating another field created_time_old, copying the text data there and then converting it via STR_TO_DATE as some other answer suggested. However, I can only put strings there, when I put the whole column it just gives me:
1411 - Incorrect datetime value: '' for function str_to_date.
I assume that there is another way/function that will manage to do it but I am not very experienced when it comes to SQL. Moreover, if you have any other suggestions when it comes to my code, please post them :)
My code is below
TRUNCATE TABLE Facetel_bazaPGS;
INSERT INTO Facetel_bazaPGS (id,created_time_old,campaign_name,email,Imię,Nazwisko,`phone_number`,platform,Time_added)

SELECT `id`,created_time,`campaign_name`,`email`,substring_index(`full_name`, ' ',1 ),substring(`full_name` from INSTR(`full_name`, ' ') + 1),`phone_number`,`platform`,Time_added

FROM `Facetel_bazaPGS_input`;
UPDATE Facetel_bazaPGS

SET platform = Replace(REPLACE(platform, 'fb', 'Facebook') , 'ig', 'Instagram');

UPDATE Facetel_bazaPGS
SET created_time = STR_TO_DATE(`created_time_old`, '%d/%m/%y');

EDIT#1: Adding sample data (can't give real data because of GDPR)
+------------------+--------------+---------------+--------------------+--------------+---------------------+----------+---------------------+
|        id        | created_time | campaign_name |       email        |  full_name   |    phone_number     | platform |     Time_added      |
+------------------+--------------+---------------+--------------------+--------------+---------------------+----------+---------------------+
| 1010334092505681 | 10/10/18     | leady         | samplemail@mail.eu | Name         | your_typical_number | ig       | 2018-10-11 08:29:45 |
| 1010457652493325 | 10/10/18     | leady         | samplemail@mail.eu | Name Surname | your_typical_number | ig       | 2018-10-11 08:29:45 |
| 1010470612492029 | 10/10/18     | leady         | samplemail@mail.eu | Name Surname | your_typical_number | fb       | 2018-10-11 08:29:45 |
+------------------+--------------+---------------+--------------------+--------------+---------------------+----------+---------------------+

A: This answer is a speculation, but it attempts to get to the root cause of your 1411 error coming from the call to STR_TO_DATE.  We can try running the following query to detect malformed date strings in your Facetel_bazaPGS_input source table:
SELECT *
FROM Facetel_bazaPGS_input
WHERE created_time NOT REGEXP '^[0-9]{2}/[0-9]{2}/[0-9]{2}$';

This would return any record not having a created_time in the format you expect.  If you don't see an empty result set, then you can fix the date strings.
Note: Just now I can see that your error message seems to be saying that some created_time values are either empty string or NULL.  In either case, the above query should flush out such records.

A: Thank you again for all your suggestions, I have given up, changed the format of the column in Excel, imported again and asked for any future imputs to have YYYY-MM-DD format in the created_time column.


text:
Q: A map of boost:signals with boost:function definition I am trying to create a simple manager that will map error codes to functions. But since a map copies the values and a signal is noncopyable that is not a solution. I cannot use a map of shared_ptr pointers since the * operator is blocked in boost::function.
Which collection should I use to store this?
typedef boost::function<bool (shared_ptr<EngineEvent> event,long timeSinceEvent)> EngineErrorHandler;
typedef boost::signal<bool (  EngineErrorHandler )> ErrorSignal;
typedef std::map<EventErrorType,ErrorSignal> ErrorHandlers;

class ServiceErrorManager {

    public:
        static ServiceErrorManager* getInstance();

        void registerErrorHandler(EngineErrorHandler& handler,EventErrorType subScribeTo);
        void signalEngineEventfail(shared_ptr<EngineEvent> event);

    private:
        static ServiceErrorManager* m_pInstance;

       ErrorHandlers errorTypeToSignal;

        ServiceErrorManager();
        ~ServiceErrorManager();
    };
}

A: You could always store everything into a struct and store shared_ptr or unique_ptr objects inside a map or set using a custom predicate. This seems like it would make your code a bit more self-explanatory as well.


text:
Q: Athena Query to match Alpha numeric Character at a fixed length in a colum data In AWS Athena, how should i write query to get column values when the values is A-Z after dot'.'.
List of Column Values are :
DT90411.A7
CT90411.23
CT90411.Q3

Currently i am not able to fetch value that have A-Z characters after dot'.'
Expected result :
DT90411.A7
CT90411.Q3

These have characters A-Z after dot'.'
Select Col_A from Table1 where Col_A  like '%.[a-z]%'; is not giving the desired result

A: Use regexp_like.
Demo:
with Table1  as(
SELECT * FROM (
    VALUES
        'DT90411.A7', 'CT90411.23' ,'CT90411.Q3'
) AS t (Col_A )
)

select Col_A
from Table1
where regexp_like(Col_A,'(i?)\.[A-Z]')

Result:
Col_A

DT90411.A7
CT90411.Q3

Regexp '(i?)\.[A-Z]' means:
(i?)  - case insensitive, remove it is you need case sensitive match
\.    - dot
[A-Z] - character class, letters A to Z


text:
Q: url re writing using htaccess in php I am working on property site and I want to rewrite some of the url in my site. There are some urls which list the property type-wise. In the footer there is a list of property types such as hotels, privatevilla, apartments....etc.
Now the url of this page is property_list.php?propertytype_id=12 where 12 is the property id of apartment. Instead of this url I'd given apartments.
When user clicks on this link then the url should be sitename/apartments instead of showing property_list.php?propertytype_id=12. I've written the following code in my .htaccess file:
RewriteEngine On
RewriteRule ^([a-zA-Z]+)?$ /property_list.php?propertytype_id=$1 [NC,L]

When I click on aprtments then at that time it is showing apartments in the url and listing all apartments but the thing is it is redirecting home page and other pages also.
How do I redirect only property type related pages?

A: So you basically want this?
RewriteEngine On
RewriteRule ^apartments$ /property_list.php?propertytype_id=12 [NC,L]

A: Is this what you are looking for. So when the URL is /sitename/apartments rewrite it to /property_list.php?propertytype_id=12
RewriteEngine On
RewriteCond %{REQUEST_URI} /sitename/apartments [NC]
RewriteRule ^(.*)?$ /property_list.php?propertytype_id=12 [NC,L]


text:
Q: Pass JSON String From ColdFusion To Javascript I am trying to pass a ColdFusion-generated JSON string as a parameter into a Javascript function.  I'm getting an "Uncaught SyntaxError: Invalid or unexpected token" error I think because of some combination of single and double quotes that just aren't organized right.
Here is some sample code:

<cfset x = {"firstName"="Bob", "lastName"="Smith"} />
<cfdump var="#x#" />
<cfset y = serializeJSON(x) />
<cfdump var="#y#" />

<cfoutput>
Uncaught SyntaxError: Invalid or unexpected token

</cfoutput>

I've tried experimenting with JSStringFormat, but that didn't seem to help.  Any thoughts or suggestions on how to pass the JSON string would be helpful.  Thx!
(I'm running on Lucee 5.2.6.60.)

A: Couple things.
In order to output JSON data or any object in the console, you have to stringify that bad boy. This can be done in JQuery with Stringify.
Also, it took several rounds of testing and tweaking in order to output the HTML correctly - on Chrome at least. The hyperlink seriously did not like all the double quotes and nothing I tried would escape them. I swapped it out with a button and used onClick instead. I got the following code to work.

<cfset x = {"firstName"="Bob", "lastName"="Smith"} />
<cfdump var="#x#" />
<cfset y = serializeJSON(x) />
<cfdump var="#y#" />

<cfoutput>
<button onclick='myJSFunction(#y#);'>test</button>

</cfoutput>


text:
Q: SSIS package deployed to SQL Server hangs when running a Powershell script We have a SSIS package that tidies up a few files and folders, and want to automate it to run every night via the SQL Server Agent.
When running the package via Visual Studio (2015 and 2017) the package completes successfully. When the package is deployed to SQL Server 2012, it never gets past the element that runs a Powershell script - it simply hangs forever (3 days is the record so far).
SSIS data flow:

"Run Compression PowerShell Script" task:

The Powershell script is very basic - two lines of code:
$filePathName = $args[0];

Compress-Archive -Path $filePathName -DestinationPath $filePathName

We think it may be a permissions issue, but we're not sure where to progress this further.
Any help is gratefully received.
Thank you

A: The SSIS element was a red herring. The issue was the execution policy being passed to PowerShell when running the script.
Changing from

-ExecutionPolicy Unrestricted

to

-ExecutionPolicy ByPass

has resolved the issue.

A: Assuming you're running the package via a SQL Server Agent job, are you running the step as the SQL Server Agent service account or a custom proxy? That will determine the context by which the PoSh script will run.
Also, under the Execution Options tab for the SSIS job step, are you running with 32-bit or 64-bit mode enabled? This will be set for the architecture of the SQL instance, while Visual Studio may be a 32-bit installation.


text:
Q: How to represent Activity Diagram with multiple scheduled background jobs? I would like to know what is the correct way to visualize background jobs which are running on a schedule controlled by scheduling service?
In my opinion the correct way should be to have an action representing the scheduling itself, followed by fork node which splits the flow for each of the respective scheduled jobs.

Example. On a schedule Service X is supposed to collect data from an API every day, on another schedule Service Y is supposed to aggregate the collected data.
I've tried to research old themes and find any diagram representing similar activity.

A: Your current diagram says that:

*

*first the scheduler does something (e.g.  identifying the jobs to launch)

*then passes control in parallel to all the jobs it wants to launch

*no other jobs are scheduled after the scheduler finished its task

*the first job that finshes interrupts all the others.

The way it should work would be:

*

*first the scheduler is setup

*then the setup launches the real scheduler,  which will run in parallel to the scheduled jobs

*scheduled jobs can finish (end flow, i.e.  a circle with a X inside) without terminating everything

*the activity would stop (flow final) only when the scheduler is finished.

Note that the UML specifications do not specify how parallelism is implemented.  And neither does your scheduler:  whether it is true parallelism using multithreaded CPUs or multiple CPUs, or whether it is time slicing where some interruptions are used to switch between tasks that are executed in reality in small sequential pieces is not relevant for this modeling.
The remaining challenges are:

*

*the scheduler could launch additional jobs.  One way of doing it could be to fork back to itself and to a new job.

*the scheduler could launch a variable number of jobs in parallel. A better way to represent it is with a «parallel» expansion region, with the input corresponding to task object,  and actions that consume the taks by executing them.

*if the scheduler runs in parallel to the expansion region,  you could also imagine that the schedule provides at any moment some additional input (new tasks to be processed).


text:
Q: Which elements in $\mathbb{Z}_5$ have multiplicative inverses? Which elements in $\mathbb{Z}_5$ have multiplicative inverses?
I have drawn this in a small table:
*|0 1 2 3 4
-----------
0|0 0 0 0 0
1|0 1 2 3 4
2|0 2 4 1 3
3|0 3 1 4 2
4|0 4 3 2 1

Everywhere in table where we see a $1$ we have multiplicative inverse I think, so in total we have $4$ multiplicative inverses, is that right?
Is there a more efficient way answering this question? Because making table is too exhausting.

A: Indeed, from reading your table, we can see that every element with a $1$ in its row has a multiplicative inverse, which is to say all the non-zero elements.
However: in any book that mentions the notion of a multiplicative inverse, you should find the following statement in one form or another

$a$ has a multiplicative inverse in $\Bbb Z_n$ if and only if $a$ is relatively prime to $n$

Of course, if $n$ is prime, then every non-zero element has a multiplicative inverse in $\Bbb Z_n$.

A: I will prove that if $p$ is a prime number (as $p=5$ in your case), then every $a \pmod p$ different from $0 \pmod p$ (i.e. we can take $1≤a≤p-1$) has a multiplicative inverse.
Since $p$ is a prime number, the gcd of $a$ and $p$ is $1$. By Bézout's identity, there are integers $x,y \in \Bbb Z$ such that $ax+py=1$. Then $$\bar x \bar a = \bar 1,$$ where $\bar k$ denotes the equivalence class of $k$ modulo $p$.
So we've shown that $a \pmod p$ has inverse $x \pmod p$.

A: Hint $\ $ Ponder the following chain of equivalences mod $n$
$\qquad\ \ ab\equiv 1\ \ {\rm for\ some}\ b$
$\iff a\mapsto ax\ \ \rm is\ onto.\ \ \ Proof\!:\ (\Leftarrow)\ \ clear.\ \ (\Rightarrow)\ \ c \equiv a(bc). $
$\iff a\mapsto ax\ \ \rm is\,\ 1\!-\!1,\ \ $ since, by pigeonholing, a map on a finite set is onto $\!\iff\!1\!-\!1$
$\iff  \ker(a\mapsto ax) = 0$
$\iff   ax\equiv 0\,\Rightarrow\, x\equiv 0$
$\iff\  n\mid ax\,\Rightarrow\  n\mid x$
$\iff (n,a) = 1$

A: Because 5 is prime, gcd(a,5)=1 for a=1,2,3,4. So 4 elements have multiplicative inverse (which means that $\mathbb Z_5$ is a field.


text:
Q: Python, Tornado: gen.coroutine decorator breaks try-catch in another decorator I have a class with plenty static methods with Tornado coroutine decorator. And I want to add another decorator, to catch exceptions and write them to a file:
# my decorator
def lifesaver(func):
    def silenceit(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as ex:
            # collect info and format it
            res = ' ... '
            # writelog(res)
            print(res)
            return None

    return silenceit

However, it doesn't work with gen.coroutine decorator:
class SomeClass:

    # This doesn't work!
    # I tried to pass decorators in different orders,
    # but got no result.
    @staticmethod
    @lifesaver
    @gen.coroutine
    @lifesaver
    def dosomething1():
        raise Exception("Test error!")

    # My decorator works well
    # if it is used without gen.coroutine.
    @staticmethod
    @gen.coroutine
    def dosomething2():
        SomeClass.dosomething3()

    @staticmethod
    @lifesaver
    def dosomething3():
        raise Exception("Test error!")

I understand, that Tornado uses raise Return(...) approach which is probably based on Exceptions, and maybe it somehow blocks try-catches of other decorators... So, how can I used my decorator to handle Exceptions with Tornado coroutines?
The answer
Thanks to Martijn Pieters, I got this code working:
def lifesaver(func):
    def silenceit(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except (gen.Return, StopIteration):
            raise
        except Exception as ex:
            # collect info and format it
            res = ' ... '
            # writelog(res)
            print(res)

            raise gen.Return(b"")

    return silenceit

So, I only needed to specify Tornado Return. I tried to add @gen.coroutine decorator to silenceit function and use yield in it, but this leads to Future objects of Future objects and some other strange unpredictable behaviour.

A: You are decorating the output of gen.coroutine, because decorators are applied from bottom to top (as they are nested inside one another from top to bottom).
Rather than decorate the coroutine, decorate your function and apply the gen.coroutine decorator to that result:
@gen.coroutine
@lifesaver
def dosomething1():
    raise Exception("Test error!")

Your decorator can't really handle the output that a @gen.coroutine decorated function produces. Tornado relies on exceptions to communicate results (because in Python 2, generators can't use return to return results). You need to make sure you pass through the exceptions Tornado relies on. You also should re-wrap your wrapper function:
from tornado import gen

def lifesaver(func):
    @gen.coroutine
    def silenceit(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except (gen.Return, StopIteration):
            raise
        except Exception as ex:
            # collect info and format it
            res = ' ... '
            # writelog(res)
            print(res)
            raise gen.Return(b"")

    return silenceit

On exception, an empty Return() object is raised; adjust this as needed.
Do yourself a favour and don't use a class just put staticmethod functions in there. Just put those functions at the top level in the module. Classes are there to combine methods and shared state, not to create a namespace. Use modules to create namespaces instead.


text:
Q: Convert from seconds to specific format of minutes - Javascript For example:
I have 101.2914
and I want to obtain
1:41.291
I thought to substract the integer part of the number minus 60, but I can't because could be that final time would be 2:XX.XXX

A: ES6:
const string = '101.2914';
let [sec, milisec] = string.split('.');
sec = +sec;
milisec = milisec.slice(0, 3);

let mins = 0;
while(sec >= 60) {
    mins += 1;
    sec -= 60;
}

const result = `${mins}:${sec}.${milisec}`;

console.log(result);

Old version:
var string = '101.2914';
var array = string.split('.');
var sec = +array[0];
var milisec = array[1].slice(0, 3);

var mins = 0;
while(sec >= 60) {
    mins += 1;
    sec -= 60;
}

var result = mins + ':' + sec + '.' + milisec;

console.log(result);

A: Yo Can use a function like this as well. Here i am setting input inside the function but you can pass it while calling function.
$scope.secToMinute= function (input) {
    input = 101.2914;

    var min = Math.floor(input/ 60);
    var second = input - (min * 60);
    alert(min + ":" + second.toFixed(3));
};

A:
I hope this may help you.

var seconds = '101.2914';
var date = new Date(0,0,0);
date.setSeconds(seconds);
var result = date.getMinutes() +':'+date.getSeconds()+'.'+seconds.split('.')[1].slice(0,3);


text:
Q: Looking for guidance on CSS code for class I'm doing an assignment in my class with HTML and CSS. I'm having trouble getting the navigation for phone and tablet views to look like the attached image. I'm assuming this could be resolved toward the bottom of the CSS code? Also, my page looks very wide compared to the photos in all views. I'm very much a novice at this if it isn't obvious.

body {
  background-color: #b8dbed;
  font-family: Arial;
}

header {
  background-color: #000033;
  color: #ffffff;
  margin-left: auto;
  margin-right: auto;
  height: 120px;
  padding-top: 30px;
  padding-left: 3em;
  text-align: center;
}

nav {
  font-weight: bold;
  padding: 1.5em;
  font-size: 120%;
  float: left;
  width: 160px;
}

nav a {
  text-decoration: none;
}

h1 {
  margin-bottom: 0;
  font-family: Georgia;
  margin-top: 0;
  font-size: 3em;
  letter-spacing: 0.25em;
}

h2 {
  color: #3399cc;
  font-family: Georgia;
  text-shadow: 1px 1px 1px #cccccc;
}

h3 {
  font-family: Georgia;
  color: #000033;
}

dt {
  color: #000033;
}

.resort {
  color: #5c7fa3;
  font-weight: bold;
}

nav ul {
  margin: 0;
  padding-left: 0;
  font-size: 1.2em;
}

main ul {
  list-style-image: url(marker.gif);
}

footer {
  font-size: 75%;
  font-style: italic;
  text-align: center;
  font-family: Georgia;
  padding: 20px;
  margin-left: 190px;
  background: #ffffff;
}

#contact {
  font-size: 90%;
}

#wrapper {
  width: 80%;
  margin-left: auto;
  margin-right: auto;
  max-width: 960px;
  min-width: 2048px;
  background: #90c7e3;
  box-shadow: 3px 3px 3px #333333;
  border: 1px solid #000033;
  background-image: linear-gradient(to bottom, #ffffff, #90c7e3);
}

main {
  padding-top: 1px;
  padding-right: 20px;
  padding-bottom: 20px;
  padding-left: 20px;
  display: block;
  background: #ffffff;
  margin-left: 190px;
  padding-left: 30px;
}

#homehero {
  height: 300px;
  background-image: url(coast2.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-left: 190px;
}

#trailhero {
  height: 300px;
  background-image: url(trail.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-left: 190px;
}

#yurthero {
  height: 300px;
  background-image: url(yurt.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-left: 190px;
}

* {
  box-sizing: border-box;
}

a:link {
  color: #5c7fa3;
}

a:visited {
  color: #344873;
}

a:hover {
  color: #a52a2a;
}

header,
main,
nav,
footer,
figure,
figcaption,
aside,
section,
article {
  display: block;
}

#mobile {
  display: none;
}

#desktop {
  display: inline;
}

@media only screen and (max-width: 64em) {
  body {
    background: #ffffff;
  }
  #wrapper {
    min-width: 0;
    width: auto;
    box-shadow: none;
    border: none;
  }
  header {
    padding-top: 0.5em;
    padding-bottom: 0.5em;
    padding-left: 0;
    height: auto;
  }
  h1 {
    letter-spacing: 0.1em;
  }
  main {
    margin-left: 0;
  }
  nav {
    float: none;
    width: auto;
    text-align: center;
    padding: 0.5em;
  }
  nav li {
    display: inline;
    padding-top: 0.25em;
    padding-bottom: 0.25em;
    padding-left: 0.75em;
    padding-right: 0.75em;
  }
  #homehero {
    margin-left: 0;
    height: 200px;
  }
  #yurthero {
    margin-left: 0;
    height: 200px;
  }
  #trailhero {
    margin-left: 0;
    height: 200px;
  }
  footer {
    margin-left: 0;
  }
}

@media only screen and (max-width: 37.5em) {
  main {
    padding-top: 0.1em;
    padding-bottom: 0.1em;
    padding-right: 1em;
    padding-left: 1em;
    font-size: 90%;
  }
  h1 {
    font-size: 2em;
  }
  nav {
    padding: 0;
  }
  nav li {
    display: block;
    margin: 0;
    border-bottom: 2px solid #330000;
  }
  nav a {
    display: block;
  }
  #homehero {
    background-image: none;
    height: 0;
  }
  #yurthero {
    background-image: none;
    height: 0;
  }
  #trailhero {
    background-image: none;
    height: 0;
  }
  #mobile {
    display: inline;
  }
  #desktop {
    display: none;
  }
}

 Pacific Trails Resort

    Home Yurts Activities Reservations

Enjoy Nature in Luxury

 Pacific Trails Resort offers a special lodging experience on the California North Coast with panoramic views of the Pacific Ocean. Your stay at Pacific Trails Resort includes a sumptuously appointed private yurt and a cooked-to-order
    breakfast each morning.

Unwind in the heated outdoor pool and whirlpool

Explore the coast on your own or join our guided tours

Relax in our lodge while enjoying complimentary appetizers and beverages

Savor nightly fine dining with an ocean view

    Pacific Trails Resort
 12010 Pacific Trails Road
 Zephyr, CA 95555

    888-555-5555

    888-555-5555

  Copyright © 2018 Pacific Trails Resort

  e.sween12@gmail.com

Any help or guidance would be appreciated.

A: You were almost there. I found a few typos in your HTML code like the  not having an opening tag, along with semantic issues such as not using
 elements in your unordered lists. After updating the HTML, all that was left was to provide a background color for the containers which hold the nav menu items at mobile and tablet viewport widths (ie the two media queries). I added a stock photo to the background-image for demonstration.
Lastly, updating your media queries to use px values instead of em. As @DCR mentioned, the em base value may change which in turn would cause your media queries to take affect at varying widths determined by the base value. Everything seems to match the desired output in the images you've included.
If you would like the page content to not exceed a certain viewport width, just specify max-width on the  and center it on the page with margin: 0 auto which creates 0 top/bottom margin and "auto" sized left/right margins to center the content. I also added a border and box-shadow to the body at "desktop size" so it matches your desired output.

body {
  background-color: #b8dbed;
  font-family: Arial;
  max-width: 100ch; /* vary this */
  margin: 0 auto 1rem auto;
  border: .1rem solid #333;
  box-shadow: 1px 2px 2px 0px #222;
}

header {
  background-color: #000033;
  color: #ffffff;
  margin-left: auto;
  margin-right: auto;
  height: 120px;
  padding-top: 30px;
  padding-left: 3em;
  text-align: center;
}

nav {
  font-weight: bold;
  padding: 1.5em;
  font-size: 120%;
  float: left;
  width: 160px;
}

nav a {
  text-decoration: none;
}

nav ul {
  list-style-type: none;
}

h1 {
  margin-bottom: 0;
  font-family: Georgia;
  margin-top: 0;
  font-size: 3em;
  letter-spacing: 0.25em;
}

h2 {
  color: #3399cc;
  font-family: Georgia;
  text-shadow: 1px 1px 1px #cccccc;
}

h3 {
  font-family: Georgia;
  color: #000033;
}

dt {
  color: #000033;
}

.resort {
  color: #5c7fa3;
  font-weight: bold;
}

nav ul {
  margin: 0;
  padding-left: 0;
  font-size: 1.2em;
}

main ul {
  list-style-image: url(marker.gif);
}

footer {
  font-size: 75%;
  font-style: italic;
  text-align: center;
  font-family: Georgia;
  padding: 20px;
  margin-left: 190px;
  background: #ffffff;
}

#contact {
  font-size: 90%;
}

#wrapper {
  width: 80%;
  margin-left: auto;
  margin-right: auto;
  max-width: 960px;
  min-width: 2048px;
  background: #90c7e3;
  box-shadow: 3px 3px 3px #333333;
  border: 1px solid #000033;
  background-image: linear-gradient(to bottom, #ffffff, #90c7e3);
}

main {
  padding-top: 1px;
  padding-right: 20px;
  padding-bottom: 20px;
  padding-left: 20px;
  display: block;
  background: #ffffff;
  margin-left: 190px;
  padding-left: 30px;
}

#homehero {
  height: 300px;
  background-image: url(https://www.visitcalifornia.com/sites/visitcalifornia.com/files/NC_DuncansCove_Seeff_1280x642_sized_downsized.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-left: 190px;
}

#trailhero {
  height: 300px;
  background-image: url(trail.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-left: 190px;
}

#yurthero {
  height: 300px;
  background-image: url(yurt.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-left: 190px;
}

* {
  box-sizing: border-box;
}

a:link {
  color: #5c7fa3;
}

a:visited {
  color: #344873;
}

a:hover {
  color: #a52a2a;
}

header,
main,
nav,
footer,
figure,
figcaption,
aside,
section,
article {
  display: block;
}

#mobile {
  display: none;
}

#desktop {
  display: inline;
}

@media only screen and (max-width: 1024px) {
  body {
    background: #ffffff;
    max-width: none;
    border: none;
    box-shadow: none;
  }
  #wrapper {
    min-width: 0;
    width: auto;
    box-shadow: none;
    border: none;
  }
  header {
    padding-top: 0.5em;
    padding-bottom: 0.5em;
    padding-left: 0;
    height: auto;
  }
  h1 {
    letter-spacing: 0.1em;
  }
  main {
    margin-left: 0;
  }
  nav {
    float: none;
    width: auto;
    text-align: center;
    padding: 0.5em;
    background: rgba(213, 244, 250, .4);
  }
  nav li {
    display: inline;
    padding-top: 0.25em;
    padding-bottom: 0.25em;
    padding-left: 0.75em;
    padding-right: 0.75em;
  }
  #homehero {
    margin-left: 0;
    height: 200px;
  }
  #yurthero {
    margin-left: 0;
    height: 200px;
  }
  #trailhero {
    margin-left: 0;
    height: 200px;
  }
  footer {
    margin-left: 0;
  }
}

@media only screen and (max-width: 600px) {
  body {
    box-shadow: none;
    border: none;
  }
  main {
    padding-top: 0.1em;
    padding-bottom: 0.1em;
    padding-right: 1em;
    padding-left: 1em;
    font-size: 90%;
  }
  h1 {
    font-size: 2em;
  }
  nav {
    padding: 0;
    background: rgba(213, 244, 250, .4);
  }
  nav li {
    display: block;
    margin: 0;
    border-bottom: 2px solid #330000;
  }
  nav a {
    display: block;
  }
  #homehero {
    background-image: none;
    height: 0;
  }
  #yurthero {
    background-image: none;
    height: 0;
  }
  #trailhero {
    background-image: none;
    height: 0;
  }
  #mobile {
    display: inline;
  }
  #desktop {
    display: none;
  }
}

 Pacific Trails Resort

Home

Yurts

Activities

Reservations

Enjoy Nature in Luxury

 Pacific Trails Resort offers a special lodging experience on the California North Coast with panoramic views of the Pacific Ocean. Your stay at Pacific Trails Resort includes a sumptuously appointed private yurt and a cooked-to-order
    breakfast each morning.

Unwind in the heated outdoor pool and whirlpool

Explore the coast on your own or join our guided tours

Relax in our lodge while enjoying complimentary appetizers and beverages

Savor nightly fine dining with an ocean view

    Pacific Trails Resort
 12010 Pacific Trails Road
 Zephyr, CA 95555

    888-555-5555

    888-555-5555

  Copyright © 2018 Pacific Trails Resort

  e.sween12@gmail.com


text:
Q: How do I setup MvvmCross in Xamarin Studio with Indie license on Windows? Is there a good straight forward setup for MVVMCross in Xamarin Studio that has an Indie license?

A: Yes, take your pick from Google:
I would recommend installing Nuget using the IDE Extensions on Xamarin Studio:
Xamarin Studio, Addin Manager, click Gallery tab, click Repostiory dropdown list and choose Manage then select the add-in from mrward.
Then either:

*

*Install MvvmCross - Hot Tuna Starter Pack on a blank PCL project to start working on core cross platform code from scratch (and install again on Android/iOS/Windows projects referencing the core project)

*Use NinjaCoder from Adrian Sudbury to generate cross platform projects out the box, or

*Follow Stuart Lodge's awesome blog with the N+1 tutorials with sample code that is (mostly if not all) compatible with Xamarin Studio found here


text:
Q: Constantly getting syntax error after subquery alias (happens with different queries) It's probably something I can't seem to understand with MySQL, but after wasting my day going through StackOverflow's related questions without fixing the issue, I decided to ask about it.
SELECT users.idUser, users.name, categoryName
FROM users
LEFT JOIN (
  SELECT `translation` as categoryName
  FROM localization,
       usercategories
  WHERE localization.`string` = usercategories.name
  AND usercategories.idUserCategory = users.idUserCategory
  )
  as Something
WHERE users.idUser != 1
ORDER BY users.name ASC

Whichever query I tried today that would include a subquery, I would get the same syntax error at pretty much the same place: right after the subquery's alias (in this case, Something).

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE users.idUser != 1 ORDER BY users.name ASC LIMIT 0, 30' at line 11

A: You could re-organize your query so that it does not need a sub-query. This would also allow you the benefit of adding more columns to the select from any of the tables. Also, it is more correct.
SELECT
    users.idUser,
    users.name,
    localization.`translation` as categoryName
FROM users
LEFT JOIN usercategories ON usercategories.idUserCategory = users.idUserCategory
LEFT JOIN localization ON localization.`string`= usercategories.name
WHERE users.idUser <> 1
ORDER BY users.name ASC

A: This issue here is that you're missing the ON clause of your join. You need to select a condition to join the two tables together, like this:
SELECT stuff
FROM stuff
LEFT JOIN (other stuff)
ON stuff.something = otherstuff.something. // Add here.

A: You're JOIN criteria is non-ANSI and does not have an ON clause ... perhaps that is causing it? Try this, a bit more optimized:
SELECT Usr.idUser AS idUser
  ,Usr.name AS name
  ,UsrCat.translation AS categoryName
FROM users AS Usr
LEFT OUTER JOIN usercategories AS UsrCat
  ON UsrCat.idUserCategory = Usr.idUserCategory
LEFT OUTER JOIN localization AS Lcl
  ON Lcl.string = UsrCat.name
WHERE Usr.idUser <> 1
ORDER BY Usr.name ASC

No need for subquery, should be pretty performant.


text:
Q: How can I resolve the following xmlns MSBuild error? I have a .NET Standard 4.7.2 solution that builds locally just fine. On trying to run a CI build in TFS 2015 sp3, I am seeing the following error. I tried the prescribed change, adding the xmlns value to each project in the solution, but the error still occurs. How can I resolve this, please?
The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the <Project> element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.

Thanks much.

A: You need to make sure the solution can be built successfully on the build agent machine. Please login your build agent machine, navigate to the agent working folder, and build the project with msbuild command line to see how's the result.
Also, make sure your local environment the same as the build agent machine, like VS version and msbuild version. You could clean the agent working folder and have another try.

A: Apparently, the Microsoft.Net.Compilers v3.8.0 nuget package got added to the solution (not sure how...) and was overriding the TFS MSBuild agent. I removed the package and things are building again


text:
Q: recharge the activity after back key I have 3 activity
-scelta
-checkin
-instarghe
form scelta and checkin i can go to instarghe.
I want that when i go to instarghe from checkin,if I use the back button,the checkin activity will be re-excecute.
Example:
checkin-->instarghe-->back button-->I execute for the second time checkin
scelta-->instarghe-->back button-->normally return to scelta
How can I do?
I write this code:
protected void onRestart(){
    //popolamento dello spinnero
    String risposta=postTarghe();
    Spinner spinner = (Spinner) findViewById(R.id.spnTarghe);
    final String targhe[]=risposta.split("/");
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            targhe
            );
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int position,long id) {
            sTarga=targhe[position];
            Log.d(TAG,"questa è la posizione selezionata: "+position);
            Log.d(TAG,"questa è la targa: "+sTarga);
        }
        public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
        }
    });
};

but when I try,the app crashs.
this is the logcat:

java.lang.RuntimeException: Unable to resume activity {com.homelinux.agnese/com.homelinux.agnese.entrata}: android.app.SuperNotCalledException: Activity {com.homelinux.agnese/com.homelinux.agnese.entrata} did not call through to super.onRestart()
   Caused by: android.app.SuperNotCalledException: Activity {com.homelinux.agnese/com.homelinux.agnese.entrata} did not call through to super.onRestart()

A: first: please post your Code inside your Question, and not as an answer!
Second:
protected void onRestart(){
    /****************
    * You forgot following line
    ****************/
    super.onRestart();
    /***************/
    //popolamento dello spinnero
    String risposta=postTarghe();
    Spinner spinner = (Spinner) findViewById(R.id.spnTarghe);
    final String targhe[]=risposta.split("/");
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            targhe
            );
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int position,long id) {
            sTarga=targhe[position];
            Log.d(TAG,"questa è la posizione selezionata: "+position);
            Log.d(TAG,"questa è la targa: "+sTarga);
        }
        public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
        }
    });
};

A: use onRestart() in checkin & use re-executing logic here. probably this will solve your problem.
call superclass onRestart() inside your overridden version of onRestart()


text:
Q: Save eventually on PFObject with PFFile (Parse Local Datastore)? Goal
I am trying to save  a PFObject that has a PFFile as an attribute. I am using the new Local Datastore for iOS, so I would like to save this PFObject with the saveEventually() method.
The Problem
The problem I am encountering is that the saveEventually() method doesn't seem to like saving the PFFiles. I tried to saveEventually() my object without any PFFile attached, and that worked fine. As soon as my PFFile was reattached, Xcode threw a couple of breakpoint notices (errors?) but did not terminate the app, and it appears as though all went well - however a check on the Parse Data Browser confirms that the save did not go through.  Prior to the Local Datastore feature I don't believe this save would have been possible - it would have thrown the "Unable to saveEventually a PFObject with a relation to a new, unsaved PFFile." error. It seems as though the Local Datastore feature has fixed this, as it states in the iOS Local Datastore docs:

"Pinning a PFObject is recursive, just like saving, so any objects
  that are pointed to by the one you are pinning will also be pinned.
  When an object is pinned, every time you update it by fetching or
  saving new data, the copy in the local datastore will be updated
  automatically. You don't need to worry about it at all."

I have updated the SDK to the latest version (v1.6.2). Any ideas?

A: PFFiles still don't support saveEventually see here
That page was last updated : 2015-01-23
You could pinInBackgroundWithBlock and if successful save the PFFile to a temporary folder in you app bundle and delete it when necessary or unpinned

A: I just released a class which allows to saveEventually a PFFile.
You can find it here :
/*
     This example uses an UIImage, but this works with any file writable as NSData
     We begin by writing this image in our tmp directory with an uuid as name.
 */
UIImage *nyancat = [UIImage imageNamed:@"nyancat.jpg"];
NSData *imageData = UIImageJPEGRepresentation(nyancat, 0.5);

NSString *filename = [[NSUUID UUID] UUIDString];
NSURL *fileUrl = [PFFileEventuallySaver fileURLInTmpWithName:filename];

[imageData writeToURL:fileUrl atomically:YES];

 /*
     We create a PFObject (you can pass an array to below function if you need your file to be saved on several objects). If upload works on first time, do what you want with your file, like linking it on your PFobject.

     If saving fails, it'll be retried as soon as network is available, on this session or nexts launches of app.
     In that case, the pointer at key kPFFILE_MANAGER_OBJECT_FILE_KEY of your PFFObject will be set with the PFFile, then saved eventually within PFFileEventuallySaver
 */
PFObject *object = [PFObject objectWithClassName:kPFFILE_CONTAINER_OBJECT_CLASSNAME];

[[PFFileEventuallySaver getInstance] trySaveobjectAtURL:fileUrl associatedObjects:@[object] withBlock:^(PFFile *file, NSError *error) {
if(!error)
{
    NSLog(@"[First try, network is fine] File saved, saving PFObject");

    object[kPFFILE_MANAGER_OBJECT_FILE_KEY] = file;
    [object saveEventually];

    NSLog(@"Try again disabling your network connection");
}
else
{
    NSLog(@"No network, connect back your wifi, or relaunch app. Your file will be sent");
}
} progressBlock:^(int percentDone) {
    NSLog(@"[First try, network is fine] Sending file %d/100%%", percentDone);
}];