text:
Q: Numexpr error when importing Pandas in ST2 I recently created my own build file for ST2 so that I could utilize the Anaconda install of python (and all of its packages i.e. pandas).   Everything seems to work except I am getting the error below from the following code:
import pandas as pd
import numpy as np
index = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 3), index=index, columns=['A', 'B', 'C'])
print df

I get the following output:
/Users/myname/anaconda/lib/python2.7/site-packages/numexpr/cpuinfo.py:50: UserWarning: [Errno 2] No such file or directory
  stacklevel=stacklevel+1)
/Users/myname/anaconda/lib/python2.7/site-packages/numexpr/cpuinfo.py:71: UserWarning: [Errno 2] No such file or directory
  stacklevel=stacklevel+1):
                   A         B         C
2000-01-01 -1.548053 -0.151756  0.118057
2000-01-02 -0.882342  0.910580 -0.063268
2000-01-03  0.376109 -1.185223  0.285832
2000-01-04 -1.723744 -0.006433  0.075403
2000-01-05  2.074607  0.464006  0.985860
2000-01-06 -0.174024  1.164324 -1.715245
2000-01-07 -1.396297 -2.066237 -0.236335
2000-01-08  1.148892  1.083617 -0.846928

To test numexpr I tried:
import numexpr
numexpr.test()

It ran in both ST2 using my build and in the terminal using Anaconda's python(produced 'OK').
I am working on OSX 10.9.4, with Python 2.7.8, Anaconda 2.1.0.
Appreciate any suggestions - Thanks
Updated to show versions:
INSTALLED VERSIONS
------------------
commit: None
python: 2.7.8.final.0
python-bits: 64
OS: Darwin
OS-release: 13.3.0
machine: x86_64
processor:
byteorder: little
LC_ALL: None
LANG: None

pandas: 0.14.1
nose: 1.3.4
Cython: 0.21
numpy: 1.9.0
scipy: 0.14.0
statsmodels: 0.5.0
IPython: 2.3.0
sphinx: 1.2.3
patsy: 0.3.0
scikits.timeseries: None
dateutil: 1.5
pytz: 2014.7
bottleneck: None
tables: 3.1.1
numexpr: 2.3.1
matplotlib: 1.4.0
openpyxl: 1.8.5
xlrd: 0.9.3
xlwt: 0.7.5
xlsxwriter: 0.5.7
lxml: 3.4.0
bs4: 4.3.2
html5lib: None
httplib2: None
apiclient: None
rpy2: None
sqlalchemy: 0.9.7
pymysql: None
psycopg2: None

A: This is an error from the routine which parse the std output of various standard UNIX commands. Make sure you have  '/usr/sbin/' in your PATH unix environment variable. This small fix solved problem on my mac os (Yosemite with Anaconda/Python).


text:
Q: Android GridView not showing items I have made an app with a gridview by following slidenerd's tutorial.  My problem is that I can see the view but it's empty. When I move my finger I can see the top and the button becoming blue.
Here is my code:
The Adapter:
public class GridViewAdapter extends BaseAdapter {
    private ArrayList<SingleButton> buttons;
    private MainActivity mainActivity;

    public GridViewAdapter(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
        this.buttons = new ArrayList<SingleButton>();

        Resources res = mainActivity.getApplicationContext().getResources();
        String[] temp = res.getStringArray(R.array.buttons);
        int[] buttonImages = { R.drawable.pic1, R.drawable.pic2,
                R.drawable.pic3, R.drawable.pic4, R.drawable.pic5,
                R.drawable.pic6, R.drawable.pic7, R.drawable.pic8,
                R.drawable.pic9 };

        for (int count = 0; count < 9; ++count) {
            this.buttons
                    .add(new SingleButton(buttonImages[count], temp[count]));
        }
    }

    @Override
    public int getCount() {
        return this.buttons.size();
    }

    @Override
    public Object getItem(int position) {
        return this.buttons.get(position);
    }

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

    @SuppressLint("ViewHolder")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ViewHolder holder = null;

        if (row == null) {
            LayoutInflater layoutInflater = (LayoutInflater) mainActivity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.single_button, parent, false);
            holder = new ViewHolder(row);
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }

        holder.buttonImage.setImageResource(buttons.get(position).image);
        holder.buttonText.setText(buttons.get(position).buttonText);

        return row;
    }

    class ViewHolder {
        ImageView buttonImage;
        TextView buttonText;

        public ViewHolder(View v) {
            this.buttonImage = (ImageView) v.findViewById(R.id.imageViewButton);
            this.buttonText = (TextView) v.findViewById(R.id.textViewButton);
        }
    }

    class SingleButton {
        int image;
        String buttonText;

        SingleButton(int image, String buttonText) {
            this.image = image;
            this.buttonText = buttonText;
        }
    }

single_button.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageViewButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/textViewButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageViewButton"
        android:layout_centerHorizontal="true"
        android:maxLines="1" />

</RelativeLayout>

main activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    tools:context="com.example.app.MainActivity" >

    <ImageView
        android:id="@+id/imageViewLogo"
        android:layout_width="wrap_content"
        android:layout_height="5dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:paddingBottom="5dp"
        android:src="@drawable/company_logo" />

    <GridView
        android:id="@+id/gridViewButtons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageViewLogo"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:horizontalSpacing="10dp"
        android:numColumns="3"
        android:stretchMode="spacingWidth"
        android:verticalSpacing="10dp" >
    </GridView>

</RelativeLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirect Silverlight To Login Page On Session Timeout I have a silverlight app that uses a simple Login.aspx page. I have all the basic ASP.NET config and it works great for page requests when sessions expire or are missing. But the silverlight service requests are not page requests, they are looking for application/msbin serialized data. So when these requests arrive for an expired session, they are redirected to the login page, which they follow and eventually end up swallowing HTML content (the login page markup). Of course that ends with a content/parsing error, as I would expect.
So my question is, what must I do to have the silverlight service responses somehow redirect the browser when the server finds the session has expired.
I've written this by hand in Javascript before and had to have the ajax response handler detect a custom header so it could do a document.location = newPath. Something along those lines would be nice.
Also, I'm not interested in other solutions I've read for keeping the session alive with no-op pings, and I would prefer not to have to implement timers and custom session manager inside the client. Hoping I've missed a setting somewhere.

A: I had exactly the same problem. Unfortunately it is not a simple setting. I documented a possible solution here. After session timeout a call of the RIA services returns a DomainServiceException which will be handled in the central Unhandled_Exception handler. If the user is not authenticated I just redirect to the main page.


text:
Q: Get the End User ip address using php I know this question was asked by many times, but I did not get the correct answer from my side. Here I am using the following code to get the end user system IP address from my hosted website.
function ipCheck() {
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    }
    elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif (getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
    }
    elseif (getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');
    }
    elseif (getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
    }
    else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
echo ipCheck();

In my local network this code is working fine. It correctly gave my local IP 192.168.xxx.xxx. but when I run this code on my website, it gave some other ip address.

A: It is working correctly. The IP address it will be giving you will be your external IP address (go to google and search "what is my ip address" and it should show you what your external IP is so you can verify your code is correct if you wish).
When used on a server hosted outside of your local network, this WILL NOT show your local ip address of 192.168.x.x as that information is not provided in the request. That IP address is only valid on your local network.

A: You can not do this because of usual Network Address Translating in IPv4 networks. That means all IP addresses behind NAT will be visible as a single IP-address (and that will be gateway address) and, therefore, you will only able to get gateway address.
Besides this, there are Proxy Servers, that could hide or change real client (i.e. his gateway) address. So in common case your question has negative answer, i.e. it's impossible.
And remember, HTTP_X_FORWARDED_FOR is a non-mandatory HTTP-request header, so it can be sent or not. It can be anything (with something like LiveHTTPHeaders under Firefox I can send 'Hello, world!' in this header and script will see that).


