text:
Q: How can I add jQuery to a WebPart (to respond to certain events on the WebPart)? I started down the path of adding an UpdatePanel to my Sharepoint page so that I can respond to events that take place (such as the checking of checkboxes and mashing of radio buttons, etc.). That so far has, however, been wrought with frustration and all that rot, as can be deduced from this question.
So I'm now probably going to traverse (no pun intended) the jQuery route and am trying to figure out/find out how to add jQuery to a WebPart.
Currenlty, I am dynamically creating controls in C# based on what a user selects in the WebPart's Editor (if they elect to show Section 1, I create all the controls for Section 1, etc.).
As an example, I'm currently conditionally creating a RadioButton in C# like so:
var radbtnEmployeeQ = new RadioButton
{
    CssClass = "dplatypus-webform-field-input"
};

Now if I want to add jQuery to it, I can add an ID to it like so:
var radbtnEmployeeQ = new RadioButton
{
    CssClass = "dplatypus-webform-field-input",
    ID = "radbtnEmp"
};

...and then add jQuery of this nature (pseudocode):
$('radbtnEmp').click {
    // visiblize/invisiblize other controls, assign certain vals to their properties
}

This seems feasible to me, but how do I go about adding jQuery to a WebPart? Is it a matter of adding a .js file at the same directory level as the *.ascx.cs file, and then referencing it from the *.ascx.cs file, or...???
UPDATE
For POC testing, I added a file to my project named "directpaydynamic.js" with this content:
<script>
    $(document).ready(function () {
        $('input:radio[name=radbtnEmp]:checked').change(function () {
            if ($("input[name='radbtnEmp']:checked").val() == 'Employee?') {
                alert("radbtnEmp checked");
            }
            else {
                alert("radbtnEmp not checked");
            }
        });
    });
</script>

(derived from an example here)
...and reference the .js file in my *.ascx.cs file like so:
SPWeb site = SPContext.Current.Web;
site.CustomJavaScriptFileUrl = @"C:\Projects\DirectPaymentWebForm\DirectPaymentSectionsWebPart\DPSVisualWebPart\directpaydynamic.js";

(I dragged the .js file onto the code to get the path)
However, running the solution and mashing the radiobutton causes neither alert() to display, so I reckon I've taken the road that was for a good reason less traveled.
UPDATE 2
Realizing I didn't need the script business (as this is a .js file, not an html file), I removed those, and also put an "at any rate" alert() in the jQuery:
$(document).ready(function () {
    alert("What's new, pussycat, whoa-oh-oh-oh-OH-oh?");
    $('input:radio[name=radbtnEmp]:checked').change(function () {
        if ($("input[name='radbtnEmp']:checked").val() == 'Employee?') {
            alert("radbtnEmp checked");
        }
        else {
            alert("radbtnEmp not checked");
        }
    });
});

...but I still endure an alarming dearth of alerts...

A: Use below code on Page load method
  string url = SPContext.Current.Site.ServerRelativeUrl;

        if (!url.EndsWith("/"))
        {
            url += "/";
        }
HtmlGenericControl styleCss = new HtmlGenericControl("link");
        styleCss.Attributes.Add("rel", "stylesheet");
        styleCss.Attributes.Add("type", "text/css");
        styleCss.Attributes.Add("href", url + "Style Library/css/style.css");
HtmlGenericControl JsLink = new HtmlGenericControl("script");
        JsLink.Attributes.Add("src", url + "Style    Library/js/jquery.min.js");`enter code here`
this.Controls.Add(styleCss);
this.Controls.Add(JsLink);

A: The thing to do (or perhaps I should write, "a" thing to do) to get this to work is to add code like the following to the end of the WebPart's *.ascx file:
<script>
$(document).ready(function () {
    alert("The ready function has been reached");
});

$(document).on("change", '[id$=ckbxEmp]', function () {
    alert('Function has been reached');
    if ($(this).is(":checked")) {
        alert("Checked");
    } else {
        alert("Not checked");
    }
});
</script>

The above works like a champ.


text:
Q: How to make "R" use all CPUs I am using GNU R to calculate a huge dataset.
My PC has 4 CPU-cores, and I can see, that R is using only 1 CPU.
Is there a way to tell R to use all 4 CPUs in order to make the calculation complete faster?

A: You should use the r-cran-multicore package to enable multiple cpu processing:
sudo apt-get install r-cran-multicore

See details about this functionality here: http://www.rforge.net/multicore but as a warning, your 'R' code will probably have to be updated to take advantage of multiple core technology. unless you are already using pre-made code which supports the multicore extensions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Exception in thread "main" java.Lang.NullPointerException" Error I am trying to run a web scraper in Eclipse that, using Jsoup, that can take the names of the professors on this page: yu.edu/faculty and print them out. This is my code:
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class YUscraper {

    public static void main(String[] args) throws IOException {

        // fetches & parses HTML
        String url = "http://yu.edu/faculty/";
        Document document = Jsoup.connect(url).get();

        // Extract data
        Element content = document.getElementById("mainlist");
        Elements names = content.getElementsByTag("a");

        // Output data
        for (Element name : names) {
            System.out.println("Name: " + name.text());
        }
    }

}

I am getting this error:
Exception in thread "main" java.lang.NullPointerException
at YUscraper.main(YUscraper.java:18)

I am relatively new to this so pardon me if I am missing something really evident. I used many examples I have seen to get to this point, but I still don't understand what throws IOException is for and what it means that an exception was found.  Please help, thanks!

A: Line Element content = document.getElementById("mainlist");
content is returned as null, so null.getElementsByTag is giving the error .. Looks like html doesn't have element by 'mainlist'

A: Line 18 is
Elements names = content.getElementsByTag("a");
Seems like there is no tag with id "mainlist" in the html retrieved from http://yu.edu/faculty/.
Seems like you were trying to access tag main-nav instead of mainlist.


text:
Q: select all lines from 2 tables with same id I have two tables in my database that looks like that :
TABLE1
user_id
value1
value2

TABLE2
user_id
value3
value4

I would like to make a query to get all the lines from TABLE1 and TABLE2 that have an user_id = 1.
I have done :
SELECT TABLE1.user_id,TABLE1,value1, TABLE1.value2, TABLE2.value3, TABLE2.value4
 FROM TABLE1
INNER JOIN TABLE2
ON TABLE1.user_id = TABLE2.user_id
WHERE TABLE.user_id = 1

But I get all the values in one row, I'd like to get all the different row from those 2 tables where the user_id = 1..
Thank you for your help.

A: Use union all:
select 't1' which, user_id, value1, value2 from table1 where user_id = 1
union all
select 't2', user_id, value3, value4 from table2 where user_id = 1

You did not specify exactly the resultset that you want to get. This gives you a dataset made of 4 columns, where the first column contains the name of the table where the user was found. Columns 3 and 4 contain either value1 and value2 (if the row comes from table1), or value3 and value4 (if the row comes from table2).
This can only work if value1 and value3 (resp. value2 and value4) have the same datatype (and length). If that's not the case, then you would better have separate columns in the resultset:
select 't1' which, user_id, value1, value2, null value3, null valu4
from table1 where user_id = 1
union all
select 't2', user_id, null, null, value3, value4
from table2
where user_id = 1


text:
Q: Subsetting columns of months by season in pandas DataFrame I have a set of data that extracted from an excel sheet. one of the columns were dates and so I used df.to_datetime() to reformat the data. The data I have is only for the first day of each month, the string format is:

"20190101"

so there are only 12 dates.
Then I used pd.pivot to make this column of dates the column labels.
The plan now is to subset the columns by seasons (e.g Jan, Feb, Dec is winter). I only have 2019 data but I will be using this code for future years. I will be taking Dec of previous year so I need to disregard the years.
How do I subset the columns based on the months. In other words I want to divide the DataFrame similarly to:
for column in full_df.iterrows()
    If (column_label.datetime.month = 01 | column_label.datetime.month = 02 |column_label.datetime.month = 12):
        winter_df[datetime.month] = full_df[column_label]

I know for loops are frowned upon in Dataframe, and I know I can hard-code it by keeping it as a string and typing in the specific strings, but the data will not be from the same year each time and I would have to adjust the code every year.
How do I do an if statement for column labels? df.filter() might be a good idea but I don't know if its possible with datetime object.
P.S. forgive me if I formed the question poorly or I don't understand your answer. Fairly new to pandas.
Update: I am looking to split the DataFrame into three based on month, The three periods of time are as follows:
Winter: January ,February ,December
Light load: March, April, May
Summer: June,July August, September

A: From your description this achieves what you want

*

*categorises a quarter into a season

*"pivots" actually transposes to column format

