text:
Q: Some Unicode characters successfully displayed, but some are not I am trying to display some non-latin characters, such as ɩ LATIN SMALL LETTER IOTA (U+0269), ʋ LATIN SMALL LETTER V WITH HOOK (U+028B), and ɔ LATIN SMALL LETTER OPEN O (U+254).
I tried almost every way I could find but none of them work. A subset of potentially crucial things I tried which did not work:

*

*all compilers available on Overleaf: pdfLatex, Latex, XeLatex, and LuaLatex

*\usepackage[utf8]{inputenc} and \usepackage[utf8x]{inputenc} (I know utf8x should be avoided, but with utf8x some characters are able to display.)

*\usepackage[T1]{fontenc} , \usepackage[T5]{fontenc}, \usepackage[T1,T4]{fontenc}
Minimal Example to demonstrate the issue
\documentclass[11pt]{article}
\usepackage{times}
\usepackage{tipa}
\usepackage{textcomp}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}

\begin{document}
line1: \unichar{"0111}, \unichar{"00F6} \\
line2: đ, ö \\
line3: \unichar{"0254}, \unichar{"0269}, \unichar{"028B} \\
line4: ɔ, ɩ, ʋ
\end{document}

The output

I have read the Unicode documentations provided by Overleaf (https://www.overleaf.com/learn/latex/Articles/Unicode%2C_UTF-8_and_multilingual_text%3A_An_introduction,  https://www.overleaf.com/learn/latex/Multilingual_typesetting_on_Overleaf_using_babel_and_fontspec) and some Unicode documentation pages to obtain some basic knowledge about Unicode.
As I was looking for answers, some solutions have to do with specifying languages for the package babel. However, my paper will include scripts from many languages (can be tens of them) and they are mostly under-represented languages (could be Indigenous and/or endangered) so they are lack of academic linguistic studies, and I do not even know which scripts they are using. I was not even sure if there is anything to do with the script/language.
I went with \unichar{"xxxx} solution because the ^^^^xxxx syntax does not work. With \unichar{"xxxx} syntax, some characters disaply fine, e.g. \unichar{"0111}(đ, latin small letter d with stroke) and \unichar{"00F6}(ö, latin small letter o with diaeresis). However, some are not, e.g. \unichar{"0254} (ɔ,   latin small letter open o), \unichar{"0269} (ɩ, latin small letter iota), \unichar{"028B}(ʋ, latin small letter v with hook).
I am wondering why some characters can be displayed and some can not, despite the fact that they are all specified in Unicode in hexadecimal notation in an identical LaTeX environment using the same command (\unichar{}).
Also, is there a way to display those characters which currently cannot be rendered?

A: Don't use utf8x.
I tried typesetting
ɩ, ʋ, and ɔ

with your preamble (removing utf8x) and I got
! LaTeX Error: Unicode character ɩ (U+0269)
               not set up for use with LaTeX.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.20 ɩ
       , ʋ, and ɔ
?

! LaTeX Error: Unicode character ʋ (U+028B)
               not set up for use with LaTeX.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.20 ɩ, ʋ
           , and ɔ
?

! LaTeX Error: Unicode character ɔ (U+0254)
               not set up for use with LaTeX.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.20 ɩ, ʋ, and ɔ

I went to the manual of tipa and found them together with the commands that produce the characters, so I was able add suitable \DeclareUnicodeCharacter instructions for them. Add the others you need with the same method.
\documentclass[11pt]{article}
\usepackage[T1]{fontenc}

%\usepackage{acl} % where is it?
\usepackage{times}
\usepackage{tipa}

%\usepackage{latexsym} % obsolete
%\usepackage{graphicx} % not needed for the example
%\usepackage{multirow} % not needed for the example
%\usepackage{textcomp} % no longer needed
%\usepackage[utf8x]{inputenc} % don't use this
%\usepackage{microtype} % not needed for the example
%\usepackage{bbm} % not needed for the example
%\usepackage{amsmath} % not needed for the example
%\usepackage{csquotes} % not needed for the example
%\usepackage{numprint} % not needed for the example

% do here the declarations you need
\DeclareUnicodeCharacter{0269}{\textiota} % ɩ
\DeclareUnicodeCharacter{0254}{\textopeno} % ɔ
\DeclareUnicodeCharacter{028B}{\textscriptv} % ʋ

\begin{document}

ɩ, ʋ, and ɔ

\end{document}

I had to comment out \usepackage{acl} because you didn't tell where to find it. I commented out other packages not specific for the problem, but please look for the comments I added.

A: Use the encoding utf8 (or whatever) do not mean that any font used will have a glyph for every encoded character. In fact, there are so many, that this almost never happen (maybe except with Unifont, that look horribly pixelated). Some fonts only have the Latin alphabet in capitals or so, while others have thousands of glyphs, but not all the uft8 characters.
So, a first step to deal with bizarre characters could be to search a good font containing most-all "rare" characters that you will need. Using xelatex and lualatex you are not limited to TeX fonts, so there are many alternatives:

\documentclass{article}
\usepackage{fontspec}
\usepackage{tabto}\NumTabs{5}
\begin{document}
\obeylines
đ ö ɔ ɩ ʋ \tab ← not all printed (default)
{\setmainfont{GFS Didot} đ ö ɔ ɩ ʋ}     \tab ← Wrong font (Missing  characters)
{\setmainfont{FontAwesome} đ ö ɔ ɩ ʋ}   \tab ← FonAwesome is not for this ...
{\setmainfont{Unifont} đ ö ɔ ɩ ʋ}       \tab ← Unifont works, but ...
{\setmainfont{FreeSerif} đ ö ɔ ɩ ʋ}     \tab ← FreeSerif works
{\setmainfont{DejaVu Serif}  đ ö ɔ ɩ ʋ} \tab ← DejaVu Serif works
{\setmainfont{EB Garamond} đ ö ɔ ɩ ʋ}   \tab ← EB Garamond works
\end{document}


text:
Q: Set current multiple value in selectize JS I have problem in selectize JS when set current value is multiple value. I set from Ajax response in Json format, here is my code.
$(".rule_list").on("click",function(e) {
        e.preventDefault();
        $.ajax({
          url: 'getruledata,
          dataType: 'json'
        })
        .done(function(data){
          console.log(data);
          $selectz[0].selectize.setValue(data[0].control_country);
        })
      });

Here my HTML code
<select id="select-country" placeholder="Pick a countries..."></select>

And here code for selectize
var $selectz = $('#select-country').selectize({
        maxItems: null,
        valueField: 'iso',
        labelField: 'nice_name',
        searchField: 'nice_name',
        options: {!! $country !!},
        create: false,
      });

Here my value format from Json response
[{"id":2,"name":"XSA 2","user_id":"3","control_device":"Mobile","control_country":"US,CA","offer_id":"2","rule_id":"1","status":"2"}]

I'm stuck in this steps, if "control_country":"US,CA" (multiple value) not working when set current value to input form, but if "control_country":"US" (single value) working correctly

A: You can set multiple values to selectize like this:
$selectz[0].selectize.setValue([optionid,optionid]);

So in your example it should be:
$selectz[0].selectize.setValue(["US","CA"]);

A: You need to use the method addItem(value, silent). As explained in the docs, addItem "selects" items, where passing true to "silent" will apply the change to the original input.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cakephp using Cache in Component I am using Cakephp 2.3 ,  i want to perform lots of common calculation in my several controllers. so i write those functions in my appcontroller and i cached some datas..
but what happens is my appController will become fatty.. so i create some component to perform these actions.. i dont know my approach is right or not..? please suggest..

*

*i want to use cache in my component,  i tried this code. but nothing is cached..
    public $helpers =array('Cache');

and
     $result = Cache::read('fm_data', 'long');
       if (!$result) {
       $result =
 $this->TFmStation->find('all',array('contain'=>array('TLocation',
            'TLanguage','TMediaOrg','TContactPerson',
                    'TAddress','TFmProgram'=>array('TTargetGroup'))));
                       Cache::write('fm_data', $result, 'long');
                }
 return $result;

*

*please help me to how to use cache in component

*how to effectively use component class in cakephp in the case of more common functions in the application.. when i write these functions in appController it load all the functions so according to memory prespective, how to effectively use component

A: Model TFmStation is best place to have the above logic. Components are there for generic functionality like UploadComponent, EmailComponent, RecaptchaComponent etc. If your logic part have something to do with model, then it should go into that model.
A Model can be called from AppController.php in a similar fashion as you calling your Component.


text:
Q: Variable parameter function with minimum parameter
Possible Duplicates:
C++ preprocessor __VA_ARGS__ number of arguments
How to count the number of arguments passed to a function that accepts a variable number of arguments?

To learn variable parameter function, I write a demo:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>

int foo(int n, int m, ...);

int
main (int argc, char *argv[])
{
    int n = 10;
    int m = 15;
    int p = 20;
    //foo (n, m);
    foo(n, m, 20);

    return EXIT_SUCCESS;
}

int foo (int n, int m, ...)
{
    va_list ap;
    int p;
    char *str;

    va_start (ap, m);
    p = va_arg (ap, int);
    n = m + p;
    printf ("%d.\n", n);
    va_end (ap);
    return 0;
}

I want to know how to deal with the function if it has only two parameters. (For this demo, if only n and m, after running foo, I want to get result: n = n+m.)

A: For every variable argument ('variadic') function, there has to be a way for the function to know how many arguments it must process.  There are various ways of handling that.

*

*The printf() and scanf() families of functions use the format string to determine how many arguments are passed to the function.

*The POSIX open() function looks at the options in the second argument to know whether there is a third argument.

*The POSIX execl() function scans until it comes across a null pointer argument.

*You can pass an explicit count of the number of arguments to process (see example by Fei Jiang).

All these methods work.  The open() mechanism is the least general and most peculiar (arising mainly from historical quirks).
But one such mechanism must be used.  The called function must be able to tell (somehow) when it has finished processing the variable section of its argument list.
Unless you are relaying the variable length argument list to other functions (e.g. you use vsnprintf() to format a string with the variable arguments passed to the function), your variadic function body will need a loop in it to process the variable number of arguments.  Your function is missing that loop.

A: At runtime, there is no way to know the actual number of additional parameters from va_list. Hence there should be another way to deduce this number, e.g. from previous parameters or from some end-of-list convention (as in, give any number of pointers followed by NULL). Consider printf, where the format string determines how many parameters (of what types) to expect in the va_list part.
As long as you take this into account, there would be nothing special about the minimum number of parameters (that is, empty va_list). Just don't pop anything from va_list when you know there is nothing to expect.

A: I do not understand what you want 'foo' to do, but typically foo should have a loop in it, and also foo should been told how many arguments it has been given when called, or rather, when the loop ends. printf knows this by %d %s %f ... in the first char* pattern parameter
For example, if we want to write a function that returns the sum of several integers, we can implement like this
#include <stdio.h>
#include <stdarg.h>

int int_sum(int count, ...) {
    int sum = 0, i;
    va_list ap;
    va_start(ap, count);
    for (i = 0; i < count; ++i) {
        sum += va_arg(ap, int);
    }
    va_end(ap);
    return sum;
}

int main() {
    printf("%d\n", int_sum(5, 1, 2, 3, 4, 5));
    return 0;
}

A: I am not sure if I understood the question, but if you have only a single argument in a varlist function, e.g. foo (int n,...), followed by ..., then you can pass the first argument of foo (n in our case) in va_start(), and it will always work.
int foo (int n,  ...);
int
main (int argc, char *argv[])
{
    int n = 10;
    int m = 15;
    int p = 20;

    foo (n, m);
    //foo (n, m, 20);

    return EXIT_SUCCESS;
}

int foo (int n,  ...)
{
    va_list ap;
    int p;
    char *str;

    va_start (ap, n);
    p = va_arg (ap, int);
    n = n + p;
    printf ("%d.\n", n);
    va_end (ap);
    return 0;
}


text:
Q: Error in User defined size for array in c *I am taking the size of array from user, the program runs perfectly when i declare int arr[n];  below the scanf in main but, it when i run following code is behaves differently each time, sometimes take more values, some times shows bus error. Even the value of n changes sometimes. *
//Code
#include <stdio.h>

void read_array(int arr[], int *n);
void print_array(int arr[], int *n);

int main() {
    int n;

    int arr[] = {};

    printf("Enter array length ");
    scanf("%d", &n);
    printf("\nmain elements %d", n);

    read_array(arr, &n);

    printf("\nElements main %d", n);
    print_array(arr, &n);

    return 0;
}

void read_array(int arr[], int *n) {
    int i;

    printf("\n Elements R_A %d", *n);
    printf("\nEnter elements");

    for (i = 0; i < *n; i++) scanf("%d", &arr[i]);
}

void print_array(int arr[], int *n) {
    int i;

    printf("\n");

    for (i = 0; i < *n; i++) printf("%d ", arr[i]);

    printf("\n Elements P_A %d", *n);
}

A: When an array is declared without an explicit size, it size is taken to be the number of elements it is initialized with.  So This:
int arr[]={};

Declares an array of size 0 which is invalid, and attempting to use it triggers undefined behavior.

A: int arr[] = {}; is a zero-length array (not supported by the standard) and you access it out of bounds.
If your compiler supports VLAs (variable length arrays), you could use one of those instead.
Example:
#include <stdio.h>

void read_array(int arr[], int *n);
void print_array(int arr[], int n); // no need to send in a pointer to n

int main() {
    int n;

    printf("Enter array length ");
    if (scanf("%d", &n) != 1 || n < 1) return 1; // check that scanf succeeded
    printf("\nmain elements %d", n);

    int arr[n];                                  // a VLA of n elements

    read_array(arr, &n);

    printf("\nElements main %d", n);
    print_array(arr, n);

    return 0;
}

void read_array(int arr[], int *n) {
    printf("\n Elements R_A %d", *n);
    printf("\nEnter elements");

    int i;
    for (i = 0; i < *n; i++) {
        if (scanf("%d", &arr[i]) != 1) break; // check that scanf succeeded
    }
    *n = i;               // store the number of elements successfully read
}

void print_array(int arr[], int n) {
    int i;

    printf("\n");

    for (i = 0; i < n; i++) printf("%d ", arr[i]);

    printf("\n Elements P_A %d", n);
}


text:
Q: Index out of range when creating new combined slice of structs from 3 individual slices (one slice for each struct property) I have a struct like this:
type Headers struct {
    header            string
    valueFromCalculation    string
    value            float64
}

I need have three slices with the values for each of these:
var headerLabels []string
var values []float64
var valueFromCalculation []string

[January February March April May June July August September TOTAL]
[175 167 148 142 125 114 130 120 30 1151]
[15% 15% 13% 12% 11% 10% 11% 10% 3%]

Now I want to create a new slice of Headers by combining these. There is one issue, that I believe i'm solving - the length of the valueFromCalcuation is 1 less than the rest of the slices
To create the new slice I want to do this:
sliceOfHeaders := []*Headers{}

for i := 0; i <= len(headerLabels); i++ {

headerEntry := new(Headers)

headerEntry.header = headerLabels[i]
headerEntry.value = values[i]

if i == len(headerLabels) {
    headerEntry.valueFromCalculation = ""
} else {
    headerEntry.valueFromCalculation = valueFromCalculation[i]
}

sliceOfHeaders = append(sliceOfHeaders, headerEntry)
}

It is throwing the below error:
"panic: runtime error: index out of range"
How can this be?
I'm accounting for the issue of the index with the valueFromCalculation length being one less than the other struct properties
Here you can see output from before I want to start my loop:
header --> [January February March April May June July August September TOTAL]
value --> [175 167 148 142 125 114 130 120 30 1151]
valueFromCalculation --> [15% 15% 13% 12% 11% 10% 11% 10% 3%]
header length --> 10
value length --> 10
valueFromCalculation length --> 9

Please can someone help me here? I can't see what i'm doing wrong
I'm accounting for the length of the 3rd property being 1 less than the rest

A: It appears you are looping one index too long on headerLabels.
Try changing
i <= len(headerLabels) to i < len(headerLabels)
And
if i == len(headerLabels) to if i == len(headerLabels) - 1


text:
Q: How to copy table row with dropdownlist in with jQuery I have a table and I want to clone the last line of it after the Add New link is pressed. It works completely fine when I have only TextBoxes in my rows but it doesn't when there's a dropdown. Please help me to modify the jquery code.
Here's the code of the table:

Add New

                        Item
                        Cost

                    @if (Model != null && Model.Count > 0)
                    {
                        int j = 0;
                        foreach (var i in Model)
                        {

                                @Html.DropDownListFor(a => a[j].fk_purchase_id, (SelectList)ViewBag.fk_purchase_id, null, htmlAttributes: new { @class = "form-control"})
                                @Html.TextBoxFor(a => a[j].cost, htmlAttributes: new { @class = "form-control" })

                                    @if (j > 0)
                                    {
                                        Remove
                                    }

                            j++;
                        }
                    }

And here's the code that needs some improvement:

I tried to modify this line whith changing input to select, but it didnt help

var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);

A: First add tbody in your table like:

                Item
                Cost

            @if (Model != null && Model.Count > 0)
            {
                int j = 0;
                foreach (var i in Model)
                {

                        @Html.DropDownListFor(a => a[j].fk_purchase_id, (SelectList)ViewBag.fk_purchase_id, null, htmlAttributes: new { @class = "form-control"})
                        @Html.TextBoxFor(a => a[j].cost, htmlAttributes: new { @class = "form-control" })

                            @if (j > 0)
                            {
                                Remove
                            }

                    j++;
                }
            }

And your script is:


text:
Q: How can I set min max selectable time for Kendo Datetimepicker? I tried to use Kendo Datetimepicker's configuration to set min time starts at 09:00 AM.
like below:
    $("#txtAppt_Date").kendoDateTimePicker({
                    format: 'ddd M/d/yyyy h:mm tt',
                    min: new Date(2017, 0, 1, 9, 0, 0)
     });

But I am only allow to set 2017-01-01's time only. Not work for 2017-01-02 or any other dates.
I want to have range between 09:00 AM to 11:00 PM for this Kendo Datetimepicker.
Please help.
Thanks.
Update
This question is solved: I referenced Setting DateTimePicker to show specific time range e.g. working hours only

A: You can set min and max as follows:
<input id="datetimepicker" />
<script>
$("#datetimepicker").kendoDateTimePicker({
    value: new Date(2011, 0, 1, 9, 0, 0),
    min: new Date(2011, 0, 1, 9, 0, 0),
    max: new Date(2011, 0, 1, 23, 0, 0)
});
</script>

Pay attention that you should provide a value within the range of min and max.
See the embedded links above for more information.
Thanks to @Erik, here's a demo fiddle.
UPDATE
If what you want is to restrict the time 9-23 across multiple days, then there's a good answer here that demos it here


text:
Q: Login is not working I am trying to make a login application so you can view grades/email teachers/etc.
and I can do all that but I CAN NOT get the login to work for the life of me.
Every time I try I get:

Could not retrieve user_id from the session. User timed out.
  Blockquote

I have no idea what's wrong with my code and why I can't login.
Someone please help me. Thank you.
Code of the main "Login":
public class GradePortalActivity extends Activity {
    private final static String SITE = "http://dcps.mygradeportal.com/";
    private TextView usernameField, passwordField;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MySoup.setSite(SITE);
        usernameField = (TextView) this.findViewById(R.id.usernameField);
        passwordField = (TextView) this.findViewById(R.id.passwordField);
    }

    public void login(View v) {
        if (usernameField.length() > 0 && passwordField.length() > 0)
            new Login().execute(new String[] { usernameField.getText().toString().trim(), passwordField.getText().toString() });
        else {
            Toast.makeText(this, "Fill out login form", Toast.LENGTH_LONG).show();
        }
    }

    private class Login extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            lockScreenRotation();
            dialog = new ProgressDialog(GradePortalActivity.this);
            dialog.setIndeterminate(true);
            dialog.setMessage("Logging in...");
            dialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            String username = params[0];
            String password = params[1];
            try {
                MySoup.login(username, password);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean status) {
            dialog.dismiss();
            if (status == true) {
                Toast.makeText(GradePortalActivity.this, "Logged in", Toast.LENGTH_LONG).show();
                new Test().execute();
            }
            if (status == false) {
                Toast.makeText(GradePortalActivity.this, "Log in failed", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class Test extends AsyncTask<String, Void, String> {
        private ProgressDialog dialog;

        @Override
        protected String doInBackground(String... params) {
            String s = MySoup.inputStreamToString(MySoup.scrape("http://dcps.mygradeportal.com/homepage.aspx"));
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            Toast.makeText(GradePortalActivity.this, s, Toast.LENGTH_LONG).show();
        }
    }

    private void lockScreenRotation() {
        switch (this.getResources().getConfiguration().orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            break;
        case Configuration.ORIENTATION_LANDSCAPE:
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            break;
        }
    }

    private void unlockScreenRotation() {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }
}

Code of "MYSOUP" (backbone of the application):
public class MySoup {

    /** The http client. */
    private static DefaultHttpClient httpClient = getHttpClient();

    /** The cookies. */
    private static List<Cookie> cookies;

    /** The http params. */
    private static HttpParams httpParams = httpClient.getParams();

    /** The username. */
    private static String username;

    /** The SITE. */
    private static String SITE;

    /** The httpget. */
    private static HttpGet httpget;

    /** The response. */
    private static HttpResponse response;

    /** The entity. */
    private static HttpEntity entity;

    /** The httpost. */
    private static HttpPost httpost;

    public static void setSite(String s) {
        if (!s.endsWith("/")) {
            s = s + "/";
        }
        if (!s.startsWith("http://") || s.startsWith("https://")) {
            s = "http://" + s;
        }
        SITE = s;
    }

    /**
     * Gets the site.
     *
     * @return the site
     */
    public static String getSite() {
        return SITE;

    }

    /**
     * Gets the http client.
     *
     * @return the http client
     */
    private static DefaultHttpClient getHttpClient() {
        DefaultHttpClient client = new DefaultHttpClient();
        ClientConnectionManager mgr = client.getConnectionManager();
        HttpParams params = client.getParams();

        client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
        return client;
    }

    /**
     * Gets the session id.
     *
     * @return the session id
     */
    public static String getSessionId() {
        return cookies.get(0).getValue();
    }

    /**
     * Gets the cookies.
     *
     * @return the cookies
     */
    public static List<Cookie> getCookies() {
        return cookies;
    }

    /**
     * Checks if is logged in.
     *
     * @return true, if is logged in
     */
    public static boolean isLoggedIn() {
        if ((cookies != null) && !cookies.isEmpty())
            return true;
        else
            return false;
    }

    /**
     * Login.
     *
     * @param url
     *            the url
     * @param username
     *            the username
     * @param password
     *            the password
     * @throws CouldNotLoadException
     *             the could not load exception
     */
    public static void login(String username, String password) throws Exception {
        String url = SITE;

        try {
            httpget = new HttpGet(url);
            response = httpClient.execute(httpget);
            entity = response.getEntity();

            httpost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("userName", username));
            nvps.add(new BasicNameValuePair("password", password));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            response = httpClient.execute(httpost);
            entity = response.getEntity();
            if (entity != null) {
            entity.consumeContent();
            cookies = httpClient.getCookieStore().getCookies();
            }} catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Could not login");
            }

            }

    /**
     * Scrape.
     *
     * @param url
     *            the url
     * @return the input stream
     */
    public static InputStream scrape(String url) {
        httpget = new HttpGet(url);
        response = null;
        try {
            response = httpClient.execute(httpget);
            entity = response.getEntity();
            InputStream s = entity.getContent();
            System.err.println("encoding " + entity.getContentEncoding());
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * Input stream to string.
     *
     * @param is
     *            the is
     * @return the string
     */
    public static String inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return total.toString();
    }

    /**
     * Press link.
     *
     * @param url
     *            the url
     */
    public static void pressLink(String url) {
        url = SITE + url;
        httpget = new HttpGet(url);
        response = null;
        try {
            response = httpClient.execute(httpget);
            response.getEntity().consumeContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Gets the username.
     *
     * @return the username
     */
    public static String getUsername() {
        return username;
    }

    /**
     * Sets the session id.
     *
     * @param sessionId
     *            the new session id
     */
    public static void setSessionId(String sessionId) {
        Cookie cookie = new BasicClientCookie("", sessionId);
        CookieStore cs = new BasicCookieStore();
        cs.addCookie(cookie);
        httpClient.setCookieStore(cs);
        cookies = httpClient.getCookieStore().getCookies();
    }

}

A: The "error":
Could not retrieve user_id from the session. User timed out.

Is being generated from this line:
String s = MySoup.inputStreamToString(MySoup.scrape("http://dcps.mygradeportal.com/homepage.aspx"));

If you browse to http://dcps.mygradeportal.com/homepage.aspx, you'll see that your server is generating the following error:

Server Error in '/' Application.
Could not retrieve user_id from the session. User timed out
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: OnCourse.Core.SWSException: Could not retrieve
  user_id from the session. User timed out
etc...

So what I suspect is happening is that you're supposed to pass in a few POST parameters when scraping http://dcps.mygradeportal.com/homepage.aspx, which you're not doing. One of those parameters is probably the elusive user_id.
Keep in mind I can't tell you this for sure because I don't know how the gradeportal service works, but this should help you troubleshoot your problem.


text:
Q: LoadError: InitError: While Precompiling in new Environment I wanted to start using dedicated environments for all my julia projects, but activating the new environment and using packages (eg. Plots.jl) results in Precompiling that fails with the following error:
 Activating environment at `~/Documents/baro/Project.toml`

julia> using Plots
[ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80]
ERROR: LoadError: InitError: could not load library "/home/marius/.julia/artifacts/08ab4b2de494e1d61e581ab1fbd610b0b4d1876f/lib/libavdevice.so"
libx264.so.157: cannot open shared object file: No such file or directory
Stacktrace:
 [1] dlopen(::String, ::UInt32; throw_error::Bool) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.4/Libdl/src/Libdl.jl:109
 [2] dlopen at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.4/Libdl/src/Libdl.jl:109 [inlined] (repeats 2 times)
 [3] __init__() at /home/marius/.julia/packages/FFMPEG_jll/tCUYA/src/wrappers/x86_64-linux-gnu.jl:231
 [4] _include_from_serialized(::String, ::Array{Any,1}) at ./loading.jl:697
 [5] _require_search_from_serialized(::Base.PkgId, ::String) at ./loading.jl:781
 [6] _require(::Base.PkgId) at ./loading.jl:1006
 [7] require(::Base.PkgId) at ./loading.jl:927
 [8] require(::Module, ::Symbol) at ./loading.jl:922
 [9] include(::Module, ::String) at ./Base.jl:377
 [10] top-level scope at none:2
 [11] eval at ./boot.jl:331 [inlined]
 [12] eval(::Expr) at ./client.jl:449
 [13] top-level scope at ./none:3
during initialization of module FFMPEG_jll
in expression starting at /home/marius/.julia/packages/FFMPEG/vocw2/src/FFMPEG.jl:3
ERROR: LoadError: Failed to precompile FFMPEG [c87230d0-a227-11e9-1b43-d7ebe4e7570a] to /home/marius/.julia/compiled/v1.4/FFMPEG/TGvga_eB360.ji.
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] compilecache(::Base.PkgId, ::String) at ./loading.jl:1272
 [3] _require(::Base.PkgId) at ./loading.jl:1029
 [4] require(::Base.PkgId) at ./loading.jl:927
 [5] require(::Module, ::Symbol) at ./loading.jl:922
 [6] include(::Module, ::String) at ./Base.jl:377
 [7] top-level scope at none:2
 [8] eval at ./boot.jl:331 [inlined]
 [9] eval(::Expr) at ./client.jl:449
 [10] top-level scope at ./none:3
in expression starting at /home/marius/.julia/packages/Plots/LWw1t/src/Plots.jl:15
ERROR: Failed to precompile Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80] to /home/marius/.julia/compiled/v1.4/Plots/ld3vC_eB360.ji.
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] compilecache(::Base.PkgId, ::String) at ./loading.jl:1272
 [3] _require(::Base.PkgId) at ./loading.jl:1029
 [4] require(::Base.PkgId) at ./loading.jl:927
 [5] require(::Module, ::Symbol) at ./loading.jl:922

This also happens for some other packages like ControlSystems.
The julia version is 1.4.2 but I was able to reproduce this error with 1.5.0 and on a different computer with 1.3.1 on it. Both systems are runnning Ubuntu 20.04 LTS.
What I tried so far was:

*

*Rebuilding the package Pkg.build()

*Check that the file supposed to load exists (it existed)

*Update libx264

*Deleting all packages in .julia folder and and reinstalling everything using Pkg.instantiate()
Any help to get the packages running will be greatly appreciated as I really like the idea of having dedicated environments for every project. Also on 1.3.1 even after switching to the default environment the error is still occuring.

A: The issue seems to lay in the FFMPEG package.
The following solved the issue for me:
Remove FFMPEG. Then delete the folder which is given in the error message. In your case: "/home/marius/.julia/artifacts/08ab4b2de494e1d61e581ab1fbd610b0b4d1876f/lib/libavdevice.so"
Then add FFPEG again which results in a change in the Manifest.toml which does not happen if you just remove FFMPEG:
Updating `~/.julia/environments/v1.3/Manifest.toml`
  [1270edf5] ↓ x264_jll v2020.7.14+0 ⇒ v2019.5.25+2

Try: using FFMPEG, Plots.
I was able to precompile Plots then.


text:
Q: Unity Script Import Settings define default variable values I'm not sure how else to word this question. so I will post screenshots of my problem.
How to I make
[SerializeField] private Sprite[] m_Sprites;
show up in the inspector here

I have tried public Sprite[] Sprites; and private Sprite[] m_Sprites as well with no effect, I've seen variables appear there but I cannot seem to figure it out now that I need it. After Further Attempts I have found that a public Sprite Sprite; appears however I require it to be an array of Sprites. I also tried creating a holder  class and defining the array inside there and it still doesn't appear.

A: The only field types allowing default references are fields of a type derived from UnityEngine.Object
... a Sprite[] is an array and does not inhertit from UnityEngine.Object.

As mentioned before you could use a ScriptableObject wrapper class such as e.g.
// this attribute adds an entry to the Asset context menu Add->SpriteCotnainer
[CreateAssetMenu]
public class SpriteContainer : ScriptableObject
{
    public Sprite[] sprites;
}

then in your class use a
[SerializeField] private SpriteContainer spriteContainer;

which now is of type ScriptableObject which inherits from UnityEngine.Object so it should show up as default reference field.
So you would need to create this asset via right click on Assets → Add → SpriteContainer. Here you can reference all the sprites you need. Then drag this into the spriteContainer field of your script.

A: You have two options, either create a gameobject/prefab, add the script to it - and then it will appear.
Or, if it's just a data object you need to access, you can make it a ScriptableObject and create an instance of it.
Either way, you will have to create an instance; you can't assign variables to scripts, only objects with the scripts attached.


text:
Q: Example for using Locust with Boto3 I am trying to use Locust together with Boto3 for load testing of S3, in particular for PutObject.
I found a tutorial and another github project, but both have been written for the older locustio package and seem incompatible with the current version locust 2.5.1.
https://medium.com/@allankp/populating-dashboards-with-boto3-and-locust-ff38b113349a
https://github.com/twosigma/locust-s3
I have made a short attempt at adapting this code to newer versions but this seems to require a good understanding of locust which I do not possess yet.
Does anyone have a simple beginner's example to share? Or would you rather recommend using the old locustio package or another tool altogether?
Many thanks.

A: Helped by this example in the official docs and Cyberwiz's answer, I created this bare-bones solution for my specific problem.
import time
import boto3
from locust import User, task, constant, events

class BotoClient:
    def __init__(self):
        self.s3_client = boto3.client(
            's3',
            aws_access_key_id="ACCESS_KEY",
            aws_secret_access_key="SECRET_KEY"
        )

    def send(self, f, bucket_name, object_name):

        request_meta = {
            "request_type": "upload file",
            "name": "S3",
            "start_time": time.time(),
            "response_length": 0,
            "response": None,
            "context": {},
            "exception": None,
        }
        start_perf_counter = time.perf_counter()

        try:
            self.s3_client.upload_fileobj(f, bucket_name, object_name)
        except Exception as e:
            request_meta['exception'] = e

        request_meta["response_time"] = (time.perf_counter() - start_perf_counter) * 1000

        events.request.fire(**request_meta)

class BotoUser(User):
    abstract = True

    def __init__(self, env):
        super().__init__(env)
        self.client = BotoClient()

    wait_time = constant(1)

class MyUser(BotoUser):

    wait_time = constant(1)

    @task
    def send_request(self):
        with open("FILE_NAME", 'rb') as f:
            self.client.send(f, "BUCKET_NAME", "OBJECT_NAME")

A: The changes needed to adapt the code to version 1+ of Locust are very small.
Quoting the documentation changelog:
Locust class renamed to User

We've renamed the Locust and HttpLocust classes to User and HttpUser. The locust attribute on TaskSet instances has been renamed to user.


text:
Q: Compute the negative numbers in an array I was searching for solution to find negative numbers in array and i came up with something like this code from searching.
public static void main(String args[]){
    int arrayNumbers[] = { 3, 4, 7, -3, -2};
    for (int i = 0; i <= arrayNumbers.length; i++){
        int negativeCount = 0;
        if (arrayNumbers[i] >= 0){
                negativeCount++;
    }
    System.out.println(negativeCount);
    }
}

I was wondering is there an easier or shorter way to find the negative number in an array vs the code above?

A: A java 7 string-based one-liner that counts the minus signs:
System.out.println(Arrays.toString(array).replaceAll("[^-]+", "").length());

A Java 8 stream-based way:
System.out.println(Arrays.stream(array).filter(i -> i < 0).count());

Regarding your code, there are a few things wrong with it:

*

*Since you don't care about the index of an element, use the foreach syntax instead

*Declare the scope of your count variable outside the loop, otherwise

*

*it keeps getting set to zero every iteration, and

*you couldn't use it even if it did contain the correct count because it would be out of scope (which would be only inside the loop) where you need to return it (after the loop)

*Use the correct test number < 0 (your code >= 0 counts non negative numbers)

Try this:
public static void main(String args[]) {
    int[] array = { 3, 4, 7, -3, -2};
    int negativeCount = 0;
    for (int number : array) {
        if (number < 0) {
            negativeCount++;
        }
    }
    System.out.println(negativeCount);
}

A: A few issues with the code:

*

*the terminating condition in the for will produce an out of bounds exception (arrays use zero-based index)

*the scope of negativeCount is within the for only

*the negative check is incorrect

A slightly shorter version would use the extended for:
int negativeCount = 0;
for (int i: arrayNumbers)
{
    if (i < 0) negativeCount++;
}

For a shorter version (but arguably less readable) eliminate the for's {}:
int negativeCount = 0;
for (int i: arrayNumbers) if (i < 0) negativeCount++;

A: Your negativeCount should be declared outside your loop.. Also, you can move your System.out.println(negativeCount) outside your loop, as it will print for every iteration..
And you can use enhanced-for loop
public static void main(String args[]){
    int arrayNumbers[] = { 3, 4, 7, -3, -2};

    int negativeCount = 0;
    for (int num: arrayNumbers) {
        if (num < 0){
                negativeCount++;
        }

    }
    System.out.println(negativeCount);
}

A: A bit shorter with the foreach syntax:
 int negativeCount = 0;
 for(int i : arrayNumbers)
 {
      if(i < 0)negativeCount++;
 }


text:
Q: Generating series for powers of Fibonacci numbers Denote $(f_n)_n$ the Fibonacci numbers and $(l_n)_n$ the Lucas numbers. The definition is such that
$$
\begin{array}{lll} f_0 = 0,& f_1= 1,& f_{n+2}=f_{n+1}+f_n,\\
l_0 = 2,& l_1=1, &
l_{n+2}=l_{n+1}+l_n.
\end{array}
$$
Define formal series
$$F_{k}(x) :=  \sum_{n\geq 0} f_{k(n+1)}x^n
\quad \text{and} \quad
 L_k(x) := \left\{ \begin{array}{ll} \frac{1}{1-x},& k=0, \\
\sum_{n\geq 0 } l_{k(n+1)}x^n, &k>0. \end{array}\right.
$$
Prove that, for all $p\geq 0$:
\begin{eqnarray}
\sum_{n\geq 0} f^{2p}_{n+1}x^n =& \frac{1}{5^p}\sum_{k=0}^p \binom{2p}{p-k}L_{2k}((-1)^{p-k}x) ,
\\
\\
\sum_{n\geq 0} f^{2p+1}_{n+1}x^n = &\frac{1}{5^p}\sum_{k=0}^p \binom{2p+1}{p-k}F_{2k+1}((-1)^{p-k}x) .
\end{eqnarray}
My interest in that formula comes from the fact that
$$
F_{2k+1}(x) = \frac{f_{2k+1}}{1-l_{2k+1}x-x^2}\quad \text{and} \quad
L_{2k}(x) = \frac{l_{2k}-2x}{1-l_{2k}x+x^2},
$$
thus giving the generating series as a rational function, from which a recurrence relation for Fibonacci powers can be read off.
It is known that Fibonacci powers for a fixed exponent must satisfy a finite recurrence relation, check out http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/Fibonomials.html. However I have no idea on how to prove this precise formula.
Edit: As Phira mentioned and I forgot to check, it is easily proven using Binet's formula, but a proof that makes no use of irrational numbers would be nice.


text:
Q: Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug' When I add ONE SHARE SDK as dependency I get the following error message:

Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
  com.android.build.api.transform.TransformException: org.gradle.tooling.BuildException:
      com.android.dx.cf.iface.ParseException: class name (com/sina/weibo/sdk/component/view/CommentComponentView$RequestParam)
       does not match path (weiboSDKCore_3.1.2/com/sina/weibo/sdk/component/view/CommentComponentView$RequestParam.class)

What could be the cause of this error?

A: Adding the following code to build.gradle app module solved my problem
android{
    defaultConfig {

        // Enabling multidex support.
        multiDexEnabled true
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}
dependencies {
    //...
    compile 'com.android.support:multidex:1.0.0'
}

Source Code

A: Sounds like the error is recognizing a class cast issue. It expects CommentComponentView$RequestParam.class
but it getting something else. Could be different version or duplicate named class where it is trying to figure out which one to use and it is using the wrong one.
For example if I have a class called
public class MyClass {
}
and the SDK has a class called
public class MyClass {
}
then in the usage it could be confusing the two. Check your import statements to make sure you are using the correct path and version of the parameter that it is expecting as maybe it is a duplicate class that is confusing it by accessing the wrong version of that class.
This may not be your issue, but worth checking out. Goodluck.

A: It's probably a rare scenario, but I had it. Previously, an android-support-v4.jar file was manually added to my project. This was done before the use of the gradle. Remove the file and the build was successful.


text:
Q: Create a program which utilizes 2 different ISAs Hello newcomer here (be gentle),
I am attempting to write a program which has floating point code in it.  However this program needs to run on 2 different processors.  Which have roughly identical ISAs except for their floating point model.  They use completely different instructions and registers to do floating point calculations.  What would be an elegant way to get gcc to compile one section of code for 1 processor's model, and another section for the other processor's model?  I already have in place a method for determining which processor the code is currently running on, so I can have it link to the corresponding code in memory.
Everything is done in C only.  For the curious, I'm using powerpc e500v2 and e300 cores.
This is not a homework question, no teachers will be upset at the internet over this.

A: Build two different .o files using the different GCC options.
I am assuming that you are talking about code that is compatible enough to share an ELF file, such as x87 vs SSE2 floating point, and not x86 and x86_64 or odd stuff like ClearSpeed.


text:
Q: Run Background nodejs Process on Ubuntu I have a nodejs/swagger project that I'm running on a virtual Ubuntu instance for a class I'm taking right now, and I'd like to be able to just have it run in the background. I'm clearly able to connect to the project, except the API seems to go awry when I close my PuTTY sessions, regardless of how I run the project.
I've used every combination of nohup, detach, &, and screen to run this, and somehow, each time, I get the exact same behavior: when I open a PuTTY session (or, for that matter, when I log in via the VBox screen through the host - I don't have to do anything, I just have to log in somehow it seems), the API seems to go back up, and when I close PuTTY (or logout in the VBox screen), the API seemingly crashes.
I say seemingly because I'm not familiar with nodejs or swagger, but what I can say is that when I'm logged in, http://localhost:3000/viewer/ gives me the interactive page that it's supposed to, whereas when I'm logged out, http://localhost:3000/viewer/ returns the same thing as http://localhost:3000/api/ when I'm logged in: {"message":"Cannot read property 'apiPath' of undefined"} (which, if I'm not mistaken, is a JSON object?).
All I can say is that it seems to have something to do with the way I installed nodejs (I used nvm install 4.1.0 instead of apt-get install nodejs-legacy), because I noticed that when I logout and then log back in, if I don't include nvm use v4.1.0 at the end of my .bashrc, then Ubuntu doesn't recognize node or npm or swagger as commands. For reference, this is the rest of what I've added to my .bashrc:
export NVM_DIR="/home/pockets/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

. ~/.nvm/nvm.sh
nvm use v4.1.0


text:
Q: Days between two dates error code in python from datetime import date

f_date = input("Enter your first date: ")
l_date = input("Enter your last date: ")
a = date(f_date)
b = date(l_date)
main = (a-b)
result = (main).days
print("Result: ",result)

My first input: 2011/11/17
My second input: 2011/11/24
the output that I want is = 7 days
but I got output : TypeError: an integer is required (got type str)
What should I do to fix this error and get the true output?

A: You need to parse the string to a datetime with a specified format, for example:
from datetime import datetime

f_date = input("Enter your first date: ")
l_date = input("Enter your last date: ")

a = datetime.strptime(f_date, "%Y-%m-%d")
b = datetime.strptime(l_date, "%Y-%m-%d")

result = (a-b)

print("Result: %d days" % result.days)

->
Enter your first date: 2020-12-20
Enter your last date: 2020-12-02
Result: 18 days


text:
Q: Items of a Model are not counting seperatly I am building a BlogApp and I am stuck on a Problem.
models.py
class Album(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True)
    file = models.ImageField(upload_to='posts',null=True,blank=True)
    video = models.FileField(upload_to='videos',null=True,blank=True)

views.py
def new_story(request):
    file = Album.objects.filter(user=request.user)
    context = {'file':file}
    return render(request, 'mains/new_story.html', context)

When i count using

video_limit = Album.objects.filter(user=request.user,video__isnull=False).count()

then it counts file objects too BUT i am trying to count only video objects.
What i am trying to do :-
There are two fields in the Albummodel AND I am trying to count file and video separately. when i count in the template using {{ file.count }} then it count all the files and videos BUT when i try to count separately {{ file.video.count }} then it is not showing.
I have no idea, how can i count separately.

A: {{ file.video.count }} is empty because file is a queryset and it has no "video" property.
You can achieve what you want without using aggregates.  The easiest way is to store the video count separately and pass it to the context:
def new_story(request):
    file = Album.objects.filter(user=request.user)
    video_count = file.filter(video__isnull=False).count()
    context = {
        'file': file,
        'video_count': video_count
    }
    return render(request, 'mains/new_story.html', context)

And in your template, you can just use {{ video_count }}
UPDATE:
Try to replace video_count with the following:
video_count = file.exclude(video='').count()

or
from django.db.models import Q
video_count = file.filter(Q(video__isnull=True) | ~Q(video='')).count()


text:
Q: Which is correct - PayPal documentation or their PHP IPN code samples? According to PayPal's Implementing an IPN Listener documentation, the correct sequence of events for an IPN listener is:

*

*listener receives a notification

*listener sends an empty HTTP 200 response

*listener prepends cmd=_notify-validate onto the notification it received and sends it back to PayPal via POST

*PayPal responds with either VERIFIED or INVALID

*listener handles the notification appropriately

However, the sample code (apparently supplied by PayPal) on GitHub does things in a different order:

*

*listener receives a notification

*listener prepends cmd=_notify-validate onto the notification it received and sends it back to PayPal via POST

*PayPal responds with either VERIFIED or INVALID

*listener handles the notification appropriately

*listener sends an empty HTTP 200 response
Does the sample code work correctly?  If not, why is PayPal citing this code as an example?  If so, why does PayPal's documentation not reflect the correct coding sequence?  ...or does the order not matter?

A: Apparently the answer is "It doesn't matter which order it's done in" - as long as the response is received within the timeout window.
I found this information buried on the PayPal site as one of the possible answers when I was searching for "sandbox transactions not sending IPN" at https://www.paypal-techsupport.com/:

How long is the IPN timeout length?
PayPal's Instant Payment Notification (IPN) system expects your web
  server to send an HTTP 200 response when the IPN is sent to your IPN
  script.
If your server doesn't respond after a certain amount of time, the IPN
  system then re-posts the IPN to your script.
The amount of time between each re-post doubles each time: 10 seconds,
  20 seconds, 40 seconds, 80 seconds, and so on, up to a maximum of 24
  hours. The IPN system stops re-posting when:

*

*PayPal receives a basic HTTP "200 OK" response from your web server, or

*When approximately four days have passed since the initial post.

Note that if your IPN listener is spending more than 10 seconds getting to its end where it responds with the HTTP 200 result (as shown in the sample code), you are doing something very wrong:  An IPN handler should be a really quick process, executing as fast as possible, especially if you want to handle significant volumes of traffic.


text:
Q: Issue with Profile Page Title "User Midhun MP - Stack Overflow" In Stack Overflow, when I navigate to Profile page using Winter bash icon. It shows the URL on title instead of normal title (User Midhun MP - Stack Overflow).
In normal case, Title:

When I Navigate to Profile Page by clicking on Winter Bash Cap, title:

A: Good catch, thanks.  Fixed now.


text:
Q: How can I format this date properly in Objective-C? I have the following string:
"2011-08-31 14:12:24"
How can I format it so that it displays as "2h ago" if that is how much time has elapsed?
I have some code that works similarly, but not quite:
+(NSString*)toShortTimeIntervalString:(NSString*)sDate
{
    NSDateFormatter* df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
    [df release];

    NSDate* today = [[NSDate alloc] init];
    NSDate *d = date; //[_twitter_dateFormatter dateFromString:sDate];
    NSTimeInterval interval = [today timeIntervalSinceDate:d];
    [today release];

    //TODO: added ABS wrapper
    double res = 0;
    NSString* result;
    if(interval > SECONDS_IN_WEEK)
    {
        res = fabs(interval / SECONDS_IN_WEEK);
        result = [NSString stringWithFormat:@"%1.0fw ago", res];
    }
    else if(interval > SECONDS_IN_DAY)
    {
        res = fabs(interval / SECONDS_IN_DAY);
        result = [NSString stringWithFormat:@"%1.0fd ago", res];
    }
    else if (interval > SECONDS_IN_HOUR){
        res = fabs(interval / SECONDS_IN_HOUR);
        result = [NSString stringWithFormat:@"%1.0fh ago", res];
    }
    else if (interval > SECONDS_IN_MIN) {
        res = fabs(interval / SECONDS_IN_MIN);
        result = [NSString stringWithFormat:@"%1.0fm ago", res];
    }
    else
    {
        interval = fabs(interval);
        result = [NSString stringWithFormat:@"%1.0fs ago", interval];
    }
    return result;
}

A: Check out NSDateComponents. It is a great tool for doing stuff like this. The Date and Time Programming Guide can walk you through what you are trying to accomplish.

A: I built an NSValueTransformer to do this. You can check it out for hints for your own code. https://github.com/billgarrison/SORelativeDateTransformer


text:
Q: Incorrectly nested style tag found then seeding database in laravel then I try to seed my laravel database i get: Incorrectly nested style tag found.
I have done everything as is required in documentation and can't understand the reason of this error
Symfony\Component\Console\Exception\InvalidArgumentException  : Incorrectly nested style tag found.

  at C:\wamp\www\advoca\vendor\symfony\console\Formatter\OutputFormatterStyleStack.php:75
    71|                 return $stackedStyle;
    72|             }
    73|         }
    74|
  > 75|         throw new InvalidArgumentException('Incorrectly nested style tag found.');
    76|     }
    77|
    78|     /**
    79|      * Computes current style with stacks top codes.

Whats wrong?
my DAtabase seeder:
class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            QueryTemplate_seeder::class,
        ]);
    }
}

my QueryTemplate_seeder :
<?php

class QueryTemplate_seeder extends Seeder
{

    public function run()
    {
           //1
           DB::table('query_templates')->insert([

            'content' => 'some string content',
            'queryid' => 111111,
            'customerId'=>'sdfsgdgsdgdsg'
        ]);

         //2
         DB::table('query_templates')->insert([

            'content' => 'some string content',
            'queryid' => 123456,
            'customerId'=>'sdgsdgsdgsdgfsdg'

        ]);

         //3
         DB::table('query_templates')->insert([

            'content' => 'some string content',
            'queryid' => 112233,
            'customerId'=>'adsgdfgsdfgdgs'
        ]);
    }
}

please help!!!

A: I solved problem by deleting all seeds and creating them again. and everything worked!


text:
Q: NewID() taking long time to process I am executing the code below for a table with 2 million plus records but NewID() is taking a long time to run.
Can you suggest an alternate method to make the query faster?
DELETE FROM Table1
WHERE ID NOT IN (SELECT TOP 60000 ID FROM Table1
WHERE flag <> '1'
ORDER BY NEWID())
AND
ID NOT IN(SELECT ID FROM Table1
WHERE flag = '1');

A: How about this... should be twice as fast
DELETE FROM Table1
WHERE ID NOT IN (SELECT TOP 60000 ID FROM Table1
                 WHERE flag <> '1'
                 ORDER BY NEWID())
   AND flag != '1';


text:
Q: How to read a file? private void getInput() throws IOException {

    InputStream resourceAsStream = this.getClass().getResourceAsStream(
            "aaa.txt");
    BufferedReader br = new BufferedReader(new FileReader(
            resourceAsStream.toString()));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String everything = sb.toString();
        System.out.println(everything);
    } finally {
        br.close();
    }
}

The file aaa.txt is in the same project and it cannot be read, I have java.lang.NullPointerException when I execute that.

A: Only do this
BufferedReader br = new BufferedReader(new FileReader("aaa.txt"));
But put the file in the filereader instead.
Hope it helpt.


text:
Q: SAPUI5 Table: unbindRows & destroyColumns cause error: Cannot read property 'shouldRender' of undefined I am using the Table object from the SAPUI5's sap.ui.table namespace:

var oTableOverview = new sap.ui.table.Table();

On rowSelectionChange, when selecting one row I populate another table, let's call it oTableDetail, that is filled with some data.
When deselecting the row from the first table, I want to clear the content of the second, and for that I use:

oTableDetail.destroyColumns();
oTableDetail.unbindRows();

When deselecting the row I get the following error:
TableRenderer.js:6 Uncaught TypeError: Cannot read property 'shouldRender' of undefined
I found the method shouldRender of the sap.ui.table.Column class, but I am not sure why would the cells be rerendered in this case.
I also noticed that if I use either oTable.destroyColumns(), or oTable.unbindRows() separately, the error does not appear.
I am using the "1.38.11" version of SAPUI5.
Can you please help me identify why this happens?
EDIT 1:  A possible workaround would be to use:

oTableDetail.setModel(new sap.ui.model.json.JSONModel({}));
oTableDetail.destroyColumns();

Although I still don't know why the code mentioned before is not working.
EDIT 2: A behavior that I find a bit weird:
trying to add a setTimeout like this works (the error is not happening):

oTable.destroyColumns();
setTimeout(function(){  oTable.unbindRows();  }, 50);

but this other way it doesn't work (the error still appears) even if the delay is longer:

oTable.unbindRows();
setTimeout(function(){  oTable.destroyColumns();  }, 50);

A: var oTableOverview = new sap.ui.table.Table();
//your model with new dynamic data
var oModel = new sap.ui.model.json.JSONModel(newData);

oTableDetail.setModel(oModel);
//use rerender method which tries to replace
//its DOM reference by re-rendering with new data.
oTableDetail.rerender();

You don't need to actually delete columns or unbind rows.
Rerender method will take care of new data.

A: So if you don't want to set a new model, then just try to clean oData of an existing model.
var oTable = this.byId("oTable")
//your model with new dynamic data
var oModel = oTable.getModel();

oModel.setData(null);
// then if its needed, use updateBindings method to refresh
oModel.updateBindings();


text:
Q: C# - Visual Studio suggesting I rename a property to something else that already exists Here is the code:
namespace Phylor.Application.FrontEnd.Search.Models.Adjudication
{
    public class ResultsGridViewModel
    {
        public List<ResultGridProductModel> NmResult = new List<ResultGridProductModel>();
        public List<ResultGridProductModel> WlsResult = new List<ResultGridProductModel>();
        public List<ResultGridPepModel> PepResult = new List<ResultGridPepModel>();
        public List<ResultGridProductModel> MedResult = new List<ResultGridProductModel>();
    }

    public class ResultGridProductModel
    {
        public long ResultId { get; set; }
        public string Url { get; set; }
        public string ProductId { get; set; }
        public string Category { get; set; }
        public string Identifier { get; set; }
        public string IndividualName { get; set; }
        public string EntityName { get; set; }
        public string Remarks { get; set; }
        public string Text { get; set; }
        public string Address { get; set; }
        public string DateOfBirth { get; set; }
        public string PlaceOfBirth { get; set; }
        public string Score { get; set; }
        public string Age { get; set; }
        public string Gender { get; set; }
        public string Race { get; set; }
        public string Nationality { get; set; }
        public string EyeColor { get; set; }
        public string Height { get; set; }
        public string Weight { get; set; }
        public string HairColor { get; set; }
        public string SourceRegion { get; set; }
        public string Program { get; set; }
        public string AliasList { get; set; }
        public string Caution { get; set; }
        public string SourceAgencyName { get; set; }
        public string SourceAgencyAcronym { get; set; }
        public string SourceParentAgency { get; set; }
        public string SourceCountry { get; set; }
        public string ServiceName { get; set; }
        public bool IsMatch { get; set; }
    }

Now see the screengrab to see what I see in Visual Studio, particularly SourceCountry.

I've never seen this broken-dotted border before, and Google is not helping me understand what it is.  What does this border mean, and why is it suggesting I rename Caution to it?

A: That's just a suggestion and the broken dotted border is only a highlight of the text selected for the current action.
You could just ignore it tho, if you don't want to rename, besides as we all know, it's only a suggestion.


text: Q: Default shipping class for variations In Woocommerce, shipping class for all product variations in ( Variations - Shipping class ) dropdown menu assigned by default to 'Same as parent'. How it can be assigned by default to shipping class that has been selected in ( Shipping - Shipping class ) dropdown menu. The reason why I need it, because I have got plugin (shipping calculator) that shows shipping classes and prices on product page, and for some reason it shows correctly only when I select shipping class manually for each variation from Variations - Shipping class dropdown menu. However, when it's got by default "Same as parent", my plugin just shows all possible shipping classes on product page. I just want to automate somehow this process, instead of selecting shipping classes for each variation all the time manually.


text:
Q: bad character range :-' at position 6 exception in python I am comparing two strings but excluding the punctuation marks in both.
Here is my code snippet:
punctuation = r"[.?!,;:-']"
string1 = re.sub(punctuation, r"", string1)
string2 = re.sub(punctuation, r"", string2)

After running this code I get following exception
bad character range :-' at position 6

How to get rid of this exception? What's the meaning of "bad character range"?

A: - has special meaning inside [] in regular expression pattern - for example [A-Z] are ASCII uppercase letters (from A to Z), so if you need literal - you need to escape it i.e.
punctuation = r"[.?!,;:\-']"

I also want to point regex101.com which is useful for testing regular patterns.

A: A - inside a character class [...] is used to denote a range of characters, for example: [0-9] would be equivalent to [0123456789].
Here, the :-' would mean any character between : and '.  However, if you look up the character numbers, you see that they are in the wrong order for that to be a valid range:
>>> ord(":")
58
>>> ord("'")
39

In the opposite order '-: (inside the []) it would be a valid character range.
In any case, it is not what you want.  You want the - to be interpreted as a literal - character.
There are two ways to achieve this.  Either:

*

*escape the - by writing \-

*or put the - as the first or last character inside the [], e.g. r"[.?!,;:'-]"


text:
Q: Using Ampersand character to create shortcuts on mac using Qt Designer I am currently working through a tutorial on designing a GUI using Qt Designer 5 in conjunction with Pycharm 3.4 on Mac Yosemite.
According to the (windows-based) tutorial preceding the text property of a line edit widget with the ampersand character causes the first character of the line edit text to become a shortcut.
When I convert the Qt Designer code to python using the pyuic4 utility and import this into my program it appears not to work.
Any advice as to what might I might be doing wrong would be most appreciated.  Thanks in advance….
def retranslateUi(self, Dialog):
    Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
    self.label.setText(_translate("Dialog", "&Number Of Items", None))
    self.label_2.setText(_translate("Dialog", "&Discount Percentage", None))
    self.label_3.setText(_translate("Dialog", "&Price per Item", None))
    self.pushButton.setText(_translate("Dialog", "Calculate Amount", None))

A: According to the documentation for QShortcut, ampersand shortcuts are disabled by default on Mac. However, apparently it's possible to be enable them like this:
    QtGui.qt_set_sequence_auto_mnemonic(True)

I should also point out that your description of ampersand shortcuts in labels is wrong. A label must have a buddy set in order for its shortcut to transfer focus to another widget (such as a line-edit). This can be done in Qt Designer via its Buddy Editing Mode.


text:
Q: Using v-bind and v-on instead of v-model vuejs I was using v-model to handle inputs in a form, I had to change it to bind props values, at first input was like
<input type="text" class="form-control" placeholder="" v-model="username">

and now it looks like
<input type="text" class="form-control" placeholder="" v-bind:value="modelData.username" v-on:input="username = $event.target.value">

modelData is coming in props. and it has username.
when Using model, in data, i had defined
data: () => {
  return {
    username: ""
  }
},

and It was working fine, but after changing it to v-bind and v-on,
My question is how I can now get the value of username in methods? as in past, I was getting it as this.username to get the value and also clear it as well but now how I can get username in
methods: {}

I have a button to save input
<button class="btn btn-secondary" type="button" @click="validateFormAndSave($event)">Save</button>

When validateFormAndSave get called I can have this.username right now I cannot get the value? But the Vue Doc says v-model and v-bind:value& v-on:input are the same?
UPDATE:
There can be and cannot be some value already there in username, as it being filled with props value, So v-on:input="username = $event.target.value" don't get the already written value but the only new one you entered? or edit it? Why is it so? is there any method for just to get what anyone typed in there or already been typed?
UPDATE:
This is getting very ambiguous. So for now.
1. I can set v-bind:value, But I cannot get it in methods without editing it.
2. I cannot set this.username = "" and it will not be removed from input as well.
3. @input only get what you newly typed not what already in there

A: v-model is just syntax sugar for =>
<input :value="modelValue" @input="modelValue = $event.target.value"/>

If you want something else, it's very easy to do. Just change the update side to onInput:
<input
    class="form-control"
    :value="username"
    @input="username = $event.target.value"
>

Then
data: () => {
  return {
    username: ""
  }
},
mounted()
{
  this.username = this.modelData.username;
},
methods:{
  consoleUsername() {
    console.log(this.username);
  }
}

A: The best possible solution can be when you are getting your data from props and also loading it a form for v-models.
Using watch feature of Vue component.
First I added props as
  export default {
    props: ["vendorModelData"],

and then I pass it through the watch to v-model
watch: {
  vendorModelData() {
    this.updatePropsValue(this.vendorModelData)
    console.log("data updated")
  }
},

in this way, it always loads differently when Props get changed.  This way I got be using v-model as well as load data from props to it.
I found it useful for me.


text:
Q: url and paths helpers on laravel when document root has changed I'm becoming to use laravel framework (v5.7). I recently changed my document root and virtual host as follows (the aim was just don't show "public" on the url's):
Document Root:
DocumentRoot "${INSTALL_DIR}/www/laravel/public"
<Directory "${INSTALL_DIR}/www/laravel/public/">
    Options +Indexes +FollowSymLinks +Multiviews
    AllowOverride all
    Require local
</Directory>

Virtual Host:
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www/laravel/public"
  <Directory "${INSTALL_DIR}/www/laravel/public/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>

Once it was done, my css and js files didn't point to the right place (normal, I thought). I looked in the laravel documentation but I started to be confused about the right way of generate urls for css and js files in my project.
Laravel has different helpers to generate urls (such as url() and asset()) and other helpers to point to folders (base_path(), public_path(), resource_path()).
I also searched on Google about this and I began more confused because many people use the asset helper to generates url of files which are located on the public folder (not the resources folder).
My questions are the following:

*

*If my css and js files are located in the public folder (public/js and public css), which is the correct way to generate those urls once the document root folder and virtual host has changed the folder to look in?

*Should I use the asset helper or the url helper to generate them?

*May I use a combination of helpers to do it?
For example: url(public_path('css/style.css'))
PD: my "own helpers" for you:
In both cases, asset() and url() prints the same:

*

*asset('') and url('') --> "http://localhost/"

*asset(public_path('')) and url(public_path('')) --> "http://localhost/C:\wamp64\www\laravel\public"

A: It looks like
asset('css/style.css')

is the right way to do it.


text:
Q: Tower of Hanoi list of disks on the rods I'm currently trying to finish a program that outputs the "radius" of each disk on each rod in lists. I currently wrote this program:
k = 3
ct = 0
list1 = Table[n, {n, 1, k}];
list2 = {};
list3 = {};
solveHanoi[n_, start_, aux_, end_] := Module[{},

   If[n == 1,
      ct++;
   first = First[ToExpression["list" <> start]];
   rest = Rest[ToExpression["list" <> start]];
   list = ToExpression["list" <> end];
   list = AppendTo[list, first];
   Clear[Evaluate["list" <> end], Evaluate["list" <> start]];
   Evaluate[Symbol["list" <> start]] = rest;
   Evaluate[Symbol["list" <> end]] = list;
   Print[Column[{ToExpression["list" <> start],
      ToExpression["list" <> aux], ToExpression["list" <> end]}]]
     ,
      solveHanoi[n - 1, start, end, aux];
      ct++;
   first = First[ToExpression["list" <> start]];
   rest = Rest[ToExpression["list" <> start]];
   list = ToExpression["list" <> end];
   list = AppendTo[list, first];
   Clear[Evaluate["list" <> end], Evaluate["list" <> start]];
   Evaluate[Symbol["list" <> start]] = rest;
   Evaluate[Symbol["list" <> end]] = list;
   Print[Column[{ToExpression["list" <> start],
      ToExpression["list" <> aux], ToExpression["list" <> end]}]];
      solveHanoi[n - 1, aux, start, end]
      ]
    ]

solveHanoi[3, "1", "2", "3"]

For some reason the output starts messing up once the second and the third stack starts swapping, as it seems to mistaken between them. I tried looking for solutions but I don't know what I did wrong.
This is the base program our teacher gave us:
solveHanoi[n_, start_, aux_, end_] := Module[{},
    If[n == 1,
      ct++;
      Print[
    "Step " <> ToString[ct] <> " : Move from " <> start <> " to " <>
     end],
      solveHanoi[n - 1, start, end, aux];
      ct++;
      Print[
    "Step " <> ToString[ct] <> " : Move from " <> start <> " to " <>
     end];
      solveHanoi[n - 1, aux, start, end]
      ]
    ]

A: Huh, all these statements with Evaluate have the tendency to mess up things. What you try to realize there is called call by reference: The strings that you supply as arguments to solveHanoi work as pointers to the respective arrays. Indeed, this is pretty clever, but you can do that much cleaner by assigning solveHanoi the attribute HoldAll and by calling solveHanoi directly with the lists as arguments; this way, the arguments can be manipulated by side effects within the function body (see the code below). In general, this is a very efficient strategy but it is also somewhat undesired in the Mathematica language, mostly because it confuses users. Nonetheless, we are going to employ it.
The second thing that I observed is that you probably want to Prepend or PrependTo instead of AppendTo. By the way: PrependTo and AppendTo have the attribute HoldFirst, which is like HoldAll but for the first argument only. So, the effect of list = AppendTo[list,first] is also achieved by AppendTo[list,first].
But the very simple issue that might got you puzzled is that you print the towers always in the order start, aux, end; note that the actual towers that are pointed to by these "pointers" vary in each call to solveHanoi. It might be better to print the towers in fixed order: Print[Row[{list1, list2, list3}]];.
The cleaned-up code could look like this:
ClearAll[solveHanoi]
SetAttributes[solveHanoi, HoldAll]
solveHanoi[n_, start_, aux_, end_] := If[
  n == 1,
  ct++;
  PrependTo[end, First[start]];
  start = Rest[start];
  Print[Row[{list1, list2, list3}]];
  ,
  solveHanoi[n - 1, start, end, aux];
  ct++;
  PrependTo[end, First[start]];
  start = Rest[start];
  Print[Row[{list1, list2, list3}]];
  solveHanoi[n - 1, aux, start, end]
  ]

And this is how to call it:
k = 3;
ct = 0;
list1 = Table[n, {n, 1, k}];
list2 = {};
list3 = {};
solveHanoi[k, list1, list2, list3]

{2,3}{}{1}
{3}{2}{1}
{3}{1,2}{}
{}{1,2}{3}
{1}{2}{3}
{1}{}{2,3}
{}{}{1,2,3}

So basically, you had perfectly the right idea.


text:
Q: BigQuery error: No matching signature for operator >= I am getting an error No matching signature for operator >= for argument types: STRING, INT64. Supported signatures: ANY >= ANY at [1:60] when I run this R script to fetch some data from BiqQuery.
This is where I get the error:
a <- dbGetQuery(db,
paste0("select * from dta.tbl where col1='",
somevariable"' and date>=",substr(gsub("\\D","",as.character(start.date)),3,8),
" and date<=",substr(gsub("\\D","",as.character(end.date)),3,8)))

Any clue on how do I get rid of this error? I am using standardsql here
Thanks ahead! :)

A: from brief glance - try below
a <- dbGetQuery(db,
paste0("select * from dta.tbl where col1='",
somevariable,"' and date>='",substr(gsub("\\D","",as.character(start.date)),3,8),
"' and date<='",substr(gsub("\\D","",as.character(end.date)),3,8), "'"))

A: It looks like you just need quotes.
and date>='",substr(gsub("\\D","",as.character(start.date)),3,8),"' and date<='",substr(gsub("\\D","",as.character(end.date)),3,8), "'"))


text:
Q: When use TortoiseGit with cygwin. Commit error I'm Korean.
So we use Korean file name. But I use TortoiseGit with Cygwin. Commit error.
When I use TortoiseGit, This error Message. But I use Cygwin it will work.
This is error Message.
git.exe update-index [...]
/usr/bin/bash: /bin/git.exe update-index -- "새 텍스트 문서.txt": No such file or directory
git did not exit cleanly (exit code 127)

TortoiseGit Setting
General -> Git for Windows
Git.exe Path : C:\cygwin\bin
(Git version 2.8.3)
Advanced
CygwinHack true
Help Me~! Thank you

A: This looks like an incompatibility between the Windows world and the Cygwin world (in the sense of encoding): TortoiseGit calls git.exe in order to update the file. As you described in the comments it also did not work for you from Windows cli.
I'm no cygwin export, but if you find a way on how to pass a korean encoded filename to git.exe from Windows cli I can try to code this into TortoiseGit.
PS: I strongly recommend not to use cygwin as cygwin git is known to be broken as it does not even pass the test suite (cf. https://github.com/libgit2/libgit2/pull/3040#issuecomment-94169001) - that's why Cygwin support is just experimental in TortoiseGit. Better use Git for Windows.


text:
Q: TFS 2018 Scheduled backups error TF401002 I am trying to create scheduled backups on my TFS server.
This phase passed (no problems here):

But in next phase (When i clicked on Configure button) i got this error:

Here is the log file:
https://file.io/ZvJKLB
** I am already changed LogOn services 'Sql server', 'Job agent' to my user.
Thank you for helping!

A: Please try to give db_backupoperator.
if you dont have security issues the cleanest way is to give "sysamin" permission to Matan user.

A: Please keep in mind this error could be masking the underlying error.
During migration to Azure DevOps Server 2020.1, I received the same error and had to review the scheduling tool's log file to find that the log file for one of the databases was full.
In both the TFS 2018 configuration tool and the Azure DevOps Server 2020.1 configuration tool, there is a link to the detailed log output.  Make sure you review the detailed log output before adjusting permissions on your SQL server.
*

[Info   @15:34:39.634] Granting account DOMAIN\YourServiceAccount
permissions to initiate database backups of
Tfs_YourCollectionsName [Error  @15:34:39.649]  Exception Message:
TF30042: The log file for the database is full. Contact your Azure
DevOps Server administrator to back up the transaction log for the
database to free up some log space.
*

The fix was to perform a LOG backup to SQL Server's 'NUL' output and then configure scheduled backups:
BACKUP LOG [Tfs_YourCollectionName]
TO DISK = N'NUL' WITH NOFORMAT, NOINIT, NAME = N'Tfs_YourCollectionName-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10
GO


text:
Q: How do you give a class in the controller the ID's it belongs to? How do i give my products the user_id, Location_id and the product_dates_id in the controller?
class Product < ActiveRecord::Base
  belongs_to :user
  belongs_to :location
  belongs_to :product_date
end

My Controller:
def new
    @location = Location.new
    @product = Product.new
    product_date = @location.product_dates.build
    product_date.products.build
end

def create
    @location = Location.new(params[:location])
end

My Table:
create_table :products do |t|
      t.integer :user_id
      t.integer :location_id
      t.integer :product_date_id
end

Thank you.

A: @location = Location.create(params[:location])
@location.products.each{ |p| p.update_attribute :user_id, current_user.id }
@location.product_dates.map(&:products).flatten.each{ |p| p.update_attribute :user_id, current_user.id }

or better add hidden field for :user_id into each product and product_date

A: To answer your question
def new
    #First create the new product object assuming you have a current_user available. If not you will need to make a current_)user available.
    @product = current_user.build_product
    #Now build a new location for the product
    location = @product.build_location # You don't need location to be an instance variable.
    #when you reference @location in your form you should now be using fields_for :locations instead.
    #build a new product_date object for the location_product_dates array
    product_date = @location.product_dates.build
    #Now add that product date object to the product
    product.product_date = product_date
end

Add accepts_nested_attributes declarations to the relevant models and use fields_for declarations in the relevant product forms, that way your create and update actions don't need any changes to them as the fields_for declarations in the form will arrange for the related objects to have their data nested inside the products hash when posted back to the create and update actions.
Couple that with the accepts_nested_attributes_for declarations for all the right models and everything will automagically be updated/created
That answers you question. The new action builds all the records and sets up all the associations for you but it seems to me like you don't really need the product_date associated to the product as it is already associated to the location which is associated to the product and as a location can have many products (assumption based on your original new action) you would struggle to work out which product_date from the many location records and their associated product_date records should be added directly to the product.
I guess you have you associations slightly wrong.
You should also consider refactoring that new action into a class method on the product model to enable you to do something like
@product = Product.new_with_associations(current_user)

The def self.new_with_associations needs to just do pretty much exactly the same as the code I gave you for the new action but you will need to pass the current_user in as a param as the session hash (which is where the current_user will ultimately be coming from) is unavailable to models for very good reason.
Putting this in a class method for the product not only cleans up your controller code but also makes makes the code re-usable and simpler to test both from the console and from your test suite


text:
Q: How can I make the imported modules use the same objects as my main? My setup is this.
I have an engine.py that defines a lot of variables and custom functions that I script and modify in external script.customextension. I am using imp.load_source('script', 'script.customextension') to import my external scripts, but when I do that all the variables and functions can not be accesssed from the external module.
I have then tried writing this as the first line in the external script: from engine import * but then I am re-instantiating all the objects and losing the ones already created that I need access to.
A gross simplification is the following
file engine.py
a = 10

def f(myval):
    global a
    a = myval
    print(a)

if __name__ == '__main__':
    imp.load_source('script', 'script.ext')

and file
script.ext has this single line
f(20)

Results in this when running engine.py:
NameError: name 'f' is not defined

Where what I wanted was:
20

A: Here's ugly:
import __main__ as main

main.f(20)

A: I found that this solution could be used instead of importing modules (see exec)
    _file = open('script.ext')
    for line in _file:
        exec(line)


text:
Q: How to grab the email value from Temp-Mail Selenium I was trying to automate some email testing, through selenium and python, and I came across the Temp-Mail website: 'https://temp-mail.org/en/'. I was trying to grab the email from it, with the code:
driver.find_element_by_xpath('//*[@id="mail"]').text

although this comes up empty. I was wondering what method I should be using for this, as the html text is
<input id="mail" type="text" onclick="select(this);" data-original-title="Your Temporary Email Address" data-placement="bottom" data-value="Loading" class="emailbox-input opentip" readonly="">

A: I managed to fix it with
driver.find_element_by_xpath('//*[@id="mail"]').get_attribute('value')

and a while loop to make sure it wasn't grabbing too early.

A: For multiple reasons, logging into sites like Gmail and Facebook using WebDriver is not recommended. Aside from being against the usage terms for these sites (where you risk having the account shut down), it is slow and unreliable.
The ideal practice is to use the APIs that email providers offer, or in the case of Facebook the developer tools service which exposes an API for creating test accounts, friends and so forth. Although using an API might seem like a bit of extra hard work, you will be paid back in speed, reliability, and stability. The API is also unlikely to change, whereas webpages and HTML locators change often and require you to update your test framework.
Logging in to third party sites using WebDriver at any point of your test increases the risk of your test failing because it makes your test longer. A general rule of thumb is that longer tests are more fragile and unreliable.


text:
Q: open command partially not working in tmux in MacOS When inside a tmux session on the local computer, a command:
open "https://www.google.com"

opens a url in the default browser.
However, when trying to open a file using an app:
open -a Preview ./picture.png

open produces no error message, but fails to open the file.
When I replicate the same command in Terminal app, picture.png opens as expected in Preview app.
I have read about a similar problem here: "open" command doesn't work properly inside tmux , however, my problem is different as there is no error output and also, reattach-to-user-namespace is now obsolete.
Anyone knows how to troubleshoot this?


text:
Q: Get text from NSTextView in Swift I have an NSTextView that users will type text into. I am using this instead of an NSTextField because I need it to support adding a new line when the user hits enter (This doesn't seem to work with NSTextField, but it does with NSTextView)
I can't for the life of me figure out how to get all the text out of the NSTextView.
This SO answer tells me how to do it in Objective-C:
How to find the text in an NSTextView?
But I'm having a hard time making the jump to Swift. If I try to cast the textStorage property to NSAttributedString, I get the error "Cannot convert the expression type NSTextStorage? to type NSAttributedString".
This is an OSX application, not an iPhone application, if that makes any difference for some reason.
Thanks in advance for the help.

A: I was forgetting the exclamation point when casting. I needed to do this: (the name of the NSTextView is txtPhoneNumbers)
    (txtPhoneNumbers.textStorage as NSAttributedString!).string

A: Swift 5
A simple solution to getting the string of an NSTextView.
if let str = textView.textStorage?.string {
    // do something with string
}


text:
Q: Watch FTP folder via node.js I need to watch ftp folder for files create/update/remove events.
But I can't find any suitable solution to do this using node.js.
Can you help me, please?

A: *

*You need get recursive listing of remote ftp directory and save it (look at https://github.com/mscdex/node-ftp and https://github.com/evanplaice/node-ftpsync)

*Set timeout to get new recursive listing

*Compare new and old listing (look at https://github.com/andreyvit/json-diff) and call handlers to the corresponding events

*Overwrite old listing with new

*Return to step two

A: You can use sftp-watcher modules. which will reduce your time.
https://www.npmjs.com/package/sftp-watcher


text:
Q: zend framework: comments form issue I have a table comments like this:
Com_ID | Com_Content | Com_Date | Book_ID| User_ID

I can get everything but User_ID. I have already storage User_ID in Zend_Auth and I can view it on screen but I don't know how to get it to my from.
For example I can get Com_Date in my IndexController like this:
public function CommentAction()
{
    $Com_Date = new Zend_Db_Expr('NOW()');
    ...

So can I do the same thing with User_ID and how to do it?
Thanks in advance!

A: An identity that has been authenticated using Zend_Auth can be retrieved in the following way:
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
    // Identity exists; get it
    $identity = $auth->getIdentity();
}

Hope this is what you mean.


text:
Q: Can I include another file in fstab Can I include another file in my fstab file?
I.e. can I have fstab execute lines from another file at an arbitrary point, and then return to the main file when completed?

A: Generally not, but with newer versions of mount/swapon/fsck... on Linux (from util-linux 2.19) at least, you can have more files (with .fstab extension) in /etc/fstab.d. So you can have a /etc/fstab.d/00_header.fstab, /etc/fstab.d/50_middle.fstab, /etc/fstab.d/99_end.fstab.
Another approach if all you want is mount -a to run some command is have an entry with your own filesystem type and create a /sbin/mount.own that does the work for you.
Note that recent versions of Ubuntu have that mountall that might get in the way.
Also note that some distributions process mounts in several stages using -t fstypes, which you may need to take into account as well.

A: I have never seen a Unixy system with such an fstab(5)-setup. Look at mount(8) for the gory details of what can be done at mount time.
What do yu want this for? If really useful in more than a narrow range of usecases it just might get implemented...


text:
Q: Descriptografar um código (pelo que entendi está em ASCII) Bom, basicamente eu gostaria de saber se tem alguma forma de transformar um script escrito em ASCII em Caracteres e se tiver, como eu transformaria?
Código (1)
 local code = '\27\76\117\97\81\0\1\4\4\4\8\0\55\0\0\0\64\67\58\92\85\115\101\114\115\92\106\111\97\111\99\92\68\79\67\85\77\69\126\49\92\88\101\110\111\66\111\116\92\83\99\114\105\112\116\115\92\92\69\78\67\82\89\80\126\49\46\76\85\65\0\2\0\0\0\22\0\0\0\0\0\0\5\17\0\0\0\2\0\128\0\7\0\0\0\1\128\0\0\7\64\0\0\5\192\0\0\6\0\65\0\28\128\128\0\69\64\1\0\70\128\193\0\92\128\128\0\133\192\1\0\134\0\66\1\193\64\2\0\36\1\0\0\0\0\0\0\156\64\128\1\30\0\128\0\10\0\0\0\4\9\0\0\0\109\105\110\105\109\105\122\101\0\4\4\0\0\0\98\112\115\0\3\0\0\0\0\0\0\240\63\4\3\0\0\0\111\115\0\4\6\0\0\0\99\108\111\99\107\0\4\10\0\0\0\67\111\110\116\97\105\110\101\114\0\4\9\0\0\0\71\101\116\70\105\114\115\116\0\4\7\0\0\0\77\111\100\117\108\101\0\4\4\0\0\0\78\101\119\0\4\10\0\0\0\114\101\99\111\110\110\101\99\116\0\1\0\0\0\0\0\0\0\7\0\0\0\20\0\0\0\1\0\0\3\44\0\0\0\5\0\0\0\6\64\64\0\69\0\0\0\70\128\192\0\92\128\128\0\132\0\0\0\28\128\128\1\25\0\128\129\22\64\7\128\5\0\1\0\6\64\65\0\28\128\128\0\69\128\1\0\70\192\193\0\92\128\128\0\84\0\128\0\133\0\2\0\24\128\128\0\22\192\4\128\69\64\2\0\70\128\194\0\92\64\128\0\69\0\1\0\70\192\194\0\92\64\128\0\69\0\3\0\129\64\3\0\92\64\0\1\69\0\1\0\70\128\195\0\133\192\3\0\92\64\0\1\69\0\3\0\140\0\68\0\92\64\0\1\69\64\2\0\70\64\196\0\92\64\128\0\22\0\249\127\5\0\0\0\6\128\64\0\28\128\128\0\8\0\0\0\30\0\128\0\18\0\0\0\4\3\0\0\0\111\115\0\4\9\0\0\0\100\105\102\102\116\105\109\101\0\4\6\0\0\0\99\108\111\99\107\0\3\0\0\0\0\0\0\240\63\4\5\0\0\0\83\101\108\102\0\4\5\0\0\0\80\105\110\103\0\4\10\0\0\0\67\111\110\116\97\105\110\101\114\0\4\7\0\0\0\71\101\116\65\108\108\0\4\4\0\0\0\98\112\115\0\4\8\0\0\0\67\97\118\101\98\111\116\0\4\5\0\0\0\83\116\111\112\0\4\16\0\0\0\67\108\111\115\101\67\111\110\116\97\105\110\101\114\115\0\4\5\0\0\0\119\97\105\116\0\3\0\0\0\0\0\64\159\64\4\17\0\0\0\79\112\101\110\77\97\105\110\66\97\99\107\112\97\99\107\0\4\9\0\0\0\109\105\110\105\109\105\122\101\0\3\0\0\0\0\0\64\143\64\4\6\0\0\0\83\116\97\114\116\0\0\0\0\0\44\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\8\0\0\0\9\0\0\0\9\0\0\0\9\0\0\0\10\0\0\0\10\0\0\0\10\0\0\0\10\0\0\0\10\0\0\0\10\0\0\0\10\0\0\0\11\0\0\0\11\0\0\0\11\0\0\0\12\0\0\0\12\0\0\0\12\0\0\0\13\0\0\0\13\0\0\0\13\0\0\0\14\0\0\0\14\0\0\0\14\0\0\0\14\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\16\0\0\0\16\0\0\0\16\0\0\0\16\0\0\0\19\0\0\0\19\0\0\0\19\0\0\0\19\0\0\0\20\0\0\0\1\0\0\0\5\0\0\0\112\105\110\103\0\12\0\0\0\39\0\0\0\1\0\0\0\9\0\0\0\108\97\115\116\84\105\109\101\0\17\0\0\0\3\0\0\0\3\0\0\0\4\0\0\0\4\0\0\0\5\0\0\0\5\0\0\0\5\0\0\0\6\0\0\0\6\0\0\0\6\0\0\0\7\0\0\0\7\0\0\0\7\0\0\0\20\0\0\0\20\0\0\0\7\0\0\0\22\0\0\0\2\0\0\0\9\0\0\0\108\97\115\116\84\105\109\101\0\7\0\0\0\16\0\0\0\5\0\0\0\109\97\105\110\0\10\0\0\0\16\0\0\0\0\0\0\0'
      loadstring(code) ()

Esse código em números acima, equivale ao código abaixo :
Código (2)
  minimize = true -- minimizar a mainbp?
  bps = 1 -- quantidade de bps, deixar em 8
  local lastTime = os.clock()
  local main = Container.GetFirst()
  Module.New("reconnect", function()
  if (os.difftime(os.clock(), lastTime) >= 1) then
  local ping = Self.Ping()
  while (#Container.GetAll() < bps) do
  Cavebot.Stop()
  Self.CloseContainers()
  wait(2000)
  Self.OpenMainBackpack(minimize)
  wait(ping + 1000)
  Cavebot.Start()
  end
  end
  lastTime = os.clock()
  end)

Eu executei esse script para transformar o código em caracteres (2) para o código ASCII (1)
Código (3)
  local script = string.dump(
  function()
  minimize = true -- minimizar a mainbp?
  bps = 1 -- quantidade de bps, deixar em 8
  local lastTime = os.clock()
  local main = Container.GetFirst()
  Module.New("reconnect", function()
  if (os.difftime(os.clock(), lastTime) >= 1) then
  local ping = Self.Ping()
  while (#Container.GetAll() < bps) do
  Cavebot.Stop()
  Self.CloseContainers()
  wait(2000)
  Self.OpenMainBackpack(minimize)
  wait(ping + 1000)
  Cavebot.Start()
  end
  end
  lastTime = os.clock()
  end)

  end
  )

  buff=""
  for v=1,string.len(script) do --Convert our string into a hex string.
  buff=buff..'\\'..string.byte(script,v)
  end

  file=io.open('encrypted.txt','w') --Output our bytecode into ascii format to encrypted.txt
  file:write(buff)
  file:flush()
  file:close()

A: Como você parece saber, o string no Código 1 é uma versão pré-compilada do Código 2. Ele contém instruções para a máquina virtual de Lua. Você pode ver uma listagem mudando o Código 1 para io.write(code), salvando a saída num arquivo luac.out, e depois executando luac -l -p.
Não é simples descompilar um script pré-compilado. Você pode tentar usar LuaDec for Lua 5.1.

A: Para "descompilar" essa string, eu utilizei o seguinte código:
local file = io.open("exemplo.txt", "w") --Define arquivo que será preenchido com o conteúdo pre-compilado.
file:write (
    code = 'CódigoPreCompilado' --Código pré-compilado, exemplo: '1/2/3/4/5/...'
    loadstring(code) () --Você poderá jogar o código pré-compilado no lugar da variável **CODE**, utilizei desta forma para que pudesse organizar melhor, escolha pessoal.
)
file:close()


text:
Q: server wont connect to network; cannot find device eth0 ive looked through several of posts here on related issues and the attempts ive made all seem to lead to the same result, that eth0 is not configured or discoverable.
i have a new 17.04 server, on a laptop which had successful wifi connection. wifi light wont come on. when i ping google, it says 'name or service not known'. have no wired access to connect to until tomorrow. i do have a live usb of the installer available to boot into recovery mode if that would help.
some results so far;
sudo ifup eth0

results;
internet systems consortorium DHCP client 4.3.5.
.
.
.
can not find device "eth0"
error getting hardware address for "eth0": no such device
.
.
failed to bring up eth0

also;
    sudo ifdown eth0
results
    ifdown:interface eth0 not configured
also;
    sudo ifconfig eth0 up
result;
    eth0 error while getting interface flags: no such device
some shots from other results;

also the above photo i added the lines "#the primary network interface, auto eth0 iface eth0 inet dhcp"
also photo from ifconfig -a

also sorry im not knowledgeable of networking really

A: I suggest that you edit the file /etc/network/interfaces to replace the eth0 entry with wlp3s0 and add the SSID and encryption details, like this:
auto lo
iface lo inet loopback

auto wlp3s0
iface wlp3s0 inet dhcp
wpa-ssid <your_router>
wpa-psk <your_wpa_key>

So that you can ssh and ftp into it, I actually recommend a static address, not DHCP, however, let's get connected first and then proceed.
Reboot and tell us if you are connected:
ping -c3 www.ubuntu.com

EDIT:
If you wish to use ethernet as you indicated in your comments, then the sequence is:
auto lo
iface lo inet loopback

auto enp2s0f0
iface enp2s0f0 inet dhcp

Reboot.