text:
Q: AucTeX: run latexmk + viewer in one command Question 1: I would like to have a single key combo (C-c C-a) which compiles the file (with latexmk) and displays it.
This answer solves the first part.
I tried adapting the answer to also call TeX-view, as you see below (with some additional debugging code) but it does not work — (TeX-active-master (TeX-output-extension)) is None at that point. Question 2: Why the heck? I'm a reasonable programmer, but I don't know enough Emacs Lisp to understand how that's possible. Is it a buffer local variable and we are in the wrong buffer? I ran out of time and hope reading the relevant AucTeX source code.
Moreover, the code should wait for latexmk, and apparently it does not, because TeX-command runs the external process asynchronously. How should I fix it?
Note: I've already tried the suggestion in this other answer, and it does not work.
(defun my-run-latex ()
  (interactive)
  (let ((output-file (TeX-active-master (TeX-output-extension))))
    (message output-file) ;Good.
    (TeX-save-document (TeX-master-file))
    (TeX-command "LatexMk" 'TeX-master-file -1)
    (message (TeX-active-master (TeX-output-extension))) ; Bad
    ;(TeX-view) ;Won't work, because TeX-active-master does not work at this point.
)

My AucTeX version is 11.87.3, on Emacs 24.3.1:
M-x emacs-version
> GNU Emacs 24.3.1 (x86_64-apple-darwin, NS apple-appkit-1038.36) of 2013-03-13 on bob.porkrind.org

Update:
Why do I need to use the view command, instead of letting the viewer reload the file?

*

*The View command will also jump to the (clarified) location corresponding to the current location in the editor, while the PDF reload command will not. View (C-c C-v) does work with Skim (Skim provides a command for this purpose).

*My PDF viewer, Skim on OS X, does not reload the file automatically. I'm using one of the two setups recommended for Skim, the one where the reload is forced through the editor. I've just tried out the other one, and Skim asks whether to reload the file (it preserves the setting only until Skim is closed). I prefer to address this through Emacs than by changing Skim (unless you can show something at least as good as Skim in every respect).


text:
Q: How to use Telegram API (to include Chat Application) in my existing android app? I want to use telegram APIs in order to develop chatting feature in My Existing Android App.
I am not getting how to implement.

A: I think, it is a good idea to take a look at the Telegram Database Library (Beta) from here TDLib (Russian, but translate with Google) and the Java doc (English) from here.
The information is a little poor yet, but I think you can understand it.

A: Use this API.
Refer to the Getting Started section to integrate Telegram in your app.


text:
Q: IOS Application Multi Language support with Database im developing application for ios5.im using core data as data storage.i have to display some information and those informations are saved in 4 languages in database, user can select language.when selects a language whole application should translated in to selected language by fetching strings from database.the database sync with remote database when application starts database sync with remote database(db is dynamic therefore can't use string file to translate my app).(except translation thing all other things are implemented im stuck with translation with db,i have small idea when user select language whole set of string loaded to user-default but i think it is not correct)any idea about translation ios app with strings in database?

A: Localizable.strings uses a key/value pair approach. Do something similar inside your db. Assign a token (key) to your string (value) plus an flag for the language. The "flag" can be a integer, string, what-ever-you-like-most
Then your FetchRequest can query for the token and for the language flag and will return the string that is matching token and flag. When the user changes language the flag is changed, too, And for the same token as previously but now with the new flag a fetch request will return the string for the selected language.


text:
Q: Equivilant of rails partials for angularjs Is there an equivilant of rails partials for angular js.
Ex: in rails I have my application.html.erb and I can do <%= render 'layouts/_header and it will render that header for every page.
Does angular have similar functionality?

A: Yes, you can do it using ngInclude directive.
See the docs and example here: http://docs.angularjs.org/api/ng.directive:ngInclude
You might also want to checkout angular-ui-router module. It allows you to do nested and parallel views. It is great, flexible, easy to use and well documented.
https://github.com/angular-ui/ui-router


text:
Q: Scrape HTML list structure with PHP I want to scrape a html list structure, so I can save parent and child separately.
Here's the view source of html

Sports Nutrition

Protein

Protein Powder

Whey Protein

Whey Protein Isolate

Pre Workout Supplements

Creatine

Creatine Monohydrate

Amino Acids

Essential Amino Acids

BCAA

Joint Supplements

Curcumin

Curcumin Phytosome

Energy & Endurance

Stimulants

I am using simple HTML DOM for scraping. I am able to get all categories, but I cannot get them in proper the hierarchy.
I also tried the children approach, but that didn't work.
So I am looking for some help in my existing to make it working.
Here's my existing code:
$html= file_get_html($url);

foreach ($html->find('ul.categories_list li') as $link) {
    echo $link->plaintext.'
';
}

A: There is this script which tried to get all elements. This needs to be improved upon:
<?php

require_once("simple_html_dom.php");
$dom = file_get_html("source.php");

getCategory($dom);
print_r($categoryList);

function getCategory(simple_html_dom $dom){
    global $categoryList;

    foreach($dom->find('ul.categories_list li') as $ul){
        //extract the a tag if found
        $categoryName = $ul->find('a',0)->href;
        $categoryLabel = $ul->find('a',0)->innertext;

        $categoryList[] = array(
                                            "categoryName"  =>  $categoryName,
                                            "categoryLabel" =>  $categoryLabel,
                                            );

        //remove a node
        $ul->find('a',0)->outertext = '';

        $string = $ul->innertext;
        if(trim($string) == ''){
            continue;
        }else{
            // die($string);
            $dom2 = str_get_html($string);
            getCategory($dom2);
        }
    }
}

It basically does recursion filling the $categoryList on each call.


text:
Q: Indice fuera de los limites de la matriz - C# Tengo un problema con mi codigo, estoy tratando de hacer comparacion de numeros dentro de un Array, solo que me da un error de Indice fuera de los limites de la matriz. Espero me puedan ayudar, se los agradeceria muchismimo, les dejo mi codigo
if ((array[0]) > (array[1]))
{
    poss = true;
}
else
{
    poss = false;
}
for (int i = 1; i < array.Length; i++)
{
    if ((array[i]) < (array[i + 1])  && poss == true)
    {
        h++;
        poss = false;
    }
    if ((array[i]) > (array[i + 1]) && poss == false)
    {
        h++;
        poss = true;
    }
}

eh = ((n * 2) - 1) / 3;
vh = ((n * 16) - 29) / 90;
zcal = (h - eh) / Math.Sqrt(vh);
MessageBox.Show(zcal.ToString());

Mi error ocurre cuando llega a la siguiente linea de código:
if ((array[i]) < (array[i + 1])  && poss == true)

Mi Array es de 20 números

A: Buenas así como se ha comentado la solución es la siguiente:
reemplazar
for (int i = 1; i < array.Length; i++)

por
for (int i = 0; i < array.Length-1; i++)

Pero me ha parecido correcto explicar el porqué, principalmente para los futuros visitantes.
Bien el error ocurría en tu caso al tener un array de 20 números por ejemplo.
Al llamar la propiedad length de el array esta devuelve la cantidad de datos que contiene, en este caso como ejemplo son 20.
Si recordamos los array contienen múltiples datos que se guardan en diferente dirección dentro de ellos es decir en una posición específica y nos referimos a esa posición por medio de un index que se expresa en números y ahí esta el punto en como se expresan las posiciones del array.
Ya que la propiedad Length  nos devuelve la cantidad de datos podríamos pensar que podemos hacer un ciclo con ese valor para recorrer el array. Por ejemplo:
for (int i = 1; i < array.Length; i++)

Pero como vimos en en esta pregunta eso no funcionará. Ya qué:
En el ejemplo tenemos un array de 20 datos.
Pero no hay una posición de datos 20, pero porqué?
Porque las posiciones de datos en los array como todo en programación empiezan por 0. Exacto el primer dato de nuestro array se guardara en la posición 0. Entonces si tenemos 20 datos y las posiciones de datos empiezan desde 0 tenemos desde las posición 0 hasta la 19 con datos(si contamos desde 0 hasta 19 tenemos un total de 20 números).
Sabiendo esto nuestro ciclo for deberíamos empezar el ciclo en 0 para poder utilizar la variable del ciclo para acceder a los datos:
for (int i = 0; i < array.Length; i++)

var obtenerDatos = array[i];

Y de esa manera obtenemos todos los datos de un array.
También se puede evitar confusiones podemos usar un ciclo especial que es el
foreach.


text:
Q: Upgrading hard drive while saving existing system data, and allowing for a dual OS boot I know this has been asked in individual parts, but I'm looking for a way to do this with the fewest steps and least pain.
I have a laptop with Windows 7, and I want to make a move to a larger hard drive.  My first requirement is to migrate/restore the existing OS and data to the new drive, a question that has been answered here and several other places.
I'm going to buy a HD with enough space to comfortably hold both Windows 7 and a Linux OS, as I want to set up my laptop as a dual boot system.
So once I've backed up my existing system, what's the quickest/best way to get to a new dual boot system? I've found lots of information on backing up and restoring, and also how to install Linux on a machine that already has Windows, but I was wondering if there was any way to do it in fewer steps, or if there was a particular order of doing things that was best.

A: From my experience, your best bet is to restore Windows first, make sure it is running, then install linux, using the linux tools to resize and create the partitions. Windows is very finicky about installation, so installing it second seems like a bad idea.
I'm not sure what steps you would want to cut out. You need to back up windows, as your link describes. You need to restore Windows. You need to install Linux.
I don't know of a way to cut out any of those steps.
If you want to speed up any of it, the slowest part will be copying the image of the windows machine. Make sure you use as fast of a media as possible.


text:
Q: How to interpret the intercept term in a GLM? I am using R and I have been analysing my data with GLM with Binomial link.
I want to know what is the meaning of the intercept in the output table. The intercept for one of my models is significantly different, however the variable is not. What does this mean?
What is the intercept. I don't know if I am just confusing myself but having searched the internet, there is nothing just saying, it is this, take notice of it...or don't.
Please help, a very frustrated student

glm(formula = attacked_excluding_app ~ treatment, family = binomial,
    data = data)
Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.3548   0.3593   0.3593   0.3593   0.3593
Coefficients:
                         Estimate Std. Error z value Pr(>|z|)
(Intercept)                 2.708      1.033   2.622  0.00874 **
treatmentshiny_non-shiny    0.000      1.461   0.000  1.00000

(Dispersion parameter for binomial family taken to be 1)
Null deviance: 14.963  on 31  degrees of freedom
Residual deviance: 14.963  on 30  degrees of freedom
(15 observations deleted due to missingness)
AIC: 18.963
Number of Fisher Scoring iterations: 5

A: It looks to me like there may be some problem with the data. It is odd that the parameter estimate for the coefficient would be 0.000. It looks like both your DV and your IV are dichotomous and that the proportions of your DV do not vary at all with your IV. Is this right?
The intercept, as I noted in my comment (and as @corone 's answer implies) is the value of the DV when the IV is 0. How was your IV coded? As is, though, the fact that the estimate for the coefficient is 0.000 implies that the IV makes no difference.
Therefore, the intercept of 2.708 is the estimated logit of the DV: that is, $\text{log}(\frac{p}{1-p})$ at all levels of the IV.

A: In your case, the intercept is the grand mean of attacked_excluding_app, calculated for all data regardless of treatment.  The significance test in the table of coefficients is testing whether it is significantly different from zero.  Whether this is relevant depends on whether you have some a priori reason to expect it be zero or not.
For instance, imagine you had tested a drug and a placebo for their effect on blood pressure.  For each subject, you record the change in their blood pressure by calculating (pressure after treatment - pressure before treatment) and treat this as the dependent variable in your analysis.  You then find that the effect of treatment (drug vs. placebo) is non-significant but that the intercept is significantly > 0 - this would tell you that on average, your subjects' blood pressure increased between the two measurement times.  This might be interesting and need further investigation.

A: The intercept term is the intercept in the linear part of the GLM equation, so your model for the mean is $E[Y] = g^{-1}(\mathbf{X \beta})$, where $g$ is your link function and $\mathbf{X\beta}$ is your linear model.  This linear model contains an "intercept term", i.e.:
$\mathbf{X\beta} = c + X_1\beta_1+X_2\beta_2+\cdots$
In your case the intercept is significantly non-zero, but the variable is not, so it is saying that
$\mathbf{X\beta} = c \neq 0$
Because your link function is binomial, then
$g(\mu) = \ln\left(\frac{\mu}{1-\mu}\right)$
And so with just the intercept term, your fitted model for the mean is:
$E[Y] = \frac{1}{1+e^{-c}}$
You can see that if $c=0$ then this corresponds to simply a 50:50 chance of getting Y=1 or 0, i.e. $E[Y] = \frac{1}{1+1} = 0.5$
So your result is saying that you can't predict the outcome, but one class (1's or 0's) is more likely than the other.


text:
Q: Fetch multiple images from the server using Django I am trying to download multiple image files from the server. I am using Django for my backend.
Question related to single image has already been answered and I tried the code and it works on single image. In my application, I want to download multiple images in a single HTTP connection.
from PIL import Image

img = Image.open('test.jpg')
img2 = Image.open('test2.png')

response = HttpResponse(content_type = 'image/jpeg')
response2 = HttpResponse(content_type = 'image/png')

img.save(response, 'JPEG')
img2.save(response2, 'PNG')

return response #SINGLE

How can I fetch both img and img2 at once. One way I was thinking is to zip both images and unzip it on client size but I dont think that is good solution. Is there a way to handle this?

A: I looked around and find an older solution using a temporary Zip file on disk: https://djangosnippets.org/snippets/365/
It needed some updating, and this should work (tested on django 2.0)
import tempfile, zipfile
from django.http import HttpResponse
from wsgiref.util import FileWrapper

def send_zipfile(request):
    """
    Create a ZIP file on disk and transmit it in chunks of 8KB,
    without loading the whole file into memory. A similar approach can
    be used for large dynamic PDF files.
    """
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    for index in range(10):
        filename = 'C:/Users/alex1/Desktop/temp.png' # Replace by your files here.

        archive.write(filename, 'file%d.png' % index) # 'file%d.png' will be the
                                                      # name of the file in the
                                                      # zip
    archive.close()

    temp.seek(0)
    wrapper = FileWrapper(temp)

    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=test.zip'

    return response

Right now, this takes my .png and writes it 10 times in my .zip, then sends it.

A: You could add your files/images to a ZIP file and return that one in the response. I think that is the best approach.
Here is some example code of how you could achieve that (from this post):
def zipFiles(files):
    outfile = StringIO() # io.BytesIO() for python 3
    with zipfile.ZipFile(outfile, 'w') as zf:
        for n, f in enumarate(files):
            zf.writestr("{}.csv".format(n), f.getvalue())
    return outfile.getvalue()

zipped_file = zip_files(myfiles)
response = HttpResponse(zipped_file, content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=my_file.zip'

Otherwise (if you don't like ZIP files) you could make individual requests from the client.


text:
Q: Do I always have to include virtual properties when saving data in EF? My user looks like this:
public class User
{
    public User()
    {
        Subscribers = new List<SubscriberNumber>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string Username { get; set; }

    [Required]
    public virtual BusinessNumber BusinessNumber { get; set; }
    public string BusinessName { get; set; }
    public int SubscriberCount { get; set; }

    public List<SubscriberNumber> Subscribers { get; set; }
}

The following call fails due to some undisclosed EntityValidationError:
var user = db.Users.First(s => s.Username == username);
user.BusinessName = "test";
db.SaveChanges();

But either opening up user.BusinessNumber in VS or using the following:
var user = db.Users.Include(s => s.BusinessNumber).First(s => s.Username == username);

gets SaveChanges() to work.  Do I always have to include virtual properties when I'm updating my Users?  This seems cumbersome...

A: The virtual on the properties allows EF to build a proxy. It is not essential to use virtual on regular properties for EF to read and write data. However Virtual is required on the Navigation properties.
By Default Context.Configuration.ValidateOnSaveEnabled = true;
EF will trigger validation on SaveChanges().
So in teh example where the Navigation property is Required (why?) The you must first populate it in the context and POCO. Placing the [required] on the foreign key property rather than the navigation property would be more common.
public class User
{
public User()
{
    Subscribers = new List<SubscriberNumber>();
}

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Username { get; set; }

[Required]
public virtual int BusinessId {get;set;};   // make the foreign key to BusinessNumber required if necessary

[ForeignKey("BusinessId")]
public virtual BusinessNumber BusinessNumber { get; set; }  // this is a nav prop, since it isnt a simple base type

public string BusinessName { get; set; }
public int SubscriberCount { get; set; }

public List<SubscriberNumber> Subscribers { get; set; }
}


text:
Q: How to locate a variable correctly in AT&T assembly? I am practicing to write a bootstrap using assembly (in AT&T syntax, and gnu/gas). The small program is assembled and linked, then copied to the first sector of a virtual disk. BIOS will load it into 0000:7c00, and here comes the problem. The call hello will be translated from call 0010 to call 7c10 during running. But the movw $message, %as doesn't get relocated. The ax is still 0026, not 7c26. The result is that I can't make the Hello World on the screen. Instead, some random data at 0000:0026 will be displayed on the screen.
How can I make it correct during booting? Should I change the asm source code using some directives? Or should I change my link script?
Thank you!
.text
.global     _start
.code16

_start:
movw    %cs, %ax
movw    %ax, %ds
movw    %ax, %es
call    hello
jmp     .

.org    0x10

hello:
movw    $message, %ax
movw    %ax, %bp
movw    $13, %cx
movw    $0x1301, %ax
movw    $0x000c, %bx
movb    $0, %dl
int     $0x10
ret

message:
.ascii  "Hello, World!"

.org    0x01fe
.byte   0x55
.byte   0xaa

I use the following assemble and link scripts
as -o boot.o boot.s
    //generate object code

ld -Ttext 0x0 -e _start -s -o boot.out boot.o
    //relocate .text to 0x0
    //entry is _start

objcopy -O binary -j .text boot.out boot
    //copy .text section to boot

vboxmanage convertfromraw boot boot.vdi --format VDI
    //create vdi for virtual box

A: I see that the main problem is in the way you are compiling your code.
The correct steps to get your code working should be:
as boot.s -c -o boot.o
ld --oformat binary --Ttext 0x7C00 -o boot.bin boot.o

Please note, as others have said, that I'm passing the --Ttext 0x7C00 parameter to ld, to force it relocating your code at that address.
As an additional suggestion, try to structure your code like this:
.text
.global     _start
.code16

_start:
jmp stage1_start

...

stage1_start:

<your bootloader here>

Note that this is compiant with how BIOS code looks at hard drives, since after 2 bytes (the length of the first jump instruction) you should place the Disk Description Table.
Additionally, you can refactor your last instructions in a more as-like syntax like this:
. = _start + 0x0200 - 2
.short 0x0AA55

Where the . variable is the location counter. Look at this page for further information on how this counter works (in the context of ld, not as).
Hope this helps!


text:
Q: Help understanding the migrate wubi documentation? I'm looking at the MigrateWubi page but I'm not sure if I need to change the partition directories to the ones I created, and if so, I'm not too sure which ones I need to change.
Here are the partitions I've made:

Should I just copy and paste: sudo bash wubi-move.sh /dev/sda5 /dev/sda6 into my terminal or something else?
Also, do I enter just this one line or do i need to enter any other commands in there? Thanks!

A: You have /dev/sda6 labeled as / (root) and /dev/sda7 labeled as /home and /dev/sda5 as swap... so the command you'd use is:
sudo bash wubi-move.sh /dev/sda6 /dev/sda5 --home=/dev/sda7

Note, it appears that /dev/sda6 and /dev/sda7 aren't completely empty. This is required by the script before it will let you migrate (the script will warn you and exit if this is the case).
If you don't want to migrate with a separate /home partition, then the command will be (the first positional parameter is the target partition and the second is the swap partition):
sudo bash wubi-move.sh /dev/sda6 /dev/sda5

Don't worry too much about it - because the script checks the partitions and won't let you migrate if you get the order wrong. You can also run it with the --check-only argument and it will just perform the checks without making any changes. (Even without that it will prompt you to confirm before making changes.)
PS. that 691 GiB that's unallocated can't be used unless you first increase the extended partition (/dev/sda4) to include it. Once you've done that you can create logical partitions.


text:
Q: Mailboxer gem's mailer results in ActionController::UrlGenerationError when no locale is passed I am trying to use the Mailboxer gem to get a user-to-user messaging system in my Rails 4 app. However, I am getting the following error in my browser when sending messages:
ActionController::UrlGenerationError in Conversations#create

the culprit line is the following mailer template (new_message_email.html.erb):
Visit <%= link_to "this page", root_url %> and go to your inbox for more info.

and the reason is
No route matches {:action=>"index", :controller=>"rooms"} missing required keys: [:locale]

This is because my entire app's routes require a locale. My routes.rb looks like this:
Rails.application.routes.draw do
  get '' => redirect("/#{I18n.default_locale}")
  scope "/:locale", locale: /en|ja|ko/ do
    root 'rooms#index'
    resources :rooms
    # ... All my other routes here ...
  end
end

Interestingly, the console has the following error (which differs from the one in the browser):
ActionView::Template::Error (No route matches {:action=>"index", :controller=>"rooms"} missing required keys: [:locale]):
    14:       </p>
    15:     </blockquote>
    16:     <p>
    17:       Visit <%= link_to "this page", root_url %> and go to your inbox for more info.
    18:     </p>
    19:   </body>
    20: </html>

but I assume the template is not the problem - the real issue is that there's some previous call that is occurring that requires a locale to be passed, so root_url fails as it doesn't know which locale to use.
I am already passing the following in my application_controller.rb:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :set_locale

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def default_url_options(options = {})
    { locale: I18n.locale }.merge options
  end
end

Does anyone know how I can fix this or how I can pass the locale to the mailer's root_url?
Also, please let me know if more code is required.
Thanks in advance :)

A: Bah, silly mistake! Specifying the locale seems to make it work:
<%= link_to "this page", root_url(locale: :en) %>

although ideally this setting should depend on the user's preferred language.


text:
Q: Parse Hebrew XML Hello I'm having problems parsing hebrew xml file.
I use file_get_contents to read the file, and when I display it I get weird charaters. I searched all over the internet and found many functions and none works.
Input:

<ROW>
  <C0>1</C0>
  <טבלה>טבלת ישובים</טבלה>
  <סמל_ישוב>967</סמל_ישוב>
  <שם_ישוב>אבו ג'ווייעד )שבט(</שם_ישוב>
  <סמל_נפה>62</סמל_נפה>
  <שם_נפה>באר שבע</שם_נפה>
  <סמל_לשכה_מנא>62</סמל_לשכה_מנא>
  <לשכה>באר שבע</לשכה>
  <סמל_מועצה_איזורית>0</סמל_מועצה_איזורית>
  <שם_מועצה> </שם_מועצה>
</ROW>

Output:
> ROWDATA>

> ROW>
> C0>1
<äìáè\>íéáåùé úìáè<äìáè>
<áåùé_ìîñ967
<áåùé_íù\>)èáù( ãòééåå'â åáà<áåùé_íù>
<äôð_ìîñ62
<äôð_íù\>òáù øàá<äôð_íù>
<àðî_äëùì_ìîñ62
<äëùì\>òáù øàá<äëùì>
<úéøåæéà_äöòåî_ìîñ0
<äöòåî_íù\> <äöòåî_íù>
\> ROW>

The code I'm using is:
$xml = file_get_contents('hebrew.xml');
echo hebrevc($xml);

I tried with outputing header before:
header('Content-Type: text/html; charset=utf-8');

I also tried with utf8_encode and I get all the the time wrong charachers.
Please help me out :/

A: Try this:
 $xml = file_get_contents('hebrew.xml');
 mb_convert_encoding($xml, 'UTF-16LE', 'UTF-8');
 echo $xml;


text:
Q: apply multiple formula to create a column in dataframe i tried to create new column in a dataframe using different equations and inputs from other column in the dataframe. the equation i want to apply will also slightly differs conditioned on another column. here is the dummy dataframe
   set.seed(123)
   df <-
    data.frame(
    N = (c(0,0,rep(10,18))),
    I0 = runif(20, 0,10),
    Dt = c(1:20),
    Isolator = rep(1:10,each=2)
  )

I want to create new column name Pcol using this equation  1-exp(-(x)*((df$I0/df$N)*df$Dt))
and x variables changes based on Isolator. I managed to create column Pcol using ifelese() and mutate() based on isolators but the input is not taken from the same row. to illustrate
df1<-mutate(df, Pcol = ifelse(Isolator %in% 1:4, 1-exp(-(0.5])*((df$I0/df$N)*df$Dt)),
                                  ifelse(Isolator %in% 5:7, 1-exp(-(0.7)*((df$I0/df$N)*df$Dt)),
                                         ifelse(Isolator %in% 8:10, 1-exp(-(0.9)*((df$I0/df$N)*df$Dt)), NA))))

I also calculated Pcol seperately by subseting dataframe based on isolators
col1<- df %>% filter(Isolator <= 4)
col2<- df %>% filter(Isolator >= 5 & Isolator < 8)
col3<- df %>% filter(Isolator >=9 )
Pcol1<-1-exp(-(0.5)*((col1$I0/col1$N)*col1$Dt))
Pcol2<-1-exp(-(0.7)*(((col2$I0/col2$N)*col2$Dt))
Pcol3<-1-exp(-(0.9)*((col3$I0/col3$N)*col3$Dt))

and the Pcol in dataframe differs drom Pcol calculated from subset group. i think ifelse() apply in the dataframe taking in input wrongly when it calculate Pcol but i don't know how to fix it or maybe there is a simpler way to apply equations into dataframe
Please help! thank you

A: Apply group of functions are normally used for iterative calculations or for manipulating lists, whereas,
Will this do?
df %>% mutate(Pcol = case_when(Isolator %in% 1:4 ~ 0.5,
                               Isolator %in% 5:7 ~ 0.7,
                               TRUE ~ 0.9),
              Pcol = 1-exp(-(Pcol)*((I0/N)*Dt)))

    N        I0 Dt Isolator      Pcol
1   0 2.8757752  1        1 1.0000000
2   0 7.8830514  2        1 1.0000000
3  10 4.0897692  3        2 0.4585288
4  10 8.8301740  4        2 0.8289903
5  10 9.4046728  5        3 0.9047422
6  10 0.4555650  6        3 0.1277415
7  10 5.2810549  7        4 0.8425062
8  10 8.9241904  8        4 0.9718350
9  10 5.5143501  9        5 0.9690084
10 10 4.5661474 10        5 0.9590868
11 10 9.5683335 11        6 0.9993686
12 10 4.5333416 12        6 0.9778076
13 10 6.7757064 13        7 0.9979002
14 10 5.7263340 14        7 0.9963455
15 10 1.0292468 15        8 0.7507959
16 10 8.9982497 16        8 0.9999976
17 10 2.4608773 17        9 0.9768357
18 10 0.4205953 18        9 0.4940738
19 10 3.2792072 19       10 0.9963296
20 10 9.5450365 20       10 1.0000000

Your manual calculations (using subsets)
col1<- df %>% filter(Isolator <= 4)
col2<- df %>% filter(Isolator >= 5 & Isolator < 8)
col3<- df %>% filter(Isolator >=8 )
Pcol1 <- 1-exp(-(0.5)*((col1$I0/col1$N)*col1$Dt))
Pcol2 <- 1-exp(-(0.7)*((col2$I0/col2$N)*col2$Dt))
Pcol3 <- 1-exp(-(0.9)*((col3$I0/col3$N)*col3$Dt))

Pcol2

Pcol <- c(Pcol1, Pcol2, Pcol3)

df %>% mutate(Pcol = case_when(Isolator %in% 1:4 ~ 0.5,
                               Isolator %in% 5:7 ~ 0.7,
                               TRUE ~ 0.9),
              Pcol = 1-exp(-(Pcol)*((I0/N)*Dt))) -> df1

Pcol - df1$Pcol

 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0


text:
Q: Custom tab item I need to add a custom tab item into my TabbedPage. That shouldn't be a page but an overlay view. It is "More" item for the bottom menu opening a more items menu over the currently shown page.
So far I found the following solution:
 protected override void OnCurrentPageChanged()
 {
     base.OnCurrentPageChanged();

     if (this.isInitialized)
     {
         if (CurrentPage.Title == "More")
         {
             CurrentPage = this.lastSelectedPage;
         }
     }

     this.lastSelectedPage = CurrentPage;
 }

It's enough to prevent opening the corresponding fake page. After this I need to show an overlay view and have no item how to do it from the tabbed page.
Another solution I'm working out now is to write a custom renderer for my tabbed page and manage all the custom work there. The question in this case is how to show my custom view over the existing content. I tried AddView (iOS) in the renderer but getting runtime exception.
public override void ItemSelected(UITabBar tabbar, UITabBarItem item)
{
    base.ItemSelected(tabbar, item);

    var view = new UILabel()
    {
        Text = "Test"
    };

    View.Add(view);
}


text:
Q: Multiline comment with QXmlStreamWriter I am trying comment a multiline section of xml to an output file using qxmlstreamwriter. I am in a loop, iterating through my nested structures, and if a structure is noted as "isCommented" then I need to insert a "< ! - -" (without spaces)
then continue writing the XML form of the output. When I get to the end of that structure I need to insert the end comment: "-->".
The qxmlstreamwriter::writeCharacters(QString) method won't suffice since it picks out the special characters such as "<" and re-interprets them. I have already handled eradicating cases for nested comments... so that isn't an issue (the inner and outer loop are guaranteed to not both be commented) Any ideas for an alternate solution? Below is an example of my code:
...
QXmlStreamWriter writer(&myFile)

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

  if (bigStruct.at(i)->isCommented){
    //start comment sequence
    //insert "<!--"
  }

  writer.writeStartElement("BigStruct");

  for (int j = 0; j < smallerStruct; j++){
      if (smallerStruct.at(i)->isCommented){
        //start comment sequence
        //insert "<!--"
      }

      writer.writeStartElement("SmallerStruct");

      writer.writeTextElement("Stuff", "blah");
      writer.writeTextElement("More Stuff", "blah blah blah");

      writer.writeEndElement();

      if (smallerStruct.at(i)->isCommented){
        //end comment sequence
        //insert "-->"
      }
  }

  writer.writeEndElement();

  if (bigStruct.at(i)->isCommented){
     //endcomment sequence
     //insert "-->"
  }
}

...

An example XML output may look like
<BigStruct>
 <SmallerStruct>
    <Stuff>blah</Stuff>
    <More Stuff>blah blah blah</More Stuff>
 </SmallerStruct>
 <!--
  <SmallerStruct>
    <Stuff>blah</Stuff>
    <More Stuff>blah blah blah</More Stuff>
 </SmallerStruct>
 -->
</BigStruct>
<!--
<BigStruct>
    <SmallerStruct>
    <Stuff>blah</Stuff>
    <More Stuff>blah blah blah</More Stuff>
 </SmallerStruct>
</BigStruct>
-->

The writeComment() was my first attempt to comment, however, it only writes a single line. Of course, I could create a large string with '\n' characters where necessary, but the code necessary to create that block would escape the program flow of my loops. What I need is a slick way of essentially having a writer.startComment() and writer.endComment()... such that I can specify the start and end of a comment, after other xml has been written. Therefore I could write XML using my qxmlstreamwriter inside a comment.
Thanks for your time.

A: I don't think that's possible, looking at the QXmlStreamWriter API. You could use another QXmlStreamWriter on a temporary QByteArray, and write the byte array's content as comment to the original writer.


text:
Q: error when reading headers from a file - requests hello I am trying to read the headers of a file to use the query in the requests, I read that to send the headers I could send a dictionary. everything seems to be correct but i always get an error
import requests
import json

url = 'http://192.168.98.106/login'

with open('data.txt.bak') as f:
   data = json.loads(f.read())

headers_dict = {

    "Host": "192.168.98.106",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0",
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "en-US,en;q=0.5",
    "Accept-Encoding": "gzip, deflate",
    "Content-Type": "application/json"
}

def get_headers_as_dict(headers: str) -> dict:
   dic = {}
   for line in headers.split("\n"):
       if line.startswith(("GET", "POST")):
           continue
       point_index = line.find(":")
       dic[line[:point_index].strip()] = line[point_index+1:].strip()
   return dic

with open('headers.txt') as f:
    headers_file = f.read()

print(get_headers_as_dict(headers_file))
print(headers_dict)

proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
r = requests.post(url, json=data, headers=headers_file, proxies=proxies)

error:
File "/home/user/documents/test.py", line 44, in <module>
    r = requests.post(url, json=data, headers=headers_file, proxies=proxies)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 528, in request
    prep = self.prepare_request(req)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 456, in prepare_request
    p.prepare(
  File "/usr/lib/python3/dist-packages/requests/models.py", line 317, in prepare
    self.prepare_headers(headers)
  File "/usr/lib/python3/dist-packages/requests/models.py", line 449, in prepare_headers
    for header in headers.items():
AttributeError: 'str' object has no attribute 'items'

Thank you so much


text:
Q: 17.10 Frequent Mouse Battery Low Notifications For more than 3 months now I get frequent notifications stating:

Mouse battery low
  Wireless mouse is low in power (10%)

I use a Logitech M705 mouse with Unifying Receiver in my living room with a tiny desktop which is connected to my tv. It appears that these notifications seem to appear most frequent when wireless reception is not optimal (although distance is only 2,5m). They appear 4-5 times successively, reappearing rapidly after dismissing them.
If batteries are indeed low they should be completely dead by now.
Does anyone know how I can turn this off?
This question is different as this has been going on for months now, previous question was about a mouse running on 0% batteries and notifications appearing about that for a few days. Mine are at 10% now, for at least 3 months. There's nothing I have to do te reproduce this problem as it happens automatically all the time.
I want to know how I can turn this off as there's no solution offered.
The suggestions from the answers to the linked question are for the battery of a laptop, not for the mouse and therefore it doesn't work:
Jetblackster says: "For ubuntu 17.10 go to org --> gnome --> settings-daemon --> plugins --> power Alter the "percentage-low" setting to what you want. I changed from 10% to 4%."
See this post about laptop battery notifications (not what I need) How to change critically low battery value?


text:
Q: How do you enable UITableViewCell reorder without removing control with "setEditing " method? When I use  [tableview setEditing:YES animated:YES]; to enable UITableViewCell reorder, the remove control appears too. How can I prevent that ?

A: Implement -tableView:editingStyleForRowAtIndexPath: in the table view delegate and return UITableViewCellEditingStyleNone.

A: Add this method to youc code:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return NO;
}


text:
Q: R Complex Association Plots I'm not used to plotting with R, so bear with me.
I have three categorical independent variables-- price before, price after, and volume band-- and one categorical dependent variable.
I want to plot an association plot for counts of each factor in the dependent variable across the combinations of the three dependent ones.
Can someone point me to any resources that explain how to do this better than the vcd package documentation? Or give me a hint how to begin?
Thank you in advance.


text:
Q: Return a specified data at row "index" from an SQLite query I have this query:
Cursor cur = db.query(true, TABLE_COORD, columns_descri,null, null, null, null, null, null);

And i want it to return the data of column_descri at row "index". "Index" is a paramater in my function:
 public void showOverlay (OverlayItem overlay, int index)
        {
        db = openHelper.getWritableDatabase();

        String[] columns_descri = new String[] {COL_DESCRI};

        Cursor cur = db.query(true, TABLE_COORD, columns_descri,null, null, null, null, null, null);
        if (cur.moveToPosition(index)) {
         //show an AlertDialog with description of row index

How can i acheive that ?
Thank you for helping.

A: You can try this:
String res = cur.getString(cur.getColumnIndex(COL_DESCRI));
cur.close();


text:
Q: THE FASTEST Smarty Cache Handler Does anyone know if there is an overview of the performance of different cache handlers for smarty?
I compared smarty file cache with a memcache handler, but it seemed memcache has a negative impact on performance.
I figured there would be a faster way to cache than through the filesystem... am I wrong?

A: I don't have a systematic answer for you, but in my experience, the file cache is the fastest.  I should clarify that I haven't done any serious performance tests, but in all the time I've used Smarty, I have found the file cache to work best.
One this that definitely improves performance is to disable checking if the template files have changed.  This avoids having to stat the tpl files.

A: File caching is ok when you have a single server instance or using shared drive (NFS) in a server cluster, but when you have a web server cluster (two or more web servers serving the same content), the problem with file based caching is not sync across the web servers. To perform a simple rsync on the caching directories is error prone. May work flawlessly for awhile but not a stable solution. The best solution for a cluster is to use distributed caching, that is memcache, which is a separate server running a memcached instance and each web server has PHP Memcache installed. Each server will then check for the existent of a cached page/item and if exists pulls from memcache otherwise will generate from the database and then save into memcached. When you are dealing with clusters, you cannot skimp on a good caching mechanism. If you are dealing with clusters, then your site already has more traffic (or will be) for a single server to handle.
There is beginners level cluster environment which can be implemented for a relative low cost. You can set up two colocated servers (nginx load balancer and a memcached server), then using free shared web hosting, you create an account of the same domain on those free hosting accounts and install your content. You configure your nginx load balancer to point to the IP addresses of the free web hosts. The free web hosts must have php5 memcache installed or the solution will not work.
Then you set you DNS for the domain with the registrar to point the NGINX IP (which would be a static ip if you are colocating). Now when someone access your domain, nginx redirects to one of your web server clusters located on the free hosting.
You may also want to consider a CDN to off load traffic when serving the static content.


text:
Q: Como enviar dados via formulário para arquivo php e retornar o resultado em um campo html Queria enviar os dados via formulário, que seria usado na minha classe php, e com o javascript capturar esse resultado e jogar no meu campo em html, com o on click do js. Mas não estou conseguindo com "action", porque ele faz a requisição para outra página, no caso meu arquivo .php. E eu não recebo o retorno no meu arquivo html. Qual a melhor forma de resolver isso?
Tenho o seguinte formulário:
<form  class="form" method="GET">
     CEP: <input type="text" name="cep" placeholder="Insira o cep" required/>
     <input class="submit" type="submit" value="Buscar"/>
</form>

E um campo para receber os dados em php:

No arquivo .js:
$(document).ready(function(){
     $(document).on('click', '.submit', function(){
          $.post('testephp.php', function(retorna){
          $(".data").html(retorna);
          });
     });
});

Classe php:
Class Controller{
    public $cep;

    public function ConsultaViaCEP(){
        $cep = Controller::setFormCEP();
        $cep = preg_replace("/[^0-9]/", "", $cep);
        $url = file_get_contents("http://viacep.com.br/ws/$cep/json/");
        $json = json_decode($url, true);
        return $json;
    }
    [...getters and setters]

    echo Controller::getCEP()."
";
    echo Controller::getLogradouro()."
";
    echo Controller::getComplemento()."
";
    echo Controller::getBairro()."
";
    echo Controller::getLocalidade()."
";
    echo Controller::getUF()."
";
}

A: Se a questão for como entendi, você pode usar preventDefault para impedir que a página seja submetida e rode apenas no JS.
$(document).on('click', '.submit', function( e ){
     e.preventDefault();

     $.post('testephp.php', function(retorna){
          $(".data").html(retorna);
     });
});


text:
Q: Building GraphQL services in isolation with apollo-federation I'm currently trying to test 1 service's graphql endpoint that will eventually be apart of an apollo-federation/gateway graphql server. This service will extend a type in an existing service in the existing federated graph.
If I want to test my service in isolation with the apollo-federation & gateway, is there a way to do that while still using @extends and @external in my graphql schema? Currently the gateway throws: UnhandledPromiseRejectionWarning: Error: Unknown type: "SomeTypeInAnotherServer", which makes sense as there's no type to extend, but can I ignore this validation somehow?

A: as @xadm posted in a comment, you can achieve this with https://github.com/xolvio/federation-testing-tool which solves my problem.

A: Your question looks like you're trying to do development, but the answer you gave looks like you're specifically doing testing. I don't know if that's where you ended up because of tooling, or if that was your actual question, but this is the answer I have for people doing development:
If you're just running one of the services, you can still make queries against it, just do so in the way ApolloGateway would. Say for example, you have a person-service and a place-service, and People can visit many places:
Person Service
type Person @key(fields: "id") {
  id: ID!
  name: String
}

type Query {
  person(id: ID): Person # Assuming this is the only entry-point
}

Place Service
type Place {
  id: ID!
  name: String
}

extend type Person @key(fields: "id") {
  id: ID!
  placesVisited: [Place]
}

Now you can make the following query to the place-service:
query ($_representations: [_Any!]!) {
  _entities(representations:$_representations) {
    ... on Person {
      id
      placesVisited {
        id
        name
      }
    }
  }
}

and here is your input:
{
  "_representations": [{
    "__typename": "Person",
    "id": "some-id-of-some-person"
  }]
}


text:
Q: ASP NET Core Insert Model With Related Data I have a Model as Below:
class ModelA {
    public int ID { get; set; }
    public string PersonName { get; set;}
    ICollection<ModelB> TaskList { get; set; }
}

class ModelB {
    public int ID { get; set; }
    public string TaskDescription { get; set; }
    public int ModelAID { get; set; }
    public ModelA Person { get; set; }
}

In the controller, I use the following code to Add a new row to ModelA with a list of rows ModelB:
IEnumerale<ModelB> BList = ....;
ModelA row = new ModelA() { PersonName = 'John' };
foreach (bRow in BList) {
    row.TaskList.add(bRow);
}

From the above code, I got an error of "row.TaskList.add(bRow)" line that the error messages say cannot add row into null object.
I just want to ask is it a incorrect way to create a new row with related data?  How can I complete the task without error?  I don't want to split the process into 2 step, first create a row of ModelA then insert the list of ModelB by different method.
Thank you!
Wilson

A: to avoid the exception change your class a little...
class ModelA {

    public ModelA()
    {
        TaskList = new Collection<ModelB>();
    }

    public int ID { get; set; }
    public string PersonName { get; set;}
    ICollection<ModelB> TaskList { get; set; }
}


text:
Q: Передача строки в функцию Как можно передать строку в функцию так, чтобы манипуляции с этой строкой внутри функции не меняли ее значения при выходе из функции?

A: В языке С нет типа "строка". Я не знаю, что имели в виду Вы, но при работе со строками, в качестве параметра функции передаётся указатель тип char *. В соответствии с общей идеологией языка С этот указатель не меняется. Но Вы легко можете, находясь внутри функции, изменить (испортить?) ту память, на которую указывает этот указатель.
Если Вы не собираесь менять содержимое памяти, переданной в функцию по указателю, то проще всего гарантировать себя от проблем так:
void function(char *str) {

    char *cp;

    cp = malloc(strlen(str)+1);   // Выделяем память под копию строки
    strcpy(cp, str);              // Копируем содержимое строки
    // Здесь что-то делаем с полученной строкой
    free(cp);                     // Освобождаем занятую память
    return;
}


text:
Q: Using a string as a dictionary's index I have a large dictionary (originally a json), something like this:
dictionary = {
    "Thing1": {
        "Thing1.1": {
            "Thing1.1.1": "Text",
            "Thing1.1.2": "Text",
            "Thing1.1.3": "Text"},
        "Thing1.2": [{
            "Thing1.2.1.1": "Text",
            "Thing1.2.1.2": "Text",
            "Thing1.2.1.3": "Text"},
            {
            "Thing1.2.2.1": "Text",
            "Thing1.2.2.2": "Text",
            "Thing1.2.2.3": "Text we're interested in"}
        ],
        "Thing1.3": {
            "Thing1.3.1": "Text",
            "Thing1.3.2": "Text",
            "Thing1.3.3": "Text"}
    },
    "Thing2": {
            "Thing2.1": {
                "Thing2.1.1": "Text",
                "Thing2.1.2": "Text",
                "Thing2.1.3": "Text"},
            "Thing2.2": {
                "Thing2.2.1": "Text",
                "Thing2.2.2": "Text",
                "Thing2.2.3": "Text"},
            "Thing2.3": {
                "Thing2.3.1": "Text",
                "Thing2.3.2": "Text",
                "Thing2.3.3": "Text"}
        },
    "Thing3": {
        "Thing3.1": {
            "Thing3.1.1": "Text",
            "Thing3.1.2": "Text",
            "Thing3.1.3": "Text"},
        "Thing3.2": {
            "Thing3.2.1": "Text",
            "Thing3.2.2": "Text",
            "Thing3.2.3": "Text"},
        "Thing3.3": {
            "Thing3.3.1": "Text",
            "Thing3.3.2": "Text",
            "Thing3.3.3": "Text"}
    }
}

And, having automated some things, I have some keys the values of which I'm interested in, in a string as such:
key = '["Thing1"]["Thing1.2"][1]["Thing1.2.2.3"]''
and I'd like to be able to call the value for which I have the key as if it was the following:
value = dictionary["Thing1"]["Thing1.2"][1]["Thing1.2.2.3"]
I have tried using exec, and formatting everything neatly using f-strings, however that's horrible and it does give me some trouble of its own, especially if I use it in functions due to the way it handles global and local variables.
Edit: I've changed the dictionary and key to represent what it looks more like in the real case: This is a dictionary of arbitrary depth that may contain lists embedded within it e.g. 'Thing1.2'.

A: If you want to give "1.2.3" and get the item you want from the list you can use this code:
keys = "1.2.3".split(".")
value = dictionary["Thing" + keys[0]]["Thing" + keys[0] + "." + keys[1]]["Thing" + keys[0] + "." + keys[1] + "." + keys[2]]

If you want, you can get it from your key1 variable:
key1 = '["Thing1"]["Thing1.2"]["Thing1.2.3"]'
keys = key1[key1.rfind("Thing") + 5: -2].split(".")
value = dictionary["Thing" + keys[0]]["Thing" + keys[0] + "." + keys[1]]["Thing" + keys[0] + "." + keys[1] + "." + keys[2]]

A: As I understand the question, you will always receive the three keys in a string as you showed above, if not please correct me. In that case, I have find the following solution:
text = '["Thing1"]["Thing1.2"]["Thing1.2.3"]'
keys = [eval(i) for i in text.replace("[", "").split("]")[:-1]]
target = dictionary[keys[0]][keys[1]][keys[2]]

Being the variables:
keys = ['Thing1', 'Thing1.2', 'Thing1.2.3']
target = "Text we're interested in"

Edit: You can also do this if you don´t want to use exec or eval:
keys = text.replace("[", "").replace('"', "").split("]")[:-1]
target = dictionary[keys[0]][keys[1]][keys[2]]

If u have a variable depth, you can replace the last lines with:
target = dictionary
for k in keys:
    target = target[k]

A: Let's assume that the depth of the nested dictionaries is unknown. In that case we need a loop to navigate it. You can use a regular expression to isolate the embedded keys. Something like this:
import re

dictionary = {
    "Thing1": {
        "Thing1.1": {
            "Thing1.1.1": "Text",
            "Thing1.1.2": "Text",
            "Thing1.1.3": "Text"},
        "Thing1.2": [{
            "Thing1.2.1.1": "Text",
            "Thing1.2.1.2": "Text",
            "Thing1.2.1.3": "Text"},
            {
            "Thing1.2.2.1": "Text",
            "Thing1.2.2.2": "Text",
            "Thing1.2.2.3": "Text we're interested in"}
        ],
        "Thing1.3": {
            "Thing1.3.1": "Text",
            "Thing1.3.2": "Text",
            "Thing1.3.3": "Text"}
    },
    "Thing2": {
        "Thing2.1": {
            "Thing2.1.1": "Text",
            "Thing2.1.2": "Text",
            "Thing2.1.3": "Text"},
        "Thing2.2": {
            "Thing2.2.1": "Text",
            "Thing2.2.2": "Text",
            "Thing2.2.3": "Text"},
        "Thing2.3": {
            "Thing2.3.1": "Text",
            "Thing2.3.2": "Text",
            "Thing2.3.3": "Text"}
    },
    "Thing3": {
        "Thing3.1": {
            "Thing3.1.1": "Text",
            "Thing3.1.2": "Text",
            "Thing3.1.3": "Text"},
        "Thing3.2": {
            "Thing3.2.1": "Text",
            "Thing3.2.2": "Text",
            "Thing3.2.3": "Text"},
        "Thing3.3": {
            "Thing3.3.1": "Text",
            "Thing3.3.2": "Text",
            "Thing3.3.3": "Text"}
    }
}

key = '["Thing1"]["Thing1.2"][1]["Thing1.2.2.3"]'

list_ = re.findall(r'\["*(.*?)"*\]', key)

d = dictionary

for k in list_:
    if k.isdigit() and isinstance(d, list):
        d = d[int(k)]
    else:
        d = d.get(k)
    if d is None:
        break

print(d)

Output:
Text we're interested in


text:
Q: Windows 7 PC very slow when accessing a MYSQL DB on a windows server machine I am testsing on Windows 7 in preparation for our departments upgrade from XP to WIn 7.
All nine XP PCs access a MySQl DB on a Windows Server machine with no problems.
However on the Windows 7 PC the SQL queries run very slow.
As a comparison running the same SELECT on XP and win 7.
SELECT * FROM table_name;

XP 3414 rows returned in 0.06 sec
WIN 7  3414 rows returned in 5.26 sec
Different applications have the same problem ( Python apps, VB6 .exes, and various mysqlDB GUIs )
All the PCs ( XP and Win7 ) have McAfee but the settings cannot be changed.
Does anyone have any suggestions on how to improve the performance?

A: Have you tried running the application on compatibility mode and selecting windows xp ?
If it improves performance then that might be a solution, if not it might just be the
different way the networks stack works in windows 7 compared to xp.
Try moving the db from the 2003 pc to a windows server 2008 box.

A: Try to uncomment (remove '#') the line:
127.0.0.1 localhost

In the C:\Windows\System32\drivers\etc file (anti-virus may block it - if so, turn it off for a second).

A: It may have other causes but for me setting on my.ini the param
mysqld skip-name-resolve
solved the problem more than one time.


text:
Q: Cannot retrieve value on rowdeleting in GridView I  have a problem for retrieving values for deleting records.
I'm using OnRowDeleting in a gridview with templatefields, and I can't retrive record selected value for deleting, this is my grid:
<asp:GridView ID="gvw_Cli_Emp_EmpData" runat="server" AutoGenerateColumns="false"
        CssClass="mGrid" PagerStyle-CssClass="pgr" Width="50%" AutoGenerateDeleteButton="True"
        AlternatingRowStyle-CssClass="alt" Font-Size="Small" OnRowDeleting="Borrando">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <a href="#" onclick="window.open('Clientes_Empleados_Detalle.aspx?cliCod= <%#Eval("ClienteCodigo1").ToString()
                        + "&EmpNom=" + Eval("Empleado1").ToString()
                        + "&EmpCod=" + Eval("IdCliEmp").ToString()
                        + "&idDepart=" + Eval("IdDepartamento").ToString()
                        + "&Depart=" + Eval("Departamento1").ToString()
                        + "&EmpNiv=" + Eval("NivelAcceso1").ToString()
                        %> ','PrintMe','height=500px,width=800px,scrollbars=1');">Editar
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="CLIENTE">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_CliCod" runat="server" Text='<%# Eval("ClienteCodigo1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CODIGO">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpId" runat="server" Text='<%# Eval("IdCliEmp") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="EMPLEADO">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpNom" runat="server" Text='<%# Eval("Empleado1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ID DEP">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_DepId" runat="server" Text='<%# Eval("IdDepartamento") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="DEPARTAMENTO">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpDep" runat="server" Text='<%# Eval("Departamento1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="NIVEL">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpNiv" runat="server" Text='<%# Eval("NivelAcceso1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>

And for delete:
protected void Borrando(object sender, GridViewDeleteEventArgs e)
{
    string cell = gvw_Cli_Emp_EmpData.Rows[e.RowIndex].Cells[0].Text; //this retuns me ""
    int EmpCliCod = Convert.ToInt32(cell);

    DialogResult dialogResult = MessageBox.Show(new Form { TopMost = true }, "Delete?", "Confirma", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
        cliEmpBL.clientesEmpleados_SupEmpleado(EmpCliCod); //here execute deletion record from my datalayer
        Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('Deleted!');", true);
    }
    else if (dialogResult == DialogResult.No)
    { }
}

So, as you can see returns me "".
I have tried resolve this, using:
        System.Windows.Forms.Label EmpId = e.Item.FindControl("lbl_CliEmp_CliCod") as System.Windows.Forms.Label;
    string val = EmpId.Text;

But same result, any idea?
please, I hope anyone can help me.
best regards

A: Try implementing below example, you will get id for selected row
<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ClienteCodigo1")%>'>Delete</asp:LinkButton>

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
    {
      int ID = Convert.ToInt32(e.CommandArgument);
      //now perform the delete operation using ID value
    }
}

A: Thanks Patrik your solution helped me.
<asp:GridView ID="gvw_CliEmp_EmpData" runat="server" AutoGenerateColumns="false"
        CssClass="mGrid" PagerStyle-CssClass="pgr" Width="50%"
        AlternatingRowStyle-CssClass="alt" Font-Size="Small"
        OnRowCommand="gvw_CliEmp_EmpData_RowCommand" OnRowDeleting="gvw_CliEmp_EmpData_RowDeleting">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <a href="#" onclick="window.open('Clientes_Empleados_Detalle.aspx?cliCod= <%#Eval("ClienteCodigo1").ToString()
                        + "&EmpNom=" + Eval("Empleado1").ToString()
                        + "&EmpCod=" + Eval("IdCliEmp").ToString()
                        + "&idDepart=" + Eval("IdDepartamento").ToString()
                        + "&Depart=" + Eval("Departamento1").ToString()
                        + "&EmpNiv=" + Eval("NivelAcceso1").ToString()
                        %> ','PrintMe','height=500px,width=800px,scrollbars=1');">Editar
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="CLIENTE">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_CliCod" runat="server" Text='<%# Eval("ClienteCodigo1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CODIGO">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpId" runat="server" Text='<%# Eval("IdCliEmp") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="EMPLEADO">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpNom" runat="server" Text='<%# Eval("Empleado1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ID DEP">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_DepId" runat="server" Text='<%# Eval("IdDepartamento") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="DEPARTAMENTO">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpDep" runat="server" Text='<%# Eval("Departamento1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="NIVEL">
                <ItemTemplate>
                    <asp:Label ID="lbl_CliEmp_EmpNiv" runat="server" Text='<%# Eval("NivelAcceso1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete"
                        CommandArgument='<%#Eval("IdCliEmp")%>'>Eliminar
                    </asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>

and code behind:
#region ==== BORRAR REGISTROS DEL INGRESO ====

protected void gvw_CliEmp_EmpData_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        int EmpCliCod = Convert.ToInt32(e.CommandArgument);

        DialogResult dialogResult = MessageBox.Show(new Form { TopMost = true }, "Eliminar?", "Confirmar", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            cliEmpBL.clientesEmpleados_SupEmpleado(EmpCliCod); //eliminar desde DL
            Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('Eliminado!');", true);
        }
        else if (dialogResult == DialogResult.No)
        { }

        gvw_CliEmp_EmpData.DataSource = null;
        gvw_CliEmp_EmpData.DataBind();
        gvw_CliEmp_EmpData.DataSource = cliEmpBL.clientes_Empleados_cons_EmpxCliente(lbl_CliEmp_CliCod.Text);
        gvw_CliEmp_EmpData.DataBind();
    }

}

protected void gvw_CliEmp_EmpData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//this is because grid fired event RowDeleting which wasn't handled
}
#endregion


text:
Q: Catch a Wifi Authentication on Windows Mobile with C# I would like to know if can be possible to catch a wifi authentication on windows mobile and use in NetworkCredential at my app based on windows form and c#.
My client want this feature because I put one login from app and has one another login to wifi connnectio.
More details: I working on Intermec CN3 with Windows Mobile 6.1 and .NET Compact Framework 3.5.
Can suggest something?


text:
Q: cannot find getActivity() and several errors after migrating to androidx error: cannot find symbol class Fragment
error: method does not override or implement a method from a supertype
error: cannot find symbol method getActivity()
error: cannot find symbol variable super
error: cannot find symbol method getString(int)

A: I think the root problem is the compiler cannot find the Fragment class. The getActivity() and getString(int) exist in the Fragment class. So you try to import the Fragment class. The problems will be solved. I hopes it helps!


text:
Q: BGP route selection So given the information AS A is a customer of AS B and AS E, and A is peering with AS C and AS D;
From what I understand, in the first step, we have to discard the routes with the lower local preferences. In this case, A is a customer of B, then that path has a greater local preference or lower local preference?
Below I attach the whole exercise in case I missing some important data:

A:
From what I understand, in the first step, we have to discard the
  routes with the lower local preferences.

Correct, one of the very first steps in the BGP best path selection algorithm is to prefer paths with the highest LOCAL_PREF (= discard paths with lower LOCAL_PREFs)
See https://www.cisco.com/c/en/us/support/docs/ip/border-gateway-protocol-bgp/13753-25.html for more details.

In this case, A is a customer of B, then that path has a greater local
  preference or lower local preference?

It is customary to give paths received from a customer a higher LOCAL_PREF (= more preferred) than paths received from peering partners or transit providers.
See https://www.noction.com/blog/what-you-should-know-about-bgps-local_pref for more details.


text:
Q: Passing parameters to Reporting Services Programmatically I need to pass a dynamic parameter to my reporting service.
The parameter name is PCName
The processing mode is in Remote, I was able to pass the parameter to the Report if I log on to the Reporting Server manually, but I want to pass it programagically.
Here is a copy of my ASP code.
<asp:ScriptManager id='scriptManager' runat='server' />
<rsweb:ReportViewer ID="ReportViewer1"
                    runat="server"
                    ProcessingMode="Remote"
                    Font-Names="Verdana"
                    Font-Size="8pt"
                    InteractiveDeviceInfos="(Collection)"
                    WaitMessageFont-Names="Verdana"
                    WaitMessageFont-Size="14pt"

                    Width="95%"
                    Height="99%" ShowDocumentMapButton="False"
    ShowPromptAreaButton="False" Visible="true">

<ServerReport   ReportPath="/Services/Logon"
                ReportServerUrl="http://reports/reportserver/" />

</rsweb:ReportViewer>

A: You should create a report parameter from your code behind and pass it to the report viewer control as following
ReportParameter param = new ReportParameter("PCName", "parameter value");
this.ReportViewer1.ServerReport.SetParameters(new ReportParameter[] { param  });
this.ReportViewer1.ServerReport.Refresh();


text:
Q: Why does this regex execute slowly? So i've got a regex that identifies URLs:
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

But when I use it to identify urls that a user has entered, simply using .test slows the page down considerably, even though according to the MDN, it's supposed to be faster than exec. Am I using an outdated method of testing Regular Expressions? Is there a faster method that i don't know about? or is my regex just really long and complicated?
Here's a JSFiddle.
Edit:
Takes 20.7 seconds in Chrome, v24
1:48.5 in Internet Explorer 9

A: So it seems that the regex only lags when it processes a url that has posted information, for example in the jsfiddle url Product.aspx?Item=N82E16811139009. When that part of the url is removed, the regex preforms correctly, and quickly.
However, removing the last star from ([\/\w \.-]*)* makes the regex preform incorrectly, so using ([\/\w \.-]*) is not an option.
Rather, for the regex to be able to handle urls with posted information, the last part needs to be removed:
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

to
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*/

this is because the regex is designed to detect filetypes or a backslash at the end of the url, not a question mark and posted information. removing the last part fixes the problem and the regex runs correctly and quickly.


text:
Q: Spacing in bibliography I would like to ask for help regarding writting bibliography. In bibliography section the Latex compiler puts huge gaps between the words. I would be grateful if someone could tell me how to get rid off them.
The code:
\begin{thebibliography}{99}
    \bibitem{tesla}
    \emph{Model S $\mid$ Tesla}.Tesla [online].[cit. 2017-04-29]. Dostupné z: https://www.tesla.com/models

\end{thebibliography}

A: \documentclass{article}

\usepackage[hyphens]{url}

\begin{document}

\begin{thebibliography}{99}
    \bibitem{tesla}
    \emph{Model S $\mid$ Tesla}.Tesla [online].[cit. 2017-04-29]. Dostupné z: \url{https://www.tesla.com/models}

\end{thebibliography}

\end{document}


text:
Q: FInd similar patterns in a row using Awk or SED Need some help here
I have file which has multiple rows, Something like below
'**FSR**+S:KSSSSS+20+14++20120401'FST+S:KSSSSS+2'**FSR**+S:KSSSSS+44+1++20160218'
'**FSR**+S:KSSSSS+20+14++20120401'FST+S:KSSSSS+2'**FSR**+S:KSSSSS+44+1++20160218'
'**FSR**+S:KSSSSS+20+14++20120401'FST+S:KSSSSS+2'**FSR**+S:KSSSSS+44+1++20160218'
'**FSR**+S:KSSSSS+20+14++20120401'

I am trying to get all the segments within a row which begins with FSR
so results should be something like this, add pipe every time its finds a FSR, since they are constant on where they would occur in row. so i am not able to use cut here, in short FSR may come in beginning , middle or in the end of the row
'**FSR**+S:KSSSSS+20+14++20120401' | **FSR**+S:KSSSSS+44+1++20160218'
'**FSR**+S:KSSSSS+20+14++20120401' | **FSR**+S:KSSSSS+44+1++20160218'
'**FSR**+S:KSSSSS+20+14++20120401' | **FSR**+S:KSSSSS+44+1++20160218'
'**FSR**+S:KSSSSS+20+14++20120401'

Additionally, this is the code, i had written in perl, thinking if this could be could be done in simple way
#!/usr/bin/perl
use strict;
use Data::Dumper;

my $filename = $ARGV[0];
chomp($filename);

open(FILE,$filename);
my ($FSR);

while(my $data = <FILE>) {
        #print $data;
        ($FSR) = "";
        if($data =~ /('FSR.*?)(.*?)(\')/) {
                $FSR = "$1,$2";
        }
print "$FSR\n";
}
 close(FILE);

Please help
Thanks
Sandy

A: EDITED:
The following one-liner would seem to address your problem as described:
$ sed -i -e 's/FSR/ | FSR/g' YOURFILE

Is there something more to this or is that what you were looking for?


text:
Q: For BottomNavigation the selected Item is not highlighted in android I have bottomNavigation in my android app as shown below in picture. It works fine if I just click on home, cart and other bottomNavigation Items.
As you can see in picture that user can navigate to all categories in home. If I navigate to AllCategoriesFragment then in home item will be selected in bottomNavigation which is correct behavior. But if I go to cart and then click again on home then it shows AllCategoriesFragment which is also correct behavior but in BottomNavigation it doesnt highlight the home items, instead it keep cart item highlighted.
How I can get rid of this issue? Or how I can highlight the bottomNavigation selected item programmatically?

A: I did it programmatically like by getting activity reference inside fragment andd then getting navView from it and afterwards set the check state of the item to true
activity?.let {
            val navView = it.findViewById<BottomNavigationView>(R.id.nav_view)
            navView.menu.getItem(0).setChecked(true)
        }


text:
Q: iOS app white screen after first use on some iOS 13+ devices Some of our users are reporting a white screen when they use our app for the second time. Even if they force close the app and restart, the problem persists.
There are no crashes or exceptions being reported by Apple or our own crash reporting (AppCenter).
Searching online, it seems a few mainstream apps (Dropbox, Spotify) are having this issue too. So far I cannot find any developers mentioning it, nor any leads for what might be causing it.
Does anyone know what might be causing this? It seems to be consistent for certain users, but when we try to reproduce the issue on our own devices we can never experience it.


text:
Q: Xampp, Access forbidden for non index files I've been using xampp for a long time and it's always worked fine.  I have a project I am currently working on and it was working fine just a couple of days ago. Now I am getting 403 Access forbidden page for any file that is not named index.php.  Anyone have any ideas why this might be happening.
I'm on Windows XP and have Xampp Version 1.6.4 installed.

A: My first guess would be an issue with the .htaccess file (or httpd.conf file).
Something to keep in mind:
The way that Apache handles .htaccess rules is "cascading" meaning that it will check every .htaccess file along the path of the file you are trying to access, so if you have some rule forbidding users from viewing any non-index files at any point, it will affect all deeper directories.
Having said that, if you know the issue isn't with the httpd.conf file, check to see if the root of the publishing path has a .htaccess file. Change it to .htaccessold and see if you can access any files in the htdocs directory other than index.
Two questions:

*

*Do you get this for all files, or just php files? can you see image files, etc?

*What about index.html? If you change your index.php to tempindex.php and create a new blah file called index.html can you see that?

Good luck. Keep me posted.

A: The only way you can see why Apache is returning this error message is to look at the error log.
We can guess at possible causes, but Apache will be able to tell you if you take the time to look.

A: It sounds like you changed some mod_rewrite rules or your site's apache configuration.  Did you add or change anything in an .htaccess file?
You're probably going to have to give more details in order to figure this out.


text:
Q: Not wanting to use if else but try except block in python I am trying to write a program that does the following in python:
accept three arguments: a prompt, a low acceptable limit, and a high acceptable limit;
if the user enters a string that is not an integer value, the function should emit the message Error: wrong input, and ask the user to input the value again;
if the user enters a number which falls outside the specified range, the function should emit the message Error: the value is not within permitted range (min..max) and ask the user to input the value again;
if the input value is valid, return it as a result.
I don't want to use if-else. I am learning catching exceptions in python. i want to use try-except
I have written the following code
def readint(prompt, min, max):
    try:
        theNum = int(input(prompt))
        if theNum in range(min, max+1):
            return theNum
    except ValueError:
            return "Error: wrong input. The value is not within the permitted range (-10..10)"
            readint(prompt, min, max)

v = readint("Enter a number from -10 to 10: ", -10, 10)

print("The number is:", v)

The output prints out any number in the mentioned range but when a number not within the range is entered, the output says "The number is: None" and it does not re-prompt me to enter another number

A: Here's a typical retry loop that uses try/except:
def thing_to_retry():
    while True:
        try:
            return thing()
        except SomeError as e:
            print("Whoopsie! Error: {}".format(e))

Since the try/except is within the loop, any exception you catch will cause another loop iteration. Success will cause the function to return from the loop.

A: min and max are keywords in python. I would avoid using them as variable names.
def readint(prompt, minimum, maximum):
    while True:
        try:
            value = int(input(prompt))
            assert minimum <= value <= maximum
            prompt = "Try again: "
        except ValueError:
            print("Error: Not an integer")
        except AssertionError:
            print("Error: Value not within range")
        else:
            break
    return value

minimum = -10
maximum = 10

value = readint(f"Enter a number between {minimum} and {maximum}: ", minimum, maximum)

A: def readint(prompt, min, max):
    doIt = True
    while doIt:

        try:
            userInput = int(input(prompt))
            if userInput in range(min, max+1):
                doIt = False
                return userInput
            else:
                raise AssertionError
        except ValueError:
            print("Error: wrong input.")
        except AssertionError:
            print("The value is not within the permitted range (-10..10)")
        except:
            doIt = True

v = readint("Enter a number from -10 to 10: ", -10, 10)

print("The number is:", v)


text:
Q: Question about rotation around center of object using CBasicAnimation I am trying to spin a wheel on its axis -- setting it in motion using the mouse. Specifically, I am trying to spin a roulette wheel.
I calculate a delta x and delta y by getting the difference of x1 x2 and y1 y2. I can see in console via NSLOG msgs that it is ok. I use these values to calculate velocity.
CABasicAnimation *fullRotation;
 fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
 fullRotation.fromValue = [ NSNumber numberWithFloat:0 ] ;
 fullRotation.toValue = [NSNumber numberWithFloat:(((360*M_PI)/180)) ;
 fullRotation.duration = duration ;
 fullRotation.repeatCount = repeat ;
[myview.layer addAnimation:fullRotation forKey:@"360"];
The above code gives me fluid animation, but the wheel always completes a full circle, which would be not very realistic.
Can anyone suggest a method for spinning the wheel by smaller amounts that still gives fluid animation? When I use the above, the wheel doesn't move at all for smaller amounts.
Thank you!
Piesia

A: It sounds like you need a little physics modeling to get the right action on the wheel. I'm not familiar with the APIs and I don't see where the code takes into account the velocity imparted by the finger movement, but I will dust off my physics lessons from 20 years ago with the hope it will help.
The initial velocity of the wheel is going to be determined by the motion of the finger at the time of release. We know that the linear velocity of the wheel at some point will be equal to the angular velocity multiplied by the radius to the point where we're measuring the velocity.
linear velocity = angular velocity * radius

As the wheel spins, it's going to encounter friction from the spindle against the wheel and this will cause it to slow down. Friction is a force applied over time until the wheel comes to a stop.
Friction = Moment of Inertia of the Wheel * angular acceleration

or
Friction / Moment of Inertia of the Wheel = angular acceleration

For the purposes of your application this will be a constant and you'll probably want to experiment with different values for this until it "feels right."
To calculate the amount of time, solve the following equation for time:
0 = angular velocity + angular acceleration * time

Angular acceleration will be negative because you're slowing down. Once you have the amount of time, you're going to calculate the number of revolutions by the following:
revolutions = ((angular velocity * time) + (0.5 * angular acceleration * time^2)) / (2 * pi)

time^2 is time squared, or time * time.
I hope this helps.


text:
Q: R: Back-referencing data frame in `with` expression Is there a way to back-reference the scope in a with expression in R?
I'm trying to write the following (valid) statement in a more elegant (i.e. non-repetitive) way:
with(subset(mtcars, cyl > 4), {
  aggregate(subset(mtcars, cyl > 4),
            by=list(gear), min)
})

I'm aware of the following alternative syntax:
aggregate(mtcars[mtcars$cyl>4,],
          by=list(mtcars[mtcars$cyl>4,'gear']), min)

I'm almost certainly sure someone came up with this problem before, but I'm lacking suitable words for web search.

A: A short version could be with the formula notation, with . meaning all other columns:
aggregate(. ~ gear, data = subset(mtcars, cyl > 4), min)

Or with a pipe, which resembles with:
subset(mtcars, cyl > 4) |>
  aggregate(. ~ gear, FUN = min)

A: Another way may be to use summarise() function using tidyverse family:
   mtcars |> filter(cyl > 4) |> group_by(gear) |>
        summarise(across(everything(), .fns = min)) |> as.data.frame()

  gear  mpg cyl disp  hp drat    wt  qsec vs am carb
1    3 10.4   6  225 105 2.76 3.215 15.41  0  0    1
2    4 17.8   6  160 110 3.90 2.620 16.46  0  0    4
3    5 15.0   6  145 175 3.54 2.770 14.50  0  1    4


text:
Q: how does SQL Server actually store russian symbols in char? I have a column NAME, which is CHAR(50).
It contains the value 'Рулон комбинированный СТЕРИТ 50мм ? 200 м'
which integer representation is:
'1056,1091,1083,1086,1085,32,1082,1086,1084,1073,1080,1085,1080,1088,1086,1074,1072,1085,1085,1099,1081,32,1057,1058,1045,1056,1048,1058,32,53,48,1084,1084,32,63,32,50,48,48,32,1084'

but CHAR implies that it contains 8 bit. How does SQL Server store values like '1056,1091,1083,1086,1085' which are UNICODE symbols?
OK, and also ? symbol is actually × (215) (Multiplication Sign)
If SQL Server can represent '1056' why it can't represent '215'?

A: What the 255 values in a char mean is determined by the database collation.  For Russia this is typically Cyrillic_General_CI_AS (where CI means Case Insentitive and AS means Accent Sensitive.)
There's a good chance this matches Windows code page 1251, so л is stored as hex EB or decimal 235.  You can verify this with T-SQL:
create database d1 collate Cyrillic_General_CI_AS;
use d1
select ascii('л')
-->
235

In the Cyrillic code page, decimal 215 means Ч, not the multiplication sign.  Because SQL Server can't match the multiplication sign to the Cyrillic code page, it replaces it with a question mark:
select ascii('×'), ascii('?')
-->
63      63

In the Cyrillic code page, the char 8-bit representation of the multiplication sign and the question mark are both decimal 63, the question mark.

A:
I have a column NAME, which is CHAR(50).
It contains the value 'Рулон комбинированный СТЕРИТ 50мм ? 200 м'
  which integer representation is:
'1056,1091,1083,1086,1085,32,1082,1086,1084,1073,1080,1085,1080,1088,1086,1074,1072,1085,1085,1099,1081,32,1057,1058,1045,1056,1048,1058,32,53,48,1084,1084,32,63,32,50,48,48,32,1084'

Cyted above is wrong.
I make a test within a database with Cyrillic collation and integer representation is different from what you showed us, so or your data type is not char, or your integer representation is wrong, and yes, "but CHAR implies that it contains 8 bit" is correct and here is how you can prove it to youerself:
--create table dbo.t (name char(50));
--insert into dbo.t values ('Рулон комбинированный СТЕРИТ 50мм ? 200 м')

select cast (name as binary(50))
from dbo.t;

select substring(cast (name as binary(50)), n, 1) as bin_substr,
       cast(substring(cast (name as binary(50)), n, 1) as int) as int_,
       char(substring(cast (name as binary(50)), n, 1)) as cyr_char
from dbo.t cross join nums.dbo.nums;

Here dbo.Nums is an auxiliary table containig integers. I just convert your string from char field into binary, split it byte per byte and convert into int and char.


text:
Q: $lookup with two $concat fields Given those documents:
{
    "name" : "User",
    "class" : "clazz",
    "reference" : "ref"
}

{
    "classReference" : "clazz+ref",
    "room" : "123"
}

How can I do a $lookup to retrieve a document like this (without changing the documents):
{
    "name" : "User",
    "class" : "clazz",
    "reference" : "ref",
    "classReference" : "clazz+ref",
    "room" : "123"
}

A: You can use below aggregation with mongodb 3.6 and above
db.user.aggregate([
  { "$lookup": {
    "from": Room.collection.name,
    "let": { "ref": { "$concat": ["$class", "$reference"] } },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$classReference", "$$ref"] } } }
    ],
    "as": "ref"
  }},
  { "$project": {
    "classReference": { "$arrayElemAt": ["$ref.classReference", 0] },
    "room": { "$arrayElemAt": ["$ref.room", 0] },
    "name": 1,
    "class": 1
    "reference": 1
  }}
])

Basically you need to  $concat both the class and reference and then pass it to $lookup pipeline.


text:
Q: connect javascript client to python websocket server I have this working python websocket server:
#!/usr/bin/env python
from socket import *

HOST = ''
PORT = 8080
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

def loop():
    while True:
        print 'Waiting for connection...'
        tcpCliSock, addr = tcpSerSock.accept()
        print '...connected from :', addr
        while True:
            data = tcpCliSock.recv(BUFSIZ)
            if not data:
                break
            else:
                print 'data: ',data
        tcpSerSock.close()

try:
    loop()
except KeyboardInterrupt:
    tcpSerSock.close()

when I connect from the python client it works even if when I close the client the server crashes:
Waiting for connection...
Traceback (most recent call last):
  File "ledServer.py", line 27, in <module>
    loop()
  File "ledServer.py", line 16, in loop
    tcpCliSock, addr = tcpSerSock.accept()
  File "/usr/lib/python2.7/socket.py", line 202, in accept
    sock, addr = self._sock.accept()
  File "/usr/lib/python2.7/socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

anyway when I run this javascript client:
window.onload = function(){
    ws = new WebSocket('ws://192.168.25.7:8080');
    ws.onmessage = function(event){document.write("message received"); alert(event.data); ws.close();}
    ws.onopen = function(){document.write("open");}
    ws.onclose = function(){document.write("close");}
    ws.onerror = function(){document.write("error");}
}

I get this on the server:
...connected from : ('192.168.25.25', 53747)
data:  GET / HTTP/1.1
Host: 192.168.25.7:8080
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Accept-Encoding: gzip, deflate
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,tr;q=0.6,nl;q=0.5
Sec-WebSocket-Key: pH4kNOzz1MYyi+oXmaFCcA==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

but even if the server says it is connected, on the client the onopen function is not executed, Chrome says that websocket status is "pending", and if I try to send a message to the server, I get:
Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

What am I doing wrong?

A: The Python socket module doesn't have anything to do with websockets.
WebSocket, like HTTP, is a protocol implemented on top of an underlying transport. What your code does is setup a TCP server listening on port 8080. Websockets are a layer above that, just like HTTP. You can see the browser attempt to handshake with your server but it gives up because your server doesn't respond appropriately.
The websocket protocol is somewhat complicated and you'll probably want a library to handle it for you. One example is the websockets module:
#!/usr/bin/env python

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(message)

asyncio.get_event_loop().run_until_complete(
    websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()