update
There seems to be a condition when pandas can give wrong quarter.  Can instead calculate from integer division on month
df = df.assign(season=lambda x: x["Date"].apply(lambda s: ["winter","spring","summer","autumn"][(s.month-1)//3]))

import datetime as dt
import pandas as pd
import random
df = pd.DataFrame([{"Date":d, "Value": random.randint(10,20)}
 for d in pd.date_range(dt.datetime(2018,1,1),dt.datetime(2019,3,1), freq="MS")])

df = df.assign(season=lambda x: x["Date"].apply(lambda s: ["winter","spring","summer","autumn"][s.quarter-1]))
df = df.set_index(["season","Date"]).T

output
season     winter                           spring                           summer                           autumn                           winter
Date   2018-01-01 2018-02-01 2018-03-01 2018-04-01 2018-05-01 2018-06-01 2018-07-01 2018-08-01 2018-09-01 2018-10-01 2018-11-01 2018-12-01 2019-01-01 2019-02-01 2019-03-01
Value          10         20         12         17         12         12         11         20         11         19         12         10         11         20         14


text:
Q: JSF How to set file name back to original? I'm having problem setting filename back after I create temporary file. I have tried to use File.renameTo() but it didn't work. Here is a code that saves my file.
public void upload(FileUploadEvent event){
    uploadedFile = event.getFile();
    Path folder = Paths.get("E:/ProjectUsers/" + loggedUser.getUser().getEmail());
    int indexOfDot = uploadedFile.getFileName().indexOf(".");
    String filename = uploadedFile.getFileName().substring(0,
            indexOfDot);

    String extension = uploadedFile.getFileName().substring(indexOfDot+1);
    try {
        InputStream input = uploadedFile.getInputstream();
        Path file = Files.createTempFile(folder, filename + "-", "." + extension);
        Files.copy(input,file, StandardCopyOption.REPLACE_EXISTING);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Success!",  "File has been uploaded"));
    }
    catch(IOException e){
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ooops!",  e.getMessage()));
    }

}

After the file is created using File.createTempFile() file has some digits attached and I don't know how to get rid of them. It is important to keep original name for me because later the filePath is added to database for later use.
For example lets say the file name I upload is abc.png , after the upload in the folder I get the file named abc-2480631562559339564.png


text:
Q: How do I work with big amount of data on IPhone? I need to analyze one part of the song. When I tested on iPhone simulator I used 2d array which was myArray[150][220500] big.. So.. I can't get this code work on device, because it does not have enough memory for that (Code works with smaller 2d array, but it's not enough for analyze).
Any ideas how could I get this work on device?

A: That is too much data to allocate on the stack. According to the documentation iOS only has 1MB of stack space on the main thread and secondary threads get 512KB. Assuming myArray is declared as an int (4 bytes) you are allocating at least

(4 * 150 * 220500) bytes = 132300000 bytes = 126.171 MB

You will need to allocate the memory on the heap instead using malloc or calloc.
//Initialize array
int **myArray = malloc(150 * sizeof(*myArray));
for(unsigned int i = 0; i < 150; ++i)
{
    //Use calloc if you want all 0's
    myArray[i] = malloc(220500 * sizeof(**myArray));
}

//Use array
myArray[10][2000] = 36;
NSLog(@"[10][2000] = %d", myArray[10][2000]);

//Delete array - You must do this to prevent memory leaks
for(unsigned int i = 0; i < 150; ++i)
{
    free(myArray[i]);
}
free(myArray);


text:
Q: How to find nodes at a distance k from the given node in binary tree I came across THIS geeksforgeeks post to find nodes at distance k from the given node in a binary tree.
I am not able to understand it even after spending multiple hours. Specially the part to find the nodes at distance k in ancestors.
Can someone please please help me with a small dry run on the code/algorithm in the geeksforgeeks post? Or any other easy to understand solution without using parent pointer?

A: Let's say the depth of target node is D.

*

*If the nodes you want is in the subtree rooted with target node, their depth should be D+k.

*After that, you need to find all ancestors of the target node.
For each ancestor, if the depth is d, the distance between this ancestor to the target node is D-d.
So the final step is to find nodes in the other subtree of this ancestor whose distance is k - (D-d).


text:
Q: Output is not fully displayed on terminal of visual studio code when using "run code" function When I run the python file with "run code" mode, the output is not fully displayed in the terminal, but when I run the python file with "run python file" mode, the output is fully displayed.
I have set the terminal Integrated scrollback to a much higher number but that didn't fix it. I'm speculating this error is caused by the code runner extension. Hope someone can understand and solve this problem for me.


text:
Q: Project dll error in Visual Studio 2013 output upon Build When I build my project, I get this message in the Output window:
1>------ Build started: Project: ProjectX, Configuration: Debug Any CPU ------
1>  ProjectX -> C:\Users\Alfred\Documents\Visual Studio 2013\Projects\ProjectX2015\ProjectX\ProjectX\bin\ProjectX.dll
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

I think it started after an update-package. It compiles but I'm starting to wonder what the 2nd line mean:
1>  ProjectX -> C:\Users\Alfred\Documents\Visual Studio 2013\Projects\ProjectX2015\ProjectX\ProjectX\bin\ProjectX.dll

Is this a real error or just something to ignore?
Below is my  ProjectX.dll.config (sanitized):
<?xml version="1.0" encoding="utf-8"?>
<configuration>

<configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=XXX" requirePermission="false" />
</configSections>
<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(localdb)\v11.0;AttachDbFilename=|DataDirectory|\XXX.mdf;Initial Catalog=MyProject;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
</connectionStrings>
   <appSettings>
       <add key="webpages:Version" value="3.0.0.0" />
       <add key="webpages:Enabled" value="false" />
       <add key="ClientValidationEnabled" value="true" />
       <add key="UnobtrusiveJavaScriptEnabled" value="true" />
       <add key="SecurityKey" value="XXX" />
   </appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpModules>
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<customErrors mode="Off"></customErrors>
</system.web>
<system.webServer>
<modules>
    <remove name="FormsAuthentication" />
    <remove name="ApplicationInsightsWebTracking" />
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<staticContent>
    <remove fileExtension=".woff" />
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
    <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
</system.webServer>
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="Microsoft.Owin" publicKeyToken="XXX" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="XXX" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
        </dependentAssembly>
        <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="XXX" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="Microsoft.AI.Agent.Intercept" publicKeyToken="XXX" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.2.1.0" newVersion="1.2.1.0" />
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="XXX" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
    </dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="XXX" />
        </parameters>
    </defaultConnectionFactory>
    <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

</configuration>

A: The first line of the output indicates that a build for a project (named "ProjectX", with "Debug Any CPU" configuration) is started. On the second line, it then outputs the location of the resulting binary. Finally, on the third line, it shows build results for all projects in the current solution.
This is standard output for a successful build of one project. Depending on the complexity of the project, there will sometimes be more lines, but lines 1 and 3 will always be there. The line 2 that shows the location of the output file will only be present in case of a successful build.


text:
Q: PhoneGap 2.7 show activityindicator in status bar I'm using PhoneGap 2.7 and iOS 6. Whenever I load some data from my server, the activity indicator in the ios status bar doesn't appear. I always thought ios automatically takes care about that. But it seems that there is no command in javascript and the plugins are not working as well.
How do i trigger the ActivityIndicator whenever I request data from the server?
PS:
The plugins NotificationEx and networkActivityIndicator are not working with 2.7
navigator.notification.activityStart(); and navigator.notification.activityStop(); is deprecated since 1.0.

A: The core functionality is available in the form of plugin
https://github.com/phonegap/phonegap-plugins/tree/master/iOS/NotificationEx
With the readme it's pretty easy to install and get started with the plugin.


text:
Q: Undefined index al subir una imagen al servidor Buenas, estoy topandome con este error y no estoy dando con la clave.
Notice: Undefined index: pac_foto in C:\wamp64\www\pruebas\pags\ver_foto.php on line 32
PHP.INI:
File Uploads activado
Max_execution_time = 300
Max_input_time = 240
Memory_limit = 128M
Post_max_size = 16M

fichero PHP destino
$pac_foto = isset($_REQUEST['pac_foto'])?$_REQUEST['pac_foto']:'';
$foto_directorio_subida = 'imgs/';
$foto_directorio_subida .= basename($_FILES['pac_foto']['name']);
$foto_tipo_archivo = $_FILES['pac_foto']['type'];
    if (move_uploaded_file($_FILES['pac_foto']['tmp_name'], $foto_directorio_subida)) {
        echo "Foto subida correctamente";
    } else {
        echo "No se pudo guardar la foto.";
    }

formulario HTML (en otro documento)
<form enctype="multipart/form-data" action="verFoto" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
    <input type="file" name="pac_foto" />
    <input type="submit" name="pac_boton_enviar" value="Guardar Datos" />
</form>

He hecho var_dump de $pac_foto y me saca el nombre del fichero que estoy subiendo. Sin embargo, hago var_dump de $_FILES y me da un array vacío.
¿Que puedo estar haciendo mal?
Un saludo y gracias

A: Respecto a tu notice:

Notice: Undefined index: pac_foto in C:\wamp64\www\pruebas\pags\ver_foto.php on line 32

*

*Deberías iniciar dicha variable en NULL al inicio de tu código
PHP $pac_foto = NULL, digamos antes de declarar dicha variable.

Respecto a tu código PHP, en si, se podría mejorar algunas áreas y añadirles comprobaciones PHP para obtener un mayor seguridad, veamos un ejemplo distinto, a ver si logro orientarte mejor.
Un posible ejemplo:
HTML
<form action="verfoto.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="pac_foto" />
    <input type="submit" name="pac_boton_enviar" value="Guardar Datos" />
</form>

PHP (verfoto.php)
<?php
//Definido y no NULL nuestro formulario.
if (isset($_POST)) {
    //Comprobamos que no este vacio nuestro input file.
    if (!file_exists($_FILES['pac_foto']['tmp_name'])) {
        echo 'Por favor selecciona una imagen para continuar';
        //Rediriges si quieres al formulario.
    } else {
        //obtenemos datos imagen.
        $file = $_FILES["pac_foto"];
        $nombre_img = $file["name"];
        $extencion_img = $file["type"];
        $ruta_temporal = $file["tmp_name"];
        $tamano_img = $file["size"];
        $dimensiones = getimagesize($ruta_temporal);
        $ancho = $dimensiones[0];
        $altura = $dimensiones[1];
        $carpeta = "/imgs/$nombre_img";

        //Inicio error imagen en true.
        $img_error = true;

        //Comprobaciones error (¡Esto es a gusto colores!).
        if ($extencion_img != 'image/jpeg' && $extencion_img != 'image/jpg' && $extencion_img != 'image/png' && $extencion_img != 'image/gif') {
            echo "$nombre_img, no es una imagen valido, un imagen con extensión valido podría ser entre (.jpg, .jpeg, .png o .gif).";
        } elseif($tamano_img > 300000) {
            echo"El tamaño de tu imagen $nombre_img, supera los 300kb permitidos.";
        } elseif($ancho > 500 || $altura > 500) {
            echo "La anchura y la altura de $nombre_img supera la máxima permitida de 500px.";
        } elseif($ancho < 250 || $altura < 250) {
            echo "La anchura y la altura de $nombre_img es inferior que la mínima permitida de 250px.";
        } else { //Imagen correcto.
            //Reseteo error en false.
            $img_error = false;
        }

        //Verdadero imagen.
        if ($nombre_img && $img_error===false) {
            //Cargamos imagen al servidor.
            if(move_uploaded_file($_FILES["pac_foto"]["tmp_name"], $carpeta)) {
                 echo "Foto subida correctamente";
            } else { //Falso, imagen no cargo.
                echo "No se pudo guardar la foto.";
            }
        }
    }
}
?>

En caso de querer implementar AJAX y crear formularios dinámicamente, te dejo un ejemplo de SOes: insertar imagen con ajax


text:
Q: Alphabet conversion chart In reference to this question about typing in English and getting output in Bengali (in the way done by the O.P) , can someone give me a conversion chart as to which combination of English characters correspond to which characters in Bengali?

A: Download the manual.tex file from here and compile it. A table is given on page 8. Here is a screenshot.


text:
Q: How to create points in split of line feature? I had a point features shapefile and line feature shapefile. I created a new shapefile by splitting line feature with those points. Now, I lost the point shapefile. Is there anyway I can create point feature from line feature? I don't want vertices at every corners. I just want them at end of each line feature.

A: You can create a point layer from a line in QGIS using the 'extract vertices' tool: Vector | Geometry tools | Extract vertices from the menu bar, or search for the tool using the locate functionality (ctrl-K or cmd-K).


text:
Q: DistributionS4 R Package Been trying to load a data since ever. load("Raw Inputs/PHL.RData") only to encounter repeated errors below.
Loading required package: DistributionS4
Error in .requirePackage(package) :
  unable to find required package 'DistributionS4'
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :

Please help :(
Update: DistributionS4 does not exist, hence installing the said package seems to be troubling.

A: I highly recommend you, to use:
install.packages("DistributionS4", dependencies=TRUE)

Because it would also install the dependencies 'DistributionS4' depends on etc.

dependencies: logical indicating whether to also install uninstalled
            packages which these packages depend on/link
            to/import/suggest (and so on recursively).  Not used if
            'repos = NULL'.  Can also be a character vector, a subset of
            'c("Depends", "Imports", "LinkingTo", "Suggests",
            "Enhances")'.


text:
Q: argument 1 must have a "write" method - creating csv file from json I am making a call to the AWS API using boto3 and Python and I am writing the JSON response to a JSONfile. I am then trying to convert the JSON file to a CSV file. When I attempt to do this with the csv writer() method, I get the above error and I am not sure why.
Code:
def ResponseConvert():
    dynamo = boto3.client('dynamodb')

    response = dynamo.scan(
    TableName='XXXX'
    )

    with open('vuln_data.json', 'w') as outfile:
        json.dump(response, outfile, indent=4)

    f = open('vuln_data.json')
    data = json.load(f)
    f.close()

    f = csv.writer(open('vuln_data.csv', 'wb+'))

    f.writerow(data.keys())
    for row in data:
        f.writerow(row.values())

ResponseConvert()

Traceback:
Traceback (most recent call last):
  File "response_convert.py", line 21, in <module>
    ResponseConvert()
  File "response_convert.py", line 19, in ResponseConvert
    f.writerow(row.values())
AttributeError: 'unicode' object has no attribute 'values'

A: CSV writers expect a file handle, not a filename.
with open('filename.csv', 'w') as f:
    writer = csv.writer(f)
    ...

You probably want a DictWriter instead, by the way.  Don't rely on the order of keys and values matching up.


text: Q: Dynamic interactive line/bezier curve in XPCE Prolog My task is to connect in xpce prolog two squares, each of which equipped with a move_gesture, with a line/bezier curve in such a way that the line is moved along with the objects; does anyone know how this can be done or whether this is possible?


text:
Q: Sending a message from one system to another using websockets I have installed python-mod-pywebsocket on my ubuntu system. I'm trying to test websocket. When I send and receive a message in the same html file, then it works fine, but when I'm doing that in different files, it doesn't work as expected. I'm pasting the codes below
Websocketsend.html
<!DOCTYPE HTML>
<html>
<script type="text/javascript">
function WebSocketTest()
{

    var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function(){ws.send("Hello!!!");
            alert("Message sent!!!");};
}
</script>
<body>
<button onclick="WebSocketTest()">Send</button>
</body>
</html>

websocketreceive.html
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function(){alert("Connection open");};
ws.onmessage = function(evt)
{
alert("Message received");
};
</script>
</body>
</html>

I've put these two files in my /var/www directory. I ran the socket server on port 9998 and then opened two different tabs in google chrome to urls localhost/websocketsend.html and localhost/websocketreceive.html respectively. In the first tab, it displays an alert box stating "Message sent", in the second tab, it shows an alert box saying "Connection open", but I can't see an alert box saying "Message received" in the second tab. Can anyone help me out?
I may be asking a very trivial or silly question, but I'm new to websockets and would appreciate any help.
Thanks in advance


text:
Q: How to find an angle to rotate vector to align with a point
We know the value of point $T$ is $(x, y)$.
From $(0, 0)$ there is a line to point $p$ (I'll call this line $D$) with length $d$ and at that point, there is a vector (I'll call it $V$) that has an angle $\theta$ with $D$.
The problem is how to find an angle $\theta'$ that makes $V$ align with $T$?
I've tried to calculate $\theta'$ by

*

*Calculate $l = \text{distance from T to (0, 0)}$

*Find $r$ by using law of cosine $r = d\cos{\theta} \pm \sqrt{l^2 - d^2\sin{\theta}}$

*Using $r$ to create a circle from point $T$ with radius $r$ and find an intersection point $p'$ with circle from $(0, 0)$ with radius $d$

*Calculate the distance between $p'$ and $p$ and use it as a base of a triangle that has point $p$, $p'$ and $(0, 0)$ as a vertex

*We can calculate $\theta' = 2\arctan{\frac{0.5 \times \text{triangle_base}}{d}}$

Is there a simpler way to solve this problem?

A: The equation of the line before rotation is
$ r(t) = D + t V $
In terms of coordinates, this is
$ r(t)= (D_1, D_2) + t (V_1, V_2) $
This is the vector equation of the line.  Define the perpendicular to the line by
$N = (-V_2, V_1) $
then it follows that the algebraic equation of the line is
$ N \cdot ( r - D ) = 0 $
After rotation by an angle $\theta'$ counterclockwise, the image of a point $r$ is $r'$ given by
$ r'(t) = R(\theta') r $
where
$R(\theta') = \begin{bmatrix} \cos(\theta') && -\sin(\theta') \\ \sin(\theta') && \cos(\theta') \end{bmatrix} $
From this, it follows that
$ r = R^{-1}(\theta') r' = R^T (\theta') r' $
Hence, the equation of the rotated line is
$ N \cdot ( R^T r' - D ) = 0 $
Now we want point $ Q  $ (I've changed it from $T$ to $Q = [Q_1, Q_2]$) to lie on this rotated line.  Substitute $r' = A$
$ N \cdot ( R^T Q - D ) = 0 $
Everything here is known except $\theta'$.  Expanding the above equation,
$ [-V_2, V_1]\cdot (  [ Q_1 \cos(\theta') + Q_2 \sin(\theta') , - Q_1 \sin(\theta') + Q_2 \cos(\theta') ]^T - [D_1, D_2] ) = 0 $
Collecting terms, this is of the form
$ A \cos(\theta') + B \sin(\theta') = C $
where
$ A = -  V_2 Q_1 +  V_1 Q_2 $
$ B = - V_2 Q_2 - V_1 Q_1 $
$ C = -V_2 D_1 + V_1 D_2 $
And this equation has two solutions
$ \theta' = \phi \pm \cos^{-1} \left( \dfrac{ C }{\sqrt{A^2 + B^2}}\right) $
where $ \phi $ is the angle such that $ \cos(\phi) =\dfrac{ A }{\sqrt{A^2 + B^2}}$,  $\hspace{4pt}\sin(\phi) = \dfrac{ B}{\sqrt{A^2 + B^2}} $


text:
Q: Save XML file in SQL Azure Could anyone please say me how to declare a column of xml type in sql azure table and also how to save that file from a local computer to the sql azure table?
Thanks in advance :)

A: Not the exact answer you are looking for but here what you can do,

*

*Save the file in BLOB, instead Azure Table. BLOB is structure designed for this purpose only.

*Secondly, you can store the BLOB url in your Azure Table.

*This will make your application easy to understand and also easy to implement.

*This will also help in reducing the size of your database, smaller database better performance

Hope this helps you.

A: Here is the short answer:
USE YourDataBaseName

GO
CREATE TABLE Something
([SomethingID] INT PRIMARY KEY IDENTITY,
[TheColumnYouWantToDeclare] XML)
GO
With EntityFramework and LINQ to SQL, you can read the xml content and save that to the column. Here is how you can do this. Of course, you can also write SQL queries but here is how I just solved the problem with LINQPAD.
var myEntityToAdd = new Something();
var xmlContent = System.IO.File.ReadAllText(@"C:\NameOfFile.xml");
var xdoc = XDocument.Parse(xmlContent).Root;
myEntityToAdd.TheColumnYouWantToDeclare = xdoc;
Somethings.InsertOnSubmit(myEntityToAdd);
SubmitChanges();
In Azure SQL tables, you can do a lot of things with XML. Here are three videos to help you:
https://channel9.msdn.com/Series/Using-XML-in-SQL-Server-and-Azure-SQL-Database/01
https://channel9.msdn.com/Series/Using-XML-in-SQL-Server-and-Azure-SQL-Database/02
https://channel9.msdn.com/Series/Using-XML-in-SQL-Server-and-Azure-SQL-Database/03


text:
Q: Three.js - Cannot 'See Through' Cube Face I have an array of three materials. One of these is a MeshBasicMaterial with transparent set to true, opacity set to 0.
I assigned this transparent material to the top face of a cube, expecting to see the inner walls of the other faces.
However, instead, the top face is simply not drawn (appearing white, like the background of the canvas) but not allowing me to 'see through' it.
How is this achieved?
(The final effect should simply be a box with the top open)
// FELT TEXTURE
var felt = new THREE.MeshLambertMaterial({
    map: THREE.ImageUtils.loadTexture('images/greenfelt.jpg')
});

// WOOD TEXTURE
var wood = new THREE.MeshLambertMaterial({
    map: THREE.ImageUtils.loadTexture('images/woodgrey.jpg')
});

// TRANSPARENT MATERIAL
var transparent = new THREE.MeshBasicMaterial({
    opacity: 0,
    transparent: true
});

var materials = new THREE.MeshFaceMaterial([
    felt,
    wood,
    transparent
]);

var cube = new THREE.CubeGeometry(RECTANGLE_WIDTH, RECTANGLE_HEIGHT, RECTANGLE_DEPTH );
    cube.faces[0].materialIndex = 1; // LEFT
    cube.faces[1].materialIndex = 1; // RIGHT
    cube.faces[2].materialIndex = 1; // BACK
    cube.faces[3].materialIndex = 1; // FRONT
    cube.faces[4].materialIndex = 2; // TOP (TRANSPARENT)
    cube.faces[5].materialIndex = 0; // BOTTOM

// RECTANGLE
var rectangle = new THREE.Mesh( cube, materials );

scene.add( rectangle );

A: Maybe your cubes are getting culled. By default, only the front of each face is drawn. Try setting material.side = THREE.DoubleSide for all cube materials (well the transparent material shouldn't need it, but all others).
felt.side = THREE.DoubleSide;
wood.side = THREE.DoubleSide;
var materials = new THREE.MeshFaceMaterial([
  felt,
  wood,
  transparent
]);


text:
Q: Working with dropdownlistbox in html I am using dropdownlist and one label in my html page. I want to change name of label
on selection of my dropdownlist box. How is it possible?
pls povide any help for me .

A:     <select id='derp' onchange="changeVal(this,'changeme');">
        <option value='test'>test</option>
    </select>
    <input id='changeme' />

[EDIT]
re-reading the question it sounds like you are trying to change the name of the input box...if that is the case, change changeEl.value to changeEl.name

A: Check this example.
It will change the attribute 'name' of your label, and its text content (reading its new name attribute value) to see the change in effect.

<select name="selectcity" onchange="changeValue(this);" >
    <option>Mumbai</option>
    <option>Delhi</option>
</select>
You selected:

A: HTML:

            <select id="ddlLanguage" style="width: 230px;">
                <option value="0">[Select]</option>
                <option value="1">Afrikaans</option>
                <option value="2">Akan</option>
                <option value="3">Albanian</option>
                <option value="4">American</option>
            </select>

            Selected Value:

JQUERY:
$(document).ready(function(){
    $("#ddlLanguage").change(function(){
        var vSelectedValue  = $("option:selected",$(this)).text();
       $("#lblChange").text(vSelectedValue);
    });
});

CLICK HERE TO SEE THE DEMO


text:
Q: homotopy quotient categories (Trying to rephrase an earlier question)
In topology, a continuous map $f: X \to Y$ has a ``homotopy cofiber" $Cf$ included in a cofiber sequence
$$
X \to Y \to Cf \to \Sigma X \to \Sigma Y \to \Sigma CF \to \ldots
$$
when $f$ is a cofibration, the cofiber is homotopy equivalent to $X/Y$.
Now, if $Y$ is a category, say, of modules over a ring $R$, and $f$ a functor from another category (e.g. embedding of projective modules into all modules), is there a similar cofiber category and a cofiber sequence?


text:
Q: bluebird + mongoose error: "Can't use $__ with Array." I was trying to use bluebird + mongoose to query DevHiin instances for each Club respectively like the following code:
the data structure of DevHiin.clubs is:
  , clubs  : [{ type: Schema.Types.ObjectId, ref: 'Club' }]

and club_M is an instance of the Club schema:
  User.findOne({"_id": req.user._id})
    .populate('clubs', '-textIndex')
    .exec(function (err, user) {
    if (err) res.status(500).json(err);

    if (user.clubs) {
      var clubs_M = user.clubs;

    for (c = 0; c < clubs_M.length; c++) {
        var club_M = clubs_M[c];

        if (club_M.lst > lstDate) {

          serverData.clubs.push(club_M);

          var ciinPromise = DevHiin.find({"clubs": {$elemMatch: club_M}, "ts": {"$gt": lastSyncTime}})
            .populate('uId', '_id username', null, null)        // get necessary user info for a hiin
            .lean()
            .sort("ts")
            .limit(10)
            .execAsync();
          promises.push(ciinPromise);
        }
      }

      Promise.all(promises).then(function (ciinArrays) {
        serverData.ciinArrays = ciinArrays;
        callback(ciinArrays);

      }).catch(function (err) {
        callback(err);
      });

unfortunately, I got the following error info:
"Error: Can't use $__ with Array.
at SchemaArray.castForQuery (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/schema/array.js:188:13)
at SchemaArray.cast$elemMatch (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/schema/array.js:336:23)
at SchemaArray.castForQuery (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/schema/array.js:191:19)
at module.exports (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/cast.js:196:39)
at Query.cast (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/query.js:2350:10)
at Query.find (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/query.js:999:10)
at Query.exec (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/query.js:1984:17)
at Query.tryCatcher (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/bluebird/js/main/util.js:24:31)
at Query.ret [as execAsync] (eval at <anonymous> (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/bluebird/js/main/promisify.js:1:0), <anonymous>:12:23)
at EventEmitter.<anonymous> (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/controllers/sync.js:189:18)
at EventEmitter.<anonymous> (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/node_modules/mpromise/lib/promise.js:175:45)
at emitOne (events.js:77:13)
at EventEmitter.emit (events.js:169:7)
at Promise.safeEmit (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/node_modules/mpromise/lib/promise.js:81:21)
at Promise.fulfill (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/node_modules/mpromise/lib/promise.js:94:24)
at Promise.resolve (/Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/promise.js:113:23)
at /Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/lib/query.js:1174:16
at /Users/vince-fan/WorkSpaces/MEAN/V_Starter/node_modules/mongoose/node_modules/kareem/index.js:109:16
at doNTCallback0 (node.js:408:9)
at process._tickCallback (node.js:337:13)"

is this an bluebird promise error, or an mongoose error? how can I fix it?

A: From the code it looks like you are trying to query using $elemMatch on an array value specified as the query criteria expression. I believe you need to use the $in instead, this selects the documents where the value of the clubs field equals any value in the specified array, which is stored by the variable club_M in your case. Thus your query should look like this:
var ciinPromise = DevHiin.find({"clubs": {"$in": [club_M._id]}, "ts": {"$gt": lastSyncTime}})

A: for querying field holds an array, simple treat it as normal field query.
My fixed code:
              var ciinPromise = DevHiin.find({"clubs": club_M._id, "ts": {"$gt": lastSyncTime}})


text:
Q: Using php regex to translate output buffer, but not within HTML tags I have an array with strings to translate ($translation), and I want to use it to translate the output buffer. However, it should not replace within html tags. I have tried using php DOM, but this is too slow and probably too complex for what I want to do.
I currently use this code, but this of course also translates between tags.
$output = ob_get_clean();

foreach($translation as $original => $translated) {
    $output = str_replace($original,utf8_encode($translated),$output);
}

I guess I should use a regular expression to replace not within HTML tags, but I can't seem to find the correct expression to do this. Can anyone help? Thanks.

A: aside from opinions on the orginial idea:
i would not use regexp for that for performance reasen. you could utilize strpos($html,'<') + strpos($html,'>') in combination with substr to extract string by string.
But if somebody(including you) ever has to change the results at another point, then i suggest you go the extra mile and implement a 'proper' translation.
My recommendation:

*

*look into gettext

*filter out the strings like mentioned above and generate a .mo -file

*encapsulate the strings between the tags with the gettext-functions (like here)


text:
Q: What does probability density mean and how can it be greater than 1? I have been reading several other questions, but I have not managed to understand the concept.
I have been taught that,
The pdf allows determining the probability that a random variable
$X$, take infinite real values between a range $a, b$. Therefore is defined as: $P(a\le X\le b)=\int_a^bf(x)\,\mathrm dx$. And the area under the curve between the same interval, represents the probability.
I thought I had understood the concept, however I have read in other answers to similar questions, that:
$1)$ PDF is not a probability
$2)$ Then, according to the $1)$, it is unbounded.
Then it comes to my head to ask,
What is the probability density function really?
And I thought the answer is in the name itself, specifically in density.
I read that the pdf, gives me information about the probability of the continuous random variable, but NOT the probability. But, what is this information? I have a slight idea of what this information can be, it would be how acumulated are the values in a certain range $a, b$ and hence the name density, but I do not even know if this is correct.
So, what does the probability density function really represent? Without calculus concepts, if not that, I want to understand the concept.
And if the concept of probability density function is not a probability, Why is it associated with the area under the curve? If it is assumed that the area under the curve is the probability?

A: The PDF is a density. As such it is related to a primal measure defined on the range of the random variable $X$. If $X$ is real-valued and takes values in some predefined interval $(a,b)\>\subset{\mathbb R}$ then the primal measure available in this range is the euclidean measure, generated by the idea $\mu\bigl([u,v]\bigr)=v-u$ when $u\leq v$.
If $X$ is a nice continuous random variable then the probability that $X=c$ is zero for all $c\in(a,b)$. But for any short interval $[u,v]$ of positive length we may expect that the probability $P\bigl(X\in [u,v]\bigr)$ has an interesting positive value. This value depends (i)  on the place of $[u,v]$ within the range $(a,b)$ of $X$ and (ii) on the length $v-u$ of this interval. It is the essence of a density that this dependence can be covered in a formula of the form
$$P\bigl(X\in[u,v]\bigr)\approx f(u)\mu\bigl([u,v]\bigr)=f(u)\>(v-u)\qquad(0<v-u\ll1)\ .$$
If we have such a formula for a given random variable $X$ then the function $f$ is called the probability density of $X$. For a given $u\in(a,b)$ the value $f(u)$  does the following: If $J$ is a very short interval containing the point $u$ then $$P(X\in J)\approx f(u)\>\mu(J)\ ,$$
where $\mu$ denotes the euclidean measure on ${\mathbb R}$.


text:
Q: Access Phone Gallery in Web Application I am developing a Web Application using Aurelia framework. I am trying to access Phone Gallery. There is an option to upload image. When someone clicks on upload then I want to access directly Phone gallery to upload image. Is this possible in Web Application ?

A: Yes, the input type file will open the phone gallery
<input type="file" accept="image/png,image/jpeg">


text:
Q: set_at called multiple times in Google Maps V3 API poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);

google.maps.event.addListener(map, 'click', addLatLng);

function addLatLng(event) {

    var path = poly.getPath();

    // Because path is an MVCArray, we can simply append a new coordinate
    // and it will automatically appear
    path.push(event.latLng);

    // Add a new marker at the new plotted point on the polyline.
    var marker = new google.maps.Marker({
        position: event.latLng,
        title: '#' + path.getLength(),
        map: map,
        dragable: false,
        clickable: true,
        name: name,
        raiseOnDrag: false,
    });

    //This event is fired when setAt() is called. The event passes the index that was passed to setAt() and the element that was previously in the array at that index.
    google.maps.event.addListener(path, 'set_at', function(index,oldWP) {
        //called when editing the path
        //we need to remove the (current) marker and add a new one at the position

    });

    google.maps.event.addListener(path, 'insert_at', function(index) {
        //when insert happens not at the end of the path but somewhere in the middle
        //We need to completely rerender all makers

    });
}

Google documentation: This event is fired when setAt() is called. The event passes the index that was passed to setAt() and the element that was previously in the array at that index.
However this event is called x times (where x is the # elem of the path).
Anybody know why this is and if this can be prevented (asside from keeping a counter in memory).

A: What you are doing here is that you are adding new listeners to the path for each time the path changes. What you want to do is to only add the listeners once. I think this should do the trick:
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
var path = poly.getPath();

google.maps.event.addListener(map, 'click', addLatLng);

function addLatLng(event) {

    // Because path is an MVCArray, we can simply append a new coordinate
    // and it will automatically appear
    path.push(event.latLng);

    // Add a new marker at the new plotted point on the polyline.
    var marker = new google.maps.Marker({
        position: event.latLng,
        title: '#' + path.getLength(),
        map: map,
        dragable: false,
        clickable: true,
        name: name,
        raiseOnDrag: false,
    });
}

 //This event is fired when setAt() is called. The event passes the index that was passed to setAt() and the element that was previously in the array at that index.
google.maps.event.addListener(path, 'set_at', function(index,oldWP) {
    //called when editing the path
    //we need to remove the (current) marker and add a new one at the position

});

google.maps.event.addListener(path, 'insert_at', function(index) {
    //when insert happens not at the end of the path but somewhere in the middle
    //We need to completely rerender all makers

});


text:
Q: Amazon like refined filtering in solr We need to implement drill down search like Amazon.

If any supplier is selected then,
currently it disabled rest of suppliers as solr facet only returns that selected filter.
query: supplier:supplierId
Though above query retuns multiple Screen Color/Screen Size, but on further selection, only the selected element is returned per filter section.
Any help to make it work like Amazon.com 's refined filtering will be much appreciated.

A: To provide multi-select faceting, you need to tag the filter involved so that you can exclude it when faceting on the corresponding field. This can be achieved using both the tag and ex local parameters.
Solr Ref Guide - Tagging and Excluding Filters :

To implement a multi-select facet for a given field, a GUI may want to still
  display the other field values and their associated counts, as if
  the corresponding filter constraint had not yet been applied.
To return counts for the field values that are currently not selected,
  tag filters that directly constrain the field, and exclude those
  filters when faceting on it.

For example, for a query that would originally look like :
q=mainquery&fq=supplier:supplierId&facet=true&facet.field=supplier

You would do the following :
q=mainquery&fq={!tag=sup}supplier:supplierId&facet=true&facet.field={!ex=sup}supplier


text:
Q: Which button is pressed in a non-blocking QMessageBox? I'm trying to make a non-blocking QMessageBox as described here.
In the slot msgBoxClosed() I only get a QAbstractButton* back, so how can I check which of the buttons (QMessageBox::Yes, QMessageBox::No) was pressed?

A: You can use the following function to determine the button QMessageBox::standardButton(QAbstractButton *button). For example:
StandardButton btn = msgBox->standardButton(button)
if (btn == QMessageBox::Ok) {
    [..]
}


text:
Q: Can we say anything about the zeros and Galois group of the polynomial $(x^p-a)^{p^2}-p^{p^2+1}x+p^{p^2} a=0$? Let $p$ be an odd prime number  and $\mathbb Q_p$ be the $p$-adic number field. Let $K=\mathbb Q_p(a)$ be the extension by $a=p^{\frac{p^2+1}{p^3-1}}$.
Consider the polynomial $f(x)=(x^p-a)^{p^2}-p^{p^2+1}x+p^{p^2}a \in K[x].$

*

*Given that $f(x)$ is irreducible over $K$ and its splitting field, say $F$, is of degree $\frac{p^3(p^3-1)}{2}$ i.e., $[F: \mathbb Q_p]=\frac{p^3(p^3-1)}{2}$.

Can I find the zeros of $f(x)$ over its splitting field?

Can we expect information about the Galois group of its splitting field? For example, whether the Galois is cyclic or not?

Since $p$ is an odd prime, $2 \nmid p^3$ but $2 \mid \frac{p^3-1}{2}$.
So $[F: \mathbb Q_p]=\frac{p^3(p^3-1)}{2}=p^3 \cdot \frac{p^3-1}{2} =[F:K][K: \mathbb Q_p]$.
For $p=3$, we get $\frac{(p^3-1)}{2}=13$. So this factor corresponds to a cyclic extension with Galois group isomorphic to $\mathbb Z_{13}$, while the other factor $[F:K]=p^3=27$. So the Galois group $G$ of the splitting field of $f(x)$  is isomorphic to one of the following: $$\mathbb Z_{13} \times \mathbb Z_{27}, ~ \mathbb Z_{13} \times \mathbb Z_{9} \times \mathbb Z_{3},~ \mathbb Z_{13} \times \mathbb Z_{3} \times \mathbb Z_{3} \times \mathbb Z_3.$$
So there is a possibility $G$ is cyclic if $G=\mathbb Z_{13} \times \mathbb Z_{27}.$
But I cannot get any exact conclusion.
I am expecting the zeros of $f(x)$ to be "$p$ to the exponent type similar to $a$" up to multiplication by a unit of $\mathbb Q_p$.
Thanks


text:
Q: BitArray conversions and data lengths I'm creating a software package that takes 16 boolean values at a time, puts them into an array of bits, then sends them off to a PLC to be unpacked and used by the PLC. My question is two-fold:
1) If I make a BitArray(16), will it only occupy 16 bits of data or does the BitArray object automatically include extra data in there as part of the object (I assume it's only 16 bits but can't find much real good confirmation on it so far) and
2) The PLCs are expecting a 16-bit integer (short) for the communication coupler to work as necessary, therefor I figured I could simply cast the BitArray into a short, but I need a list of 1's and 0's, not "true" and "false" - so what would be the best way to do this? Some sample code of what I have in mind below:
/*  Pack bits into a container to send them as one item */
var bitContainer_1 = new BitArray(16);
bitContainer_1[0] = result.Toggle_Signal;
bitContainer_1[1] = result.Auto_RFO;
bitContainer_1[2] = result.Spare_1;
bitContainer_1[3] = result.Spare_2;
bitContainer_1[4] = result.HMI_Horn_Necessary;
bitContainer_1[5] = result.HMI_Horn_Urgent;
bitContainer_1[6] = result.HMI_Horn_Emergency;
bitContainer_1[7] = result.Spare_3;
bitContainer_1[8] = result.Sys_1_Auto_Ready;
bitContainer_1[9] = result.Sys_1_Auto_Active;
bitContainer_1[10] = result.Spare_4;
bitContainer_1[11] = result.Spare_5;
bitContainer_1[12] = result.Sys_2_Auto_Ready;
bitContainer_1[13] = result.Sys_2_Auto_Active;
bitContainer_1[14] = result.Spare_6;
bitContainer_1[15] = result.Spare_7;
short packagedBits_1 = Convert.ToInt16(bitContainer_1);

I assumed I could do something to the booleans before going into bitContainer to cast them to 1 or 0 and found out that didn't seem to work, so I wanted to see what any/all my options may be while avoiding lots of if(true){var = 1} else{var = 0} type scenarios since I'm rather unfamiliar with this type of task. As these communications will be in charge of machine behaviors, reducing overhead and time to package these & send them is vital.

A: 1) BitArry(16) takes up more space than 16 bits.  Try a ushort for something that takes exactly 16 bits.
2) If you want speed I would recommend you used a ushort and performed bitwise operations on it.  You could set it like this:
    bitContainer = (ushort)(result.Spare_7 << 15 | result.Spare_6 << 14...)

then you can set or reset each bit as you required.
Edit: The bitwise OR operator '|' is used here to chain each entry bit together into the final ushort variable.  The '<<' operator shifts a value n number of bits to the left, so this is bringing in each 1 or 0 in result.xxxx to it's correct place in bitContainer.


text:
Q: Moment JS Parse strange behaviour I'm using moment.parse String+Format method
when I call moment("=min(C2:C4)", 'DD/MM/YYYY') it evaluates to valid date
Sun Apr 02 2017 00:00:00 GMT+0300 (FLE Daylight Time)
I can't understand how moment parses "=min(C2:C4)" to valid date. Just wonder, some one can explain.

A: From Moment.js docs:

Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior.

Short answer: because of your expected loose format, moment parses the 2 as the day and the 4 as the month.
Long answer:
Visualizing this might be easier if you run your command in a console and view the results. I'd recommend taking a look there first, and I'll explain the important parts below.

*

*Date string vs. format

You've specified your string as "=min(C2:C4)" and your format as DD/MM/YYYY, so moment is looking for a date in that general format: a day followed by a month followed by a year.

*moment._pf.unusedTokens[]
This is an array and has one value, 'YYYY'; the parser did not find a year, but it did find a day and a month... hmmm.

*moment._pf.unusedInput[]
This tells us more - an array with three values:
1. '=min(C'
2. ':C'
3. ')'

Looks like moment found the 2 and the 4 to match day and month. You'll find these values in the moment._pf.parsedDateParts array.
So, that should explain why the date is April 2, 2017. The month of 3 (this is the finalized month, not the actual value parsed. Months are zero-indexed, so it's back to "4") and the day of 2. No year was given, so moment assumes it's the current year. No time was given, so it assumes the start of the day.
If you don't want this behavior you should pass a 3rd / last param as true (strict matching). Check http://momentjs.com/docs/#/parsing/string-format/ for more details.


text:
Q: Why do gifs sent to Twitter using UIActivityViewController end up as jpg? I'm trying to send a gif to twitter using  this code:
NSURL *imagePath = [[NSURL alloc] initWithString:[[NSBundle mainBundle] pathForResource:@"example" ofType:@"gif"]];
NSData *gifItem = [NSData dataWithContentsOfURL:imagePath];
NSArray *sharingItems = @[gifItem, @"TEST"];
UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:sharingItems applicationActivities:nil];
[self presentViewController:activityController animated:YES completion:nil];

However the gif ends up as a single frame jpg on Twitter feed.
I've tried several gifs, some of them end up fine, some end up as a single frame. There's not much difference between them, maybe size, but it's still below 5MB limit Twitter has.
I've tried to upload the gif to Giphy first and display it in feed, like in case of facebook, but then the gif is not displayed in line.
I've checked some other apps on ios which do the same I want to, and they share quite long gifs [up to 5 seconds, large in resolution] and it works for them fine. Don't know why mine end up as a single frame jpg.
Thanks
Krystian
EDIT:
after making the gif below 200KB, the file became playable inline on twitter. But I am certain that the other gifs that are playable inline on twitter are far bigger.


text:
Q: Finding doubly periodic solutions to partial differential equations Say I have a certain PDE in real variables $x$ and $y,$ which might be nonlinear, so that we can't necessarily just throw a Fourier series at it.
By way of some intuition, let's say, I have a very strong feeling that this equation should admit solutions which are periodic in both $x$ and $y.$ These might be in the form of some combination of elliptic functions, theta functions, etc.
Does anyone know any kind of methods that could be of use in going about finding solutions with two periods, given I have some vaguely intuitive sense of being pretty sure they should exist, say by some loose physical argument of plausibility (not being concerned with rigour at this stage)?
I'm not looking for a general method, but any tools at all, references, whatever, anything which might be useful for attacking a PDE if I have good reason to think I can express a solution in terms of e.g. Jacobian elliptic functions, or theta functions, etc.
Thanks to all who give this a go or who can point me in the right direction.


text:
Q: What does "div.container" and mean in CSS Currently tweaking a theme and have tried searching for an answer to this question to this! I'm not stuck - but more just want to know the answer out of curiosity.
I understand that

*

*"#" means an id and

*"." means a class.

I've also been reading on this post about how you can add specificity to your html/css through combination of elements/ids/classes ie:
a.fancy { color: red; } /*an element that has an anchor and a class = red.*/

However the code I am working on has the following elements that I don't understand:
div.footer {background-color: {{ settings.footer_color }};

Why would you specify "div.footer" as both the div and the class when simply using a "." would suffice? In my mind there would be no point when the class ".footer" could be used without a div?
Hope you can help me work this one out!

A: div.footer means you are targeting only
 elements with the class .footer.

This is targeted.

This isn't targeted, as it isn't a div with the class .footer.

div .footer, however, would target all elements with the class .footer that are descendants from
 elements.

This is targeted.

But this isn't targeted.

A: div.footer means the element must both BE a
 and HAVE the class footer.
.footer would trigger for any element with class footer; for example, a <span class="footer".

A: With the new implementation of html5  is a legitimate tag just like
 or
. As confusing as it may be the period . before the footer declaration constrains it to a class name instead of the tag.
So in your case: div.footer =
 with class name footer =
.
There are numerous reasons why you may make such a declaration.
Sample html

Footer only

Div only

  Footer tag; DIFFERENT

Example Css
div {
 border: 1px solid red;
}
.footer {
 background: blue;
 color: #fff; /* white font color */
}

Depending on what you want to do, let's use the specific div.footer examples to show what we can do.back
Inheritance
By inheritance, div.footer will inherit "3 properties" -> background, color and border from the div and .footer declarations.
Now you may want to override some of these properties so...
Overriding Property
Use something like div.footer { color: red; } this will override the white color.
Layout Insight
The beauty of css is that you can use declaration to give you "insight" on what the html markup will be laid out as.
Omitting properties I would write the css as follows:
#footer {}
#footer ul {}
#footer ul li {}
#footer p {}
#footer p a {}

The html:

List 1

LIst 2

Hello! Copyright website company name.

You could then reverse engineer the html through just css because of the descendent character use. This maximizes the power of "cascading".
--
NOow I hope some of this has given you some insight. A few other pointers are this:

*

*Typically a webpage has only one footer. When there is only one of something use the # id selector ALWAYS.

*Use classes to not only apply styles to multiple elements but to also provide "meaning to your markup" -> go back to the principle of "layout insight" to understand what I mean.

*div.footer should could more simply be .footer Now, it may be necessary to include div just to say "I only want to apply this class to divs only" and in that case go for it. But defining all your declarations with div.someClasName is not all that valuable.

*DO NOT use names of tags as classnames. div.div is very confusing - especially if you are programming for a while. Therefore, since  is now a legit tag you shouldn't apply it as a classname. On the other hand "#footer" could be argued differently because it can only exist once in a webpage.

A: It's about specificity. div.footer is more specific (a div with that particular class) than .footer (any element with that class).
As to when to use one or the other, it really depends on the markup and CSS you are building.


text:
Q: Regex Grouping a Simple URL How can get this regex to select every group that starts with :text/? So it starts with a : and ends with a / unless it's the last string.
Sample URL
/site/:param/anything/:s

Regex so far is this:
(:.+/)

I'm so close but so far.
So it would select the bolded items:
/site/:param/anything/:s

A: I think this should do it:
(?<=/:)[^/]+

There's no need to check explicitly for the terminating / or end of string, since either of them will end the [^/]+ match.

A: This would select the first occurence:
(:[^\/]+)(\/|$)

I don't think there is a way for a regex to match an indefinite number of entries in a given string. You'll have to repeat the above regex for that. Example in Ruby:
"/site/:param/anything/:s".match(/(:[^\/]+)(\/|$)/)


text:
Q: Ansible version compare Trying to compare the installed package version and upgrade to latest version in Ansible, Blocked at when package is not installed in server.
- debug:
    msg: "Installed version is null or lower than {{ gcc_new_version.stdout }}"
  when: 'gcc_version.stdout == "" || gcc_version.stdout is version(gcc_new_version.stdout, '<')

Error:
fatal:  FAILED! => {"msg": "The conditional check 'gcc_version.stdout == "" || gcc_version.stdout is version(gcc_new_version.stdout, '<')' failed. The error was: template error while templating string: expected token 'name', got '|'. String: {% if gcc_version.stdout == "" || gcc_version.stdout is version(gcc_new_version.stdout, '<') %} True {% else %} False {% endif %}\n\nThe error appears to be in 'ansible/roles/linux/tasks/gcc.yml': line 24, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- debug:\n  ^ here\n"}

A: I think the issue is the syntax in when condition. Conditions are in Jinja context, so use of single quotes ' around conditions is not required. Also the or keyword can be used instead of ||.
- debug:
    msg: "Installed version is null or lower than {{ gcc_new_version.stdout }}"
  when: (gcc_version.stdout == "") or (gcc_version.stdout is version_compare(gcc_new_version.stdout, '<'))


text:
Q: Is in a column with special characters in python I have a dataframe such as
COL1
jcf7180001991334_2-HSPs_+__SP_1
jcf7180001991334:23992-26263(+):SP_2
jcf7180001988059:2889-4542(-):SP_3

and a list :
the_list['jcf7180001991334_2-HSPs_+__SP_1','not_in_tab1','jcf7180001991334:23992-26263(+):SP_2','not_intab2','not_intab3','jcf7180001988059:2889-4542(-):SP_3']

and by iterating over that list such as :
for element in the_list:
 if element in df['COL1']:
  print(element, " in df")
 else:
  print(element, " not in df")

I should then get the following output :
jcf7180001991334_2-HSPs_+__SP_1 in df
not_in_tab1 not in df
jcf7180001991334:23992-26263(+):SP_2 in df
not_intab2 not in df
not_intab3 not in df
jcf7180001988059:2889-4542(-):SP_3 in df

But instead I cannot fint any o them in the df and i get :
jcf7180001991334_2-HSPs_+__SP_1 not in df
not_in_tab1 not in df
jcf7180001991334:23992-26263(+):SP_2 not in df
not_intab2 not in df
not_intab3 not in df
jcf7180001988059:2889-4542(-):SP_3 not in df

I guess it is because of the special characters within the element such as parentheses and + or - ? Does someone know how to deal with that ?

A: By default, in checks whether the value is in the index.
Then, you may look in the values  like this df['COL1'].values
import pandas as pd
data = {
  "COL1": ['jcf7180001991334_2-HSPs_+__SP_1', 'jcf7180001991334:23992-26263(+):SP_2', 'jcf7180001988059:2889-4542(-):SP_3']}

df = pd.DataFrame(data)

the_list=['jcf7180001991334_2-HSPs_+__SP_1', 'not_in_tab1', 'jcf7180001991334:23992-26263(+):SP_2', 'not_intab2', 'not_intab3','jcf7180001988059:2889-4542(-):SP_3']

for element in the_list:

 if element in df['COL1'].values: # Here You should look in The values
  print(element, " in df")
 else:
  print(element, " not in df")

[Output]
jcf7180001991334_2-HSPs_+__SP_1  in df
not_in_tab1  not in df
jcf7180001991334:23992-26263(+):SP_2  in df
not_intab2  not in df
not_intab3  not in df
jcf7180001988059:2889-4542(-):SP_3  in df

A: Give this a try:
["in df" if x in df['COL1'].values else "not in df" for x in the_list]


text:
Q: Agregar una nueva columna en SSIS Mi caso es el siguiente:
Tengo dos conexiones a dos bases diferentes en una consumo una fecha máxima, con el script
SELECT MAX (open_time) AS fecha
FROM base1.dbo.tabla1

Esto me devuelve una fecha.
En la otra base de datos tengo unos campos e intento crear una columna con la información de la otra tabla base2.dbo.tabla1.
Esto lo estoy haciendo con SSIS por medio de una ETL y una unión pero aún no me sale la transformación.


text:
Q: Coverting epoch time value into a timestamp(6) in teradata How do I covert epoch time value into a timestamp(6) in teradata ?
Lets take 1336987231051 as the example epoch time ( note this is in milliseconds, where as epoch time is in seconds), I did something like this
// miliseconds epoch time
select cast(1336987231051 as timestamp(6))

// seconds epoch time
select cast((1336987231051/1000) as timestamp(6))

and I get this error message for both of the above select statements :
[Error] Script lines: 12-12 ------------------------
[Teradata Database] [TeraJDBC 13.10.00.31] [Error 5407] [SQLState HY000] Invalid operation for DateTime or Interval.

I verified in http://www.epochconverter.com/ that 1336987231051 is valid epoch time.
What is the right sql for this in teradata ?

A: select
    cast(cast(700101 as date) + seconds_from_epoch / 86400 as timestamp(6)) +
        (seconds_from_epoch mod 86400) * interval '00:00:01' hour to second
from my_table

A: Simplest way to convert EPOCH to TERADATA TIME.
SELECT
   1336987231051/1000 as unix_epoc_time   ,
   to_timestamp(unix_epoc_time) utc,
   cast(cast(utc as char(19))||'+00:00' as timestamp(0) with time zone) AT LOCAL
;

*

*If your epoch is 10 digit, you don't need /1000.

*Remember, Unix time is in UTC.

*Your system will treat this "utc" as local. So, let us make it understand that it is UTC by adding "+00:00" and then convert it to your LOCAL using AT LOCAL OR using either of these "America Central" , "America Eastern" , "America Mountain" etc.


text:
Q: Notepad ++ Find String and place symbol at beginning of line I have 5000 lines. I need to find if a line contains a certain word phrase such as "package" and put a "1%" at the beginning of it. How would I do this with replace in notepad++?
An example being:
DOGS AND CATS
if the line contains the word "DOGS" anywhere in the string make the new line:
1% DOGS AND CATS

A: *

*Ctrl+H

*Find what: ^(?=.*DOGS)

*Replace with: %1

*CHECK Match case

*CHECK Wrap around

*CHECK Regular expression

*UNCHECK . matches newline

*Replace all
Explanation:
^               # beginning of line
(?=.*DOGS)      # positive lookahead, make sure we have DOGS somewhere in the line

Screenshot (before):

Screenshot (after):


text:
Q: TPS55340 boost circuit not making desired voltage I've created a 12 VAC -> 24 VDC boost power supply based on the TPS55340 regulator.  I used a reference design from TI's WEBENCH tool, with some selected part substitutions for parts availability, coupled with a pretty standard AC->DC rectifier rated for 3 A.  The load is a series/parallel array of LEDs (\$V_f = 2.7-3.7\text{ V}\$).  Each series of 6 LEDs should draw 20 mA and total 240 mA.
The problem I'm having is that the voltage as measured between the +24V NET and GND is approximately 17 V, which only gives approximately 2.5 mA to each series of LEDs and makes them very dim. The datasheet (linked above) says that the output voltage is selected via the divider attached to the FB circuit and computed via $$V_{\text{out}} = 1.229\text{ V} \times \left(\frac{R_{\text{FBT}}}{R_{\text{FBB}}} + 1\right)$$
The standard example - which I happen to be using - is 187k/10k for 24 V.  I did pull those two resistors off a board and measure them to verify.
Any pointers to send me on the right direction here?  I'm really new to hardware design but this seems like a pretty straightforward boost circuit that I've screwed up somehow.
Critical Parts

*

*L1 -- SPM10040T-100M 10UH
5.8A 29.4MOHM

*L1_ALT -- RLF12560T-7R8N8R2 7.8UH 8.4A 12.24 MOHM

Entire BOM - Google Sheet
TI's Reference design

My Circuit as Built

Layout Top

Layout Bottom

A: Here's a simulation with 220µF post-rectifier cap.
The current source sims a boost regulator. Since it tries to output a constant 240mA at 24V, it will input roughly constant power (neglecting efficiency) so its input current is proportional to 1/Vin. So I've used a function source, with "v(vcc)>3" to set current to zero when voltage is below 3V (I'll assume the boost just shuts down, also this avoids a division by zero) and "0.45*12/V(VCC)" to simulate the boost input current. I realized after taking the screenshot that it should be 0.5A instead of 0.45A but whatever.

As you can see the input cap is too small, so as it discharges, the boost draws even more current (green plot) until it sucks all the energy out of the cap and shuts down.
Switching to 1600µF looks a lot better, the capacitor stores enough energy to last until the next AC half-period where it gets recharged.

When the cap voltage doesn't drop too much (just a few volts) the boost input current is constant enough that you can use the back of the envelope approximation of:
\$ dv/dt = i/C \$
\$ C = \frac{ i.dt }{ dv } \$
So if you want dv = 2V drop between periods ; dt is say 8ms because even with a 50Hz AC period the rectifier should conduct 20% of the time, and i=0.5A, then this gives a required capacitance of 2000µF. 1600µF is close enough, it should  work fine. 220µF is definitely not enough though.


text:
Q: Missing a rewrite flag? server 500 caused by .htaccess I currently have an htaccess file on my root dir. I created a NEW htaccess file inside of callbacks/api and entered this:
RewriteEngine on
RewriteBase /callbacks/api
RewriteRule ^(.*)\.(json|xml|csv|txt|printr)$ ./endpoint.php?api_request=$1&api_response_type=$2

I am following the same rewrite rules that I have in my other htaccess (that work just fine). However in this instance I pass the following URL:
domain.com/callbacks/api/v1/test_rest.xml

Inside of my endpoint.php file I have:
<?
//just making sure the 500 is not due to php
//so lets just dump the GET's
var_dump($_GET);
?>

Am i missing a flag required at the end of my rewrite rule?

A: Try this:
RewriteEngine on
RewriteBase /callbacks/api
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.(json|xml|csv|txt|printr)$ ./endpoint.php?api_request=$1& api_response_type=$2   [L]

I did not test the rule, just added 2 lines to prevent loops.


text:
Q: How to create conditional in routeconfig.cs I need to rewrite URLs based on a specific condition.  I tried to add the conditional check in the routeconfig.cs and enclose the different routes.MapRoutes() methods for the URL rewrites but that doesn't work.  When accessing the website, it displays the directory, which results in an error.
Here's an example:
routes.MapRoute(...)

ClassA classA = new Class();
if(classA.IsThisTrue()) {
  routes.MapRoute(...)
  routes.MapRoute(...)
}

routes.MapRoute(...)

If I remove the conditional, it works.
Is there some other way to do that?

A: You could use custom constraint for this:
public class MyCons : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        ClassA classA = new Class();
        return classA.IsThisTrue();
    }
}

Then use it in your routes:
routes.MapRoute(
    name: "myRoute",
    // your own route
    url: "myUrl/{myParam}",
    defaults: new { controller = "Some", action = "Index" }
    constraints: new { myParam= new MyCons() }
);
// other route
routes.MapRoute(
    name: "myOtherRoute",
    // your own route
    url: "myOtherUrl/{myParam}",
    defaults: new { controller = "Foo", action = "Index" }
    constraints: new { myParam= new MyCons() }
);


text:
Q: как получить данные асинхронной функции в python Начал изучать python, решил для практики написать бота для бинанс.
Удалось создать класс с асинхронной функцией, и получать данные с биржи, проблема в том, как правильно получать эти данные и обрабатывать
Вот код класса, который получает данные с биржи
class StreamDataConnector:
    '''Object constructor'''
    '''@.param symbol: str
       @:param interval: str
    '''
    def __init__(self, symbol, interval):
        self.symbol = symbol
        self.interval = interval

        async def connerctor():

            url = f"wss://stream.binance.com:9443/stream?streams={self.symbol}@kline_{self.interval}"

            async with websockets.connect(url) as client:
                while True:
                    data = json.loads(await client.recv())['data']
                    print(data)

        loop = asyncio.get_event_loop()
        loop.run_until_complete(connerctor())

Данные идут в непрерывном потоке
Я думал как то записывать в файл данные эти и читать этот файл параллельно, но это по моему не то. Подскажите пожалуйста, как это правильно делать, спасибо

A: Если я правильно понял вопрос, то речь о том, чтоб разделить программу на два компонента:

*

*коннектор, который в цикле читает данные

*процессор, который получает данные из коннектора, и их обрабатывает

Один вариант, это создать асинхронный генератор:
import asyncio

class StreamDataConnector:
    async def get_data(self):
        i = 0
        while True:
            i += 1                     # это имитация получения
            await asyncio.sleep(1)     # данных
            yield i

class Processor:
    async def process(self, connector):
        async for data in connector.get_data():
            # тут обрабатываем, в этом примере просто печатаем
            print(data)

async def main():
    connector = StreamDataConnector()
    processor = Processor()

    await asyncio.create_task(processor.process(connector))

asyncio.run(main())

Тут цикл, в котором i увеличивается на 1 и делается sleep имитирует получение новых данных. У вас в get_data должно быть то, что сейчас в connerctor т.е. открытие сокета и чтение, только вместо print делайте yield, как в примере.


text:
Q: Discord JS: How would I make a open/close command? I want to make a command like ";opensales" will make a command work and if I say ";closesales" it'll disable the command.
I've tried changing a const but that only returns a TypeError: Assignment to constant variable.
I've tried things such as:
opensales = true

but this didn't work.
I expected it so if I set it to true, the command would work.
I've tried changing a const but that only returns a TypeError: Assignment to constant variable.
I've tried things such as:
opensales = true

but this didn't work.
EDIT: I figured out how to do based on the comments, so in case any of you want to know how, here you go:
Add let sales = at the top of your code. Then add this to your opensales command (for your disable command, just change true to false):
sales = true // Enables sales.


text:
Q: How to group / sort records by value of some inner attribute? I wonder if there's way (actually I tried to find myself but hasn't been successful at all) how to re-sort XML report of records according to some group chracteristics. Let's say I have log file consisting of records in form of
<?xml version="1.0"?>
<log>
  <record id="12345">
    <author>me</author>
    <ts>2014-05-02T13:03:50.528995Z</ts>
    <data>arbitrary data</data>
  </record>
  <record id="23456">
    <author>someone else</author>
    <ts>2014-05-05T08:24:32.123495Z</ts>
    <data>another arbitrary data</data>
  </record>
  …
</log>

What I want is to group records by author in a report: author's name and below ordered list of particular records. I don't know in advance who authors are, so I need to create list of their names dynamically.
Is XSLT capable of solving of this?

A: OK, so after carefully reading Jeni Tennison's tutorial I've figured it out.
<xsl:stylesheet version="1.0">

  <xsl:key name="key-authors" match="record" use="author" />

  <xsl:template match="log">

    <xsl:for-each select="record[generate-id() = generate-id(key('kAuthors',author)[1])]">
      <xsl:sort select="./author" />
      <xsl:value-of select="./author" />

      <xsl:for-each select="key('kAuthors',./author)">
        <xsl:apply-templates select="."/>
      </xsl:for-each>

    </xsl:for-each>

  </xsl:template>

  <xsl:template match="record">
    <!-- do whatever with the record values: @id, author, ts, data -->
  </xsl:template>

</xsl:stylesheet>

Thanks, michael.hor257k.


text:
Q: Event loop - Trigger on socket connection I'm trying to learn more about event loops and to fully understand it so i have tried to make something basic. I'm on Mac so i'm using kqueue.
The idea is to trigger the event loop only on new socket connections. The event loop get triggered on socket connection, but it wont stop on the next cycle. It keep printing after the first connections:
NEW CLIENT
NEW CLIENT
NEW CLIENT
NEW CLIENT
NEW CLIENT

etc...
It supossed to only print " NEW CLIENT " on new socket connection.
Here is the full source code:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <errno.h>

struct kevent e;
static struct sockaddr_in server;
static int server_fd, queue;

static void event_server_listen (int port) {
    int err, flags;

    queue = kqueue();

    server_fd = socket(AF_INET, SOCK_STREAM, 0);

    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    int opt_val = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt_val, sizeof(opt_val));

    err = bind(server_fd, (struct sockaddr *) &server, sizeof(server));

    flags = fcntl(server_fd, F_GETFL, 0);

    err = fcntl(server_fd, F_SETFL, flags | O_NONBLOCK);

    err = listen(server_fd, SOMAXCONN);

}

static void event_change (int ident, int filter, int flags, void *udata) {

    e.ident = ident;
    e.filter = filter;
    e.flags = flags;
    e.fflags = 0;
    e.data = 0;
    e.udata = udata;
}

static void event_loop () {

    while (1) {

        int nev = kevent(queue, &e, 1, &e, 1, NULL);

        if (nev == -1) { exit(0); }

        printf("NEW CLIENT\n");

    }
}

int main (int argc, char *argv[]) {

    int port = 8899;

    event_server_listen(port);
    event_change(server_fd, EVFILT_READ, EV_ADD | EV_ENABLE, NULL);
    event_loop();

    return 0;
}

Can someone please explain why that is happening and show me how to fix it please?


text:
Q: Pseudocolumn in Spark JDBC I am using a query to fetch data from MYSQL as follows:
var df = spark.read.format("jdbc")
         .option("url", "jdbc:mysql://10.0.0.192:3306/retail_db")
         .option("driver" ,"com.mysql.jdbc.Driver")
         .option("user", "retail_dba")
         .option("password", "cloudera")
         .option("dbtable", "orders")
         .option("partitionColumn", "order_id")
         .option("lowerBound", "1")
         .option("upperBound", "68883")
         .option("numPartitions", "4")
         .load()

Question is, can I use a pseudo column (like ROWNUM in Oracle or RRN(employeeno) in DB2) with option where I specify the partitionColumn ?
If not, can we specify a partition column which is not a primary key ?

A:
can I use a pseudo column (like ROWNUM in Oracle or RRN(employeeno) in DB2)

TL;DR Probably no.
While Spark doesn't consider constraints like PRIMARY KEY or UNIQUE there is very important requirement for partitionColumn, which is not explicitly stated in the documentation - it has to be deterministic.
Each executor fetches it's own piece of data using separate transaction. If numeric column is not deterministic (stable, preserved between transactions), the state of data seen by Spark might be inconsistent and records might be duplicated or skipped.
Because ROWNUM implementations are usually volatile (depend on non stable ordering and can be affected by features like indexing) there not safe choice for partitionColumn. For the same reason you cannot use random numbers.
Also, some vendors might further limit allowed operations on pseudocolumns, making them unsuitable for usage as a partitioning column. For example Oracle ROWNUM

Conditions testing for ROWNUM values greater than a positive integer are always false.

might fail silently leading to incorrect results.

can we specify a partition column which is not a primary key

Yes, as long it satisfies criteria described above.

A: As per Spark's official documentation the partitionColumn can be any numeric column (not necessarily primary key column).

partitionColumn must be a numeric column from the table in question.

Reference: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html


text:
Q: If the self-induced EMF in an inductor is 180° out of phase with source voltage, shouldn't they cancel out and net voltage should become zero?
I know that inductor opposes the change in magnetic flux linked with it. In case of an ac sinusoidal voltage applied across a pure inductor, the emf induced across the inductor is equal and opposite in direction to the source voltage. So the net voltage should be 0. However when I connected a C.R.O across the inductor terminals, I observed only the source waveform, how is that possible, shouldn't it be zero. How can I see both induced emf and source waveform on the C.R.O

A: If it wasn't for the fact that the inductor produced a back emf, it might as well be a lump of copper across your signal generator output and then it would be a dead short and you would see no waveform. So, the inductor is doing two things; taking a current from the signal generator and simultaneously producing a back emf.
Most engineers biggest difficulty is understanding how any current can flow when the back emf exactly equals the applied voltage. Regard it as a separate path inside the inductor if you want.

How can I see both induced emf and source waveform

If you put another winding around your inductor with the same number of turns onto the coil's core in the same position as the original coil then you would see the back emf across that new winding.

A:
the emf induced across the inductor is equal and opposite in direction
  to the source voltage. So the net voltage should be 0

That is an overly simplistic analysis. The induced voltage is only 'equal and opposite' the source voltage as it would be in a resistor or any other component - it simply has to be because the voltage across the inductor must equal the voltage applied to it.
The important formula is \$V = -L\frac{di}{dt}\$, which means the current will change at whatever rate is required for the induced voltage to match the applied voltage.
It gets more interesting if you allow the supply voltage and inductor voltage to be different. A real inductor has internal resistance distributed along the length of its winding, but we can split this into an ideal resistor and inductor (inside the dotted lines of the circuit below) to separate the induced voltage from the supply voltage...

simulate this circuit – Schematic created using CircuitLab
...and now the waveforms look like this:-

We can now see that the voltage induced in the inductor is proportional to the rate of current change,  eg. at the beginning of the cycle where current is rising, the inductor produces positive voltage even though the supply voltage is 0 (the difference is dropped across the resistor).


text:
Q: Coefficients of a polynomial with roots represented as squares of cosines Consider a polynomial with roots $\cos^2 \left(\frac{j \pi}{2n + 1}\right), 1 \leq j \leq n$. The coefficients of this polynomial are sums of these numbers taken one at a time, two at a time, three at a time, and so on, up to sign. That is
$$
\sum\limits_{j = 1}^n \cos^2 \left( \frac{j\pi}{2n+1} \right), \sum\limits_{j<k; \;j,k = 1}^n \cos^2 \left(\frac{j\pi}{2n+1} \right)\cos^2 \left( \frac{k\pi}{2n+1} \right),
$$
and so on. I can prove that $\sum\limits_{j = 1}^n \cos^2 \left( \frac{j\pi}{2n+1} \right) = \frac{n}{2} - \frac{1}{4}$. Upon examination, other sums of this form also appear to be rational numbers. I would like to know if there is a expression for these sums as a function of $n$.
If so, what is it or how can I find and prove it?


text:
Q: Guardar dados Mysql php numa única tabela Estou com uma pequena dúvida em guardar um formulário no mysql que é.
Tenho um formulário que está dividido em 2 e quero que seja guardado na mesma tabela.
Quando guardo só faço guardar a segunda parte do mysql ele apaga-me a primeira.
Exemplo Formulario1: Nome, função
Inserir na BD:
$sqlinsert = "Insert into tb_trabalhador (Nome, funcao) Values ('".$Nome."','".$Funcao."')";

mysql_query($sqlinsert) or die(mysql_error());
if ($sqlinsert)

Formulario2: Cartaocidadao, data de nascimento
Inserir na BD:
$sqlinsert = "Insert into tb_trabalhador (Cartao, Data) Values ('".$Cartao."','".$Data."')";

 mysql_query($sqlinsert) or die(mysql_error());
 if ($sqlinsert)

A: O problema é que me parece que você quer juntar os dados em um registro só, mas está criando dois.
Depois de usar cada um dos seus códigos, você vai ter uma tabela assim:
Cartao | Data       | Nome   | Funçao
-------+------------+--------+--------
2136   | 31/05/2014 |        |
-------+------------+--------+--------
       |            | Holmer | Estivador

Se quiser acrescentar dados numa tabela, vai precisar de algo assim:
$cartao = "2136" // esse é só um exemplo, pode ser ID, aí vai depender do seu caso.
$sqlupdate = "UPDATE tb_trabalhador". // ATUALIZE tb_trabalhador
    "SET Nome=$nome, Funcao=$Funcao". // mudando o nome pra $Nome e função pra $Funcao
    "WHERE Cartao=$Cartao";           // na linha em que o cartão for $Cartao

Nota: este é apenas um exemplo. Como já deve ter sido avisado em algumas das suas perguntas anteriores, você deveria estar usando funções do mysqli_ para poder usar bindParameter, em vez de criar a string com parâmetros, mas este ja é outro problema.


text:
Q: Removing AVPlayerItem observers If I use KVO to observe my player items like this:
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:MyClassKVOContext];
    [playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:MyClassKVOContext];
    [playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:MyClassKVOContext];
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:MyClassKVOContext];

Two questions:
1) Do I need to remove my observers once the item finishes playing? (i.e. in AVPlayerItemDidPlayToEndTimeNotification)
2) If I call [_avQueuePlayer removeAllItems] does it also remove each item's observers?

A: make your player object(AVPlayerItem *playerItem) Globally and set its property and synthesize it.
1) Do I need to remove my observers once the item finishes playing? (i.e. in AVPlayerItemDidPlayToEndTimeNotification)

Yes, your need to remove all observer when you are about to leave that view controller where that player is playing. Not after finishes playing.

2) If I call [_avQueuePlayer removeAllItems] does it also remove each item's observers?

Yes, it remove all observer that are set for that global variable.


text:
Q: New element in the context menu of a contenteditable  How to add a new element in the context menu of a contenteditable
?
I'd like to add an option "Show HTML" that would display the raw HTML that is inside the div.

document.getElementById("a").oncontextmenu = function() {
  alert("How to add a new element in the Context menu?");
}

Hello you, right-click here and see the new option "Show HTML"

Note: Unlike this question or this one I don't want to override the normal context menu and build a new one, but add a new element to the existing context menu:

A: You can not use this in all browsers. Method  of defining a context menu item, now deprecated and removed from the HTML specification. https://www.w3.org/TR/2016/REC-html51-20161101/interactive-elements.html#context-menus,
https://caniuse.com/#search=contextmenu


text:
Q: HL7 - Parsing Specimen Source (OBR-15) using nHapi in c# I was wondering if any wonderful person with experience of using nHAPI in C# would be able to help a newbie out with the OBR-15 field (Specimen Source) of an HL7 message? I've dug around and I can't find any documentation online to help me out, so I'd be grateful for any suggestions.
My problem is, I can't find the correct method for filling the OBR-15 field using nHAPI. I'm hoping to send an OBR segment that looks like this (I've removed data from all other fields except OBR15, so my actually message isn't as bare as this):

OBR|1||||||||||||||T034^Blood||||||||||||||||||||

I've tried every way possible to form this field with no success. I'm always getting an ampersand that appears in the front everything I'm sending, which means that the field is unreadable in downstream applications:

OBR|1||||||||||||||&T034^^^^^^&Blood||||||||||||||||||||

My OBR-15 code snippet (I've just kept the relevant stuff in here, as otherwise this section would be massive):
using System;
using System.Collections.Generic;
using System.Web.Services;
using NHapi.Model.V24.Message;
using NHapi.Model.V24.Segment;
using NHapi.Model.V24.Group;
using System.Data;
using System.Text;
using NHapi.Base.Parser;
using NHapi.Model.V24.Datatype;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Data.SqlClient;

namespace HL7WebService
{

    public class HL7Reporting : System.Web.Services.WebService
    {
        private ORU_R01 Create_ORU_R01(Dictionary <string,string> reportData, int reportNumber)
        {
            ORU_R01 oruR01 = new ORU_R01();

            // lots of stuff removed for clarity

            ORU_R01_ORDER_OBSERVATION oruR01OrderObs = oruR01.GetPATIENT_RESULT().GetORDER_OBSERVATION(1);
            OBR obr = oruR01OrderObs.OBR;

            // OBR-15 Specimen Source
            obr.SpecimenSource.SpecimenSourceNameOrCode.Text.Value = "T034";
            obr.SpecimenSource.SpecimenRole.Text.Value = "Blood";

            // lots of other stuff removed for clarity

            return oruR01;
        }
    }
}

I'm using nHapi (v2.5.0.6) and visual studio 2015. If I've missed anything out or you require any further information, just let me know and I'll provide it. Thanks!

A: I solved it by declaring OBR-15 the following way:
obr.SpecimenSource.SpecimenSourceNameOrCode.Identifier.Value = "T034";
obr.SpecimenSource.Additives.Value = "Blood";