text:
Q: Library/tool for drawing ternary/triangle plots I need to draw ternary/triangle plots representing mole fractions (x, y, z) of various substances/mixtures (x + y + z = 1). Each plot represents iso-valued substances, e.g. substances which have the same melting point. The plots need to be drawn on the same triangle with different colors/symbols and it would be nice if I could also connect the dots.
I have looked at matplotlib, R and gnuplot, but they don't seem to be able to draw this kind of plot. The 3rd party ade4 package for R seems to be able to draw it, but I'm not sure if I can draw multiple plots on the same triangle.
I need something that runs under Linux or Windows. I'm open to any suggestions, including libraries for other languages, e.g. Perl, PHP, Ruby, C# and Java.

A: R has an external package called VCD which should do what you want.
The documentation is very good (122 page manual distributed w/ the package); there's also a book by the same name, Visual Display of Quantitative Information, by the package's author (Prof. Michael Friendly).
To create ternary plots using vcd, just call ternaryplot() and pass in an m x 3 matrix, i.e., a matrix with three columns.
The method signature is very simple; only a single parameter (the m x 3 data matrix) is required; and all of the keyword parameters relate to the plot's aesthetics, except for scale, which when set to 1, normalizes the data column-wise.
To plot data points on the ternary plot, the coordinates for a given point are calculated as the gravity center of mass points in which each feature value comprising the data matrix is a separate weight, hence the coordinates of a point V(a, b, c) are
V(b, c/2, c * (3^.5)/2

To generate the diagram below, i just created some fake data to represent four different chemical mixtures, each comprised of varying fractions of three substances (x, y, z). I scaled the input (so x + y + z = 1) but the function will do it for you if you pass in a value for its 'scale' parameter (in fact, the default is 1, which i believe is what your question requires). I used different colors & symbols to represent the four data points, but you can also just use a single color/symbol and label each point (via the 'id' argument).

A: A package I have authored in R has just been accepted for CRAN, webpage is www.ggtern.com:
It is based off ggplot2, which I have used as a platform. The driving force for me, was a desire to have consistency in my work, and, since I use ggplot2 heavily, development of the package was a logical progression.
For those of you who use ggplot2, use of ggtern should be a breeze, and, here is a couple of demonstrations of what can be achieved.

Produced with the following code:
# Load data
data(Feldspar)

# Sort it by decreasing pressure
# (so small grobs sit on top of large grobs
Feldspar <- Feldspar[with(Feldspar, order(-P.Gpa)), ]

# Build and Render the Plot
ggtern(data = Feldspar, aes(x = An, y = Ab, z = Or)) +
#the layer
geom_point(aes(fill = T.C,
               size = P.Gpa,
               shape = Feldspar)) +
#scales
scale_shape_manual(values = c(21, 24)) +
scale_size_continuous(range = c(2.5, 7.5)) +
scale_fill_gradient(low = "green", high = "red") +

#theme tweaks
theme_tern_bw()  +
theme(legend.position      = c(0, 1),
      legend.justification = c(0, 1),
      legend.box.just      = "left") +

#tweak guides
guides(shape= guide_legend(order   =1,
                           override.aes=list(size=5)),
       size = guide_legend(order   =2),
       fill = guide_colourbar(order=3)) +

#labels and title
labs(size = "Pressure/GPa",
     fill = "Temperature/C") +
ggtitle("Feldspar - Elkins and Grove 1990")

Contour plots have also been patched for the ternary environment, and, an inclusion of a new geometry for representing confidence intervals via the Mahalanobis Distance.

Produced with the following code:
ggtern(data=Feldspar,aes(An,Ab,Or)) +
  geom_confidence(aes(group=Feldspar,
                      fill=..level..,
                      alpha=1-..level..),
                      n=2000,
                  breaks=c(0.01,0.02,0.03,0.04,
                           seq(0.05,0.95,by=0.1),
                           0.99,0.995,0.9995),
                  color=NA,linetype=1) +
  geom_density2d(aes(color=..level..)) +
  geom_point(fill="white",aes(shape=Feldspar),size=5) +
  theme_tern_bw() +
  theme_tern_nogrid() +
  theme(ternary.options=element_ternary(padding=0.2),
                        legend.position=c(0,1),
                        legend.justification=c(0,1),
                        legend.box.just="left") +
  labs(color="Density",fill="Confidence",
   title="Feldspar - Elkins and Grove 1990 + Confidence Levels + Density") +
  scale_color_gradient(low="gray",high="magenta") +
  scale_fill_gradient2(low="red",mid="orange",high="green",
                       midpoint=0.8) +
  scale_shape_manual(values=c(21,24)) +
  guides(shape= guide_legend(order   =1,
                             override.aes=list(size=5)),
         size = guide_legend(order   =2),
         fill = guide_colourbar(order=3),
         color= guide_colourbar(order=4),
         alpha= "none")

A: Veusz supports ternary plots. Here is an example from the documentation:

A: Chloë Lewis developed a triangle-plot general class, meant to support the soil texture triangle
with Python and Matplotlib. It's available here http://nature.berkeley.edu/~chlewis/Sourcecode.html https://github.com/chlewissoil/TernaryPlotPy
Chloe editing to add: Moved it to a more reliable host! Also, it's a public repo, so if you want to request library-ization, you could add an issue. Hope it's useful to someone.

A: Created a very basic script for generating ternary (or more) plots.  No gridlines or ticklines, but those wouldn't be too hard to add using the vectors in the "basis" array.

from pylab import *

def ternaryPlot(
            data,

            # Scale data for ternary plot (i.e. a + b + c = 1)
            scaling=True,

            # Direction of first vertex.
            start_angle=90,

            # Orient labels perpendicular to vertices.
            rotate_labels=True,

            # Labels for vertices.
            labels=('one','two','three'),

            # Can accomodate more than 3 dimensions if desired.
            sides=3,

            # Offset for label from vertex (percent of distance from origin).
            label_offset=0.10,

            # Any matplotlib keyword args for plots.
            edge_args={'color':'black','linewidth':2},

            # Any matplotlib keyword args for figures.
            fig_args = {'figsize':(8,8),'facecolor':'white','edgecolor':'white'},
        ):
    '''
    This will create a basic "ternary" plot (or quaternary, etc.)
    '''
    basis = array(
                    [
                        [
                            cos(2*_*pi/sides + start_angle*pi/180),
                            sin(2*_*pi/sides + start_angle*pi/180)
                        ]
                        for _ in range(sides)
                    ]
                )

    # If data is Nxsides, newdata is Nx2.
    if scaling:
        # Scales data for you.
        newdata = dot((data.T / data.sum(-1)).T,basis)
    else:
        # Assumes data already sums to 1.
        newdata = dot(data,basis)

    fig = figure(**fig_args)
    ax = fig.add_subplot(111)

    for i,l in enumerate(labels):
        if i >= sides:
            break
        x = basis[i,0]
        y = basis[i,1]
        if rotate_labels:
            angle = 180*arctan(y/x)/pi + 90
            if angle > 90 and angle <= 270:
                angle = mod(angle + 180,360)
        else:
            angle = 0
        ax.text(
                x*(1 + label_offset),
                y*(1 + label_offset),
                l,
                horizontalalignment='center',
                verticalalignment='center',
                rotation=angle
            )

    # Clear normal matplotlib axes graphics.
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_frame_on(False)

    # Plot border
    ax.plot(
        [basis[_,0] for _ in range(sides) + [0,]],
        [basis[_,1] for _ in range(sides) + [0,]],
        **edge_args
    )

    return newdata,ax

if __name__ == '__main__':
    k = 0.5
    s = 1000

    data = vstack((
        array([k,0,0]) + rand(s,3),
        array([0,k,0]) + rand(s,3),
        array([0,0,k]) + rand(s,3)
    ))
    color = array([[1,0,0]]*s + [[0,1,0]]*s + [[0,0,1]]*s)

    newdata,ax = ternaryPlot(data)

    ax.scatter(
        newdata[:,0],
        newdata[:,1],
        s=2,
        alpha=0.5,
        color=color
        )
    show()

A: There seems to be an implementation at work here in gnuplot:

(source: ugm.ac.id)

A: I just discovered a tool which uses Python/Matplotlib to generate ternary plots called wxTernary. It's available via http://wxternary.sourceforge.net/ -- I was able to successfully generate a ternary plot on the first try.

A: There is a R package named soiltexture. It's aimed at soil texture triangle plot, but can be customized for some aspects.

A: Find a vector drawing library and draw it from scratch if you can't find an easier way to do it.


text:
Q: What could cause 45FPS limit for SSD1306? I'm porting U8G2 display library to ESP32 microcontroller (no suitable tag) with ESP-IDF (its official platform) as the platform, I2C protocol for now, using SSD1306 display for testing. After all improvements and optimisations FPS got stuck at 45. I tried:

*

*Changing bus clock (no difference on 800KHz and 1MHz)

*Disabling waiting for ACK (150+ FPS test do so, but no difference for me)

*Changing ESP32 processor frequency (160MHz and 240MHz give the same result)

*Commenting out all delay functions (they probably aren't called at all)

What is likely a critical link in chain here?

A: The SSD1306 display driver does not have a direct connection to every pixel on the screen. Instead it connects to each row and column of the display matrix and scans across each column sequentially to generate the displayed image. Persistence effects allow your eye to perceive this as a static image.
You can update the graphics ram at any rate you want, but data will only be sent to the pixels on the display when the scan line reaches the ram location. The data used will be whatever is in the memory at that exact point in time.
On your screen it sounds like the SSD1306 is scanning at 45Hz. There are a set of registers you can program to change the display clock (and hence overall refresh rate) but be aware that increasing this will increase power consumption and the panel itself may malfunction if the rate is set too high. The relevant information is on page 22 of the datasheet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails - save controller instance variable data across HTTP request In my project, a user is uploading a text file, that needs to be read.
File, can be of any size, the file I am using is 1 MB and has ~1500 lines. The file can be bigger as well. Hence instead of putting all in db, i thought of processing the file and retaining the data in instance variable.
But instance variables are not available across HTTP request. Hence what are the options available to me to retain the instance variable values across HTTP request.The other reason for not choosing DB was, I dont need the data to be persisted. As long as user is logged in, data needs to be present for that time duration only. Once user is logged out, I can discard the data.
Please let me know if you need further information.

A: As @xyious advises, I would say avoid storing that much data in session, it is just not a good practice. You could, however, do the following:

*

*Setup a system-wide configuration setting that holds a path where you store temporary files, in this case, the files uploaded by the user

*Generate a random (maybe with SecureRandom.hex) filename when the user uploads the file and store this file in the path mentioned on point #1

*Store this random filename in the user session, that way, even if you change between requests you can still access the filename

*On each request, whenever you need to process the data, pull the filename from the user's session and join the path of the setting of #1, read the file from the filesystem and do the processing as necessary

*Add a callback on your login/sessions controller so that when a user logs out you go and find the filename and delete it before logging out, that way you don't keep unused files around

A: I would advise against it, but you could store the data in a session variable, or in a cookie.
Why would you need that much data to be stored while the user is logged in ? Is it possible to just save important bits ?

A: Using instance variables to store content is not a right approach since you don't have a limit on the size of file uploaded and you end up passing the data everytime.
Firstly, decide something on the size limit since you expect text file from users and then upload the file temporarily with a reference path in DB. This file can be cleaned up when required and will make accessing the content simple. To further improve this, enable caching mechanism and setup a caching server for the uploaded files.
If you are not fine with this then other option i can think of is using session variables which is already suggested. So this data will stay per session which fits your requirement. you can just session[:file_Data] = "put parsed content here"


text:
Q: Proving one interval is a subset of others I am trying to prove that $\left(a,b\right)$ is an open set in $\mathbb{R}$ under the usual metric $d\left(x,y\right)=|x-y|$
given any $x\in \left(a,b\right)$ I am supposed to produce an open ball which is contained in $\left(a,b\right)$.
I think $\epsilon=min\{x-a,b-x\}$ will work for us as the radius of the ball. That is $\left(x-\epsilon,x+\epsilon\right) \subset \left(a,b\right)$

I am unable to prove the following mathematically.
   $\left(x-\epsilon,x+\epsilon\right) \subset \left(a,b\right)$

Help me with this.

A:
Maybe this small picture will help a bit.


text:
Q: What are the major pros for docker hub? As i know, It is just a hub which contains image only, So i can't push on docker hub with docker-compose. However, I can push our repository which contains docker-compose things to github, so that someone who want to execute my source can pull it from github.
Then, they can run command like docker-compose up.
I think this is just a good with github or bigbucket.
Is there something more feature i can use or i have to consider with docker hub?

A: The premise is simple: Docker Hub gives us a space to host and manage our Docker images. This way we can delegate all the hard and tedious work to it.
The main purpose of doing this is to separate the container management from the deployment service. Once Docker Hub informs us that our new image has been built correctly, we're ready to deliver it to whichever service we prefer. This has a huge benefit over traditional methods because separating the image building process from the actual instance means that our application environment will keep running until we do the actual deployment.
But that's not all! Docker Hub also comes with many handy features to make our work easier.
In my opinion, the true star features are these two:
Autobuild: Docker Hub automatically pulls our code from GitHub or BitBucket, locates the Dockerfile in it and starts building, tagging and pushing the image into the container.
Autotest: Docker Hub starts running our application tests after building the image and allows us to automatically stop the push process if anything fails.
You can get more information about Docker Hub here.

A: Docker hub is a cloud based repository which helps users to create, share and distribute container images.A user can access the high-quality container images provided by Docker as well as use a space to create their own private repositories, automated build functions, webhooks and work groups.
I think It's a great platform to access the public, open source image repositories.
One Simple Use Case: It would also be beneficial in case if you create a cluster using multiple machines and all machines are pointing to the same version of images using docker hub. It would act as a central repositories(source of truth) for your system.
Please follow official docs to get more insights.


text:
Q: Salt-key command in runner I'm writing a custom Salt Stack runner to wrap accepting and rejecting minions. How do I call salt-key from my python runner that's equivalent to this from command line
salt-key -a {minion_name}

A: I can't provide you a definite answer, but here are my two cents:
The source code of the salt-key script is this one. Following the call chain, I reached this module which contains several classes to do key processing.
The module's documentation reads:

The Salt Key backend API and interface used by the CLI. The Key class can be
  used to manage salt keys directly without interfacing with the CLI.

This is the mentioned class.
Based on this code, I presume it's used like:
import salt.client
import salt.key

client = salt.client.LocalClient()
key_manager = salt.key.Key(client.opts)
key_manager.accept('web*')

A: I know it has been a while since this question is answered, I would like to add my two cents on this subject.
In order to do key interactions programmatically, we use Wheel in salt. Usage is rather simple and clear:
from salt import config
from salt import wheel
masterOpts = config.master_config('/etc/salt/master')
wheelClient = wheel.WheelClient(masterOpts)
wheelClient.cmd('key.accept', ['minionId1'])

Bunch of other operations could be found in SaltStack documentatation here


text:
Q: Php array iteration fail i have an app where i save weekdays and business hours on MySql as follow:
0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22

The php array fetch this from Mysql as following formats
Array ( [open_hours] => 0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22 )

0 10 22 simply means Monday 10am 22pm
My current code seems not works well, below are the code i use to format the date and time
$openHrs = $businessMapper->getBusinessHours($business_id);
// return Array ( [open_hours] => 0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22 )
$openHrs = explode(",", $openHrs['open_hours']);
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
        foreach($openHrs as &$temp) {
             //$temp = $weekdays[$temp[0]]
            $temp = explode(" ", $temp);
             //$temp = explode(" ", $temp);
            $temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
            $temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';
            $temp = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
        }

But the issues is, i only get one result which is Sat 10am 10pm. How can i fix my code? Thanks!!

A: Issue : every time when foreach iterates it over writes the previous value ie $temp will contains only the last value.
Solution : Added a variable $res as array and assigned each value to it.
Try this :
$openHrs = $businessMapper->getBusinessHours($business_id);
// return Array ( [open_hours] => 0 10 22,1 10 22,2 10 22,4 10 22,5 10 22,6 10 22 )
$openHrs = explode(",", $openHrs['open_hours']);
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
$res      = array();
        foreach($openHrs as &$temp) {
             //$temp = $weekdays[$temp[0]]
            $temp = explode(" ", $temp);
             //$temp = explode(" ", $temp);
            $temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
            $temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';
            $res[]   = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
        }

echo "<pre>";
print_r($res);

A: foreach($openHrs as &$temp)
you cannot use $temp  variable in your loop!

A: $openHrs = $businessMapper->getBusinessHours($business_id);
$openHrs = explode(",", $openHrs['open_hours']);
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

$resultArray = array();

foreach($openHrs as $temp) {
   $tempRecord = explode(" ", $temp);

   if (count($tempRecord) == 3) {
       $timeBegin = $tempRecord[1] > 12 ? $tempRecord[1] - 12. 'pm' : $tempRecord[1]. 'am';
       $timeEnd = $tempRecord [2] > 12 ? $tempRecord[2] - 12. 'pm' : $tempRecord[2]. 'am';
       $resultArray[] = "{$weekdays[$temp[0]]} {$timeBegin} {$timeEnd}";
   }
}


text:
Q: Unable to Refer to Listbox on Sheet I haven't used list boxes before and don't need to use objects too often in my work, but for some reason, my code runs OK for this:
ActiveSheet.ListBox1.AddItem MyName(i)

but if I try to get the listbox using a worksheet instead of the ActiveSheet, it errors
wkTest.ListBox1.AddItem MyName(i)

Where test is the worksheet on which ListBox1 lives. What is the best way to reference a listbox if you want to refer it to it based on the sheet it's? Or is this not the right way to go about doing this.

A: Shortcomings of the List Box ActiveX Control?
Setup

*

*Open a new worksheet and in the Developers tab click on Insert
and under ActiveX Controls click on List Box (ActiveX Control).

*"Draw" the control onto the worksheet. Copy the following code into a
standard module (e.g. Module1).

Conclusions

*

*The first part of the code demonstrates that although you can access
the ListBox by its name via the Shapes and OLEObjects collections,
both do not provide a way to add items to the ListBox.

*The only way to do this seems to be to use the CodeName, which is
demonstrated through various solutions in the second part of the
code.

This was inspired by the ideas from Rory and Michael Smith in the comments.
The Code
Option Explicit

Sub ListBoxTest()

    ' Worksheet
    Dim wkTest As Worksheet: Set wkTest = ThisWorkbook.Worksheets("Sheet1")

    ' Shape - no use
    Dim shTest As Shape: Set shTest = wkTest.Shapes("ListBox1")
    Debug.Print "Shape", shTest.Name, shTest.Left
    'shTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...

    ' OLEObject - no use
    Dim ooTest As OLEObject: Set ooTest = wkTest.OLEObjects("ListBox1")
    Debug.Print "OLEObject", ooTest.Name, ooTest.Left
    'ooTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...

    Dim obj As Object

    'Set obj = wkTest.ListBox1 ' Compile error: Method or data member not found.

    ' Object 1 Solution
    Set obj = Worksheets("Sheet1").ListBox1
    Debug.Print "Object 1", obj.Name, obj.Left
    obj.AddItem "One"

    ' Object 2 Solution
    Set obj = Sheet1.ListBox1
    Debug.Print "Object 2", obj.Name, obj.Left
    obj.AddItem "Two"

    ' Object 3 Solution
    wkTest.Activate
    Set obj = ActiveSheet.ListBox1
    Debug.Print "Object 3", obj.Name, obj.Left
    obj.AddItem "Three"

    ' Favorite
    With Sheet1.ListBox1
        Debug.Print "Favorite", .Name, .Left
        .AddItem "Four"
    End With

End Sub

Sub ListBoxClear()
    Dim obj As Object: Set obj = Worksheets("Sheet1").ListBox1
    obj.Clear
End Sub


text:
Q: ¿Cómo mostrar datos en la vista en ASP.NET MVC? Realizo una llamada a un WS y recibo unos datos, el problema es que no se cómo mostrar los datos que recibo
Mi controller
  [HttpPost]
    public ActionResult Consulta(Models.SolicitudesViewModels.Consulta consultar)
    {
        var token = Session["token"] as string;

        SRSolicitudes.SolicitudesSoapClient wsSolicitudes = new SRSolicitudes.SolicitudesSoapClient();
        SRSolicitudes.ConsultaSolicitudes outConsultaSolicitudes = new SRSolicitudes.ConsultaSolicitudes();
        outConsultaSolicitudes = wsSolicitudes.ConsultarSolicitud(token, consultar.Estado, consultar.Cedula, consultar.Nombres, consultar.Apellidos, consultar.Computacion, 1, 50);

        ViewBag.resultado = outConsultaSolicitudes.Cantidad;
        ViewBag.Ocultar = false;
        ViewBag.Mostrar = false;

        return View();
    }

Mi vista:
    @model Demo.SolicitudesViewModels.Consulta

Consultar Solicitudes

    @if (ViewBag.Ocultar == false)
    {

Se encontraron @ViewBag.resultado resultados.

    }
    <form name="buscando" action="@Url.Action("Consulta", "Solicitudes")" method="POST">

                    <input class="btn btn-primary" type="submit" value="Buscar" />
                     Salir

                    Cédula

                    @Html.TextBoxFor(m => m.Cedula, null, new { @class = " form-control" })

                    Apellidos

                    @Html.TextBoxFor(m => m.Apellidos, null, new { @class = " mayusculas form-control" })

                    Nombres

                    @Html.TextBoxFor(m => m.Nombres, null, new { @class = " mayusculas form-control" })

                    Nro. de Computación

                    @Html.TextBoxFor(m => m.Computacion, null, new { @class = "form-control" })

                    Estado

                    @Html.DropDownListFor(m => m.Estado, new SelectList(new[] { null, "Aprobado", "Rechazado" }), new { @class = "form-control" })

                @if (ViewBag.Mostrar == false)
                {

                        Categoria

                        Acciones

                }

            @if (ViewBag.Mostrar == false)
            {

                    Cedula
                    Apellido
                    Nombres
                    NroComputacion
                    Estado
                    Categoria

                        <button class="btn btn-xs btn-primary" role="button"> Ver</button>

            }

    </form>

aqui es donde quiero mostrar mis datos como una tabla

                    Cedula
                    Apellido
                    Nombres
                    NroComputacion
                    Estado
                    Categoria

                        <button class="btn btn-xs btn-primary" role="button"> Ver</button>

la llamada se devuelve cantidad y solicitudes que es una array y contiene lo siguiente
    <ConsultaSolicitud>
        <IdSolicitud>int</IdSolicitud>
        <Estado>string</Estado>
        <NroComputacion>int</NroComputacion>
        <Cedula>string</Cedula>
        <Apellidos>string</Apellidos>
        <Nombres>string</Nombres>
        <Fecha>dateTime</Fecha>
        <Categoria>string</Categoria>
      </ConsultaSolicitud>

A: Primero que todo pienso que debes cambiar la calse model view Consulta y agregar un listado de Consultas Solicitud
public class Consulta
    {
        public string  Estado { get; set; }
        public string Cedula { get; set; }
        public string Nombres { get; set; }
        public string Apellidos { get; set; }
        public string Computacion { get; set; }
        public List<ConsultaSolicitud> ConsultaSolicitud { get; set; }
    }

entonces en el controlador asignas el resultado del WS a la lista de  ConsultaSolicitud
consultar.ConsultaSolicitud = new List<ConsultaSolicitud>();
consultar.ConsultaSolicitud = outConsultaSolicitudes;

y retornar la vista con el objeto consultar.
return View(consultar)

en la vista puedes iterar sobre los elementos de la lista ConsultaSolicitud y llenar la tabla
@foreach(var item in Model.ConsultaSolicitud ){

    @item.Cedula
    @item.Apellido
    //las otras columnas

        <button class="btn btn-xs btn-primary" role="button"> Ver</button>

}

Espero que te sirva. Saludos

A: No veo que estes enviando un modelo a la view, en el action Consulta deberias enviar los datos
return View(outConsultaSolicitudes);

de esta forma en la view defines
@model List<SRSolicitudes.ConsultaSolicitudes>

con esto tendrias lista para iterar y crear la tabla
@foreach(var item in Model){

        @item.Cedula
        @item.Apellido
        //las otras columnas

            <button class="btn btn-xs btn-primary" role="button"> Ver</button>

}


text:
Q: About the proof of Borel-Weil-Bott theorem: Two derived pushforward sheaves are isomorphic by descent theory I was reading the note on the proof of Borel-Weil-Bott theorem written by Jacob Lurie (See http://www.math.harvard.edu/~lurie/papers/bwb.pdf) and I was stuck at the point where he said that for a $\mathbb{P}^1$-bundle $\pi: E \longrightarrow S$ and any line bundle ${\cal L}$ on $E$ with fibre degree $n$, we have, by descent theory, the following isomorphism:
$$\pi_*{\cal L}\cong R^1\pi_*({\cal L}\otimes K^{\otimes n+1})~~(*)$$
where $K$ is according to him the relative canonical bundle.
It is clear to me that the sheaves on both sides are vector bundles over $S$ with fibres $H^0(\mathbb{P}^1,{\cal L}|_{\mathbb{P}^1})$ and $H^1(\mathbb{P}^1,{\cal L}|_{\mathbb{P}^1}\otimes K_{\mathbb{P}^1}^{\otimes n+1} )$ respectively which are (non-canonically) isomorphic by Serre duality. Notice this holds whenever we have two line bundles whose fibre degrees sum to $-2$ but I don't believe the isomorphism (*) holds for any such pair of line bundles.
My question is what is the assumption required in order to make (*) hold? What content of descent theory did he use? I am also confused why Serre duality takes this form instead of the usual one ${\cal L}^{\vee}\otimes K$. Can we get the similar conclusion based on this usual form, i.e.
$$\pi_*{\cal L}\cong R^1\pi_*({\cal L}^{\vee}\otimes K)?$$


text:
Q: how to make the live chart image to the right? http://phplist.xxmn.com/test.html

how to make the live chart image to the right?
<script src="http://chatserver.comm100.com/js/LiveChat.js?siteId=117659&planId=646&partnerId=-1" type="text/javascript"></script> i downloaded the js file(http://chatserver.comm100.com/js/LiveChat.js) and uploaded it to my site's directory. and declared those variables in the front of the code.
(
var siteId=117659;
var planId=646;
var partnerId=-1
)

but it can't work, why? how to correct it.

A: Since you've got not control over the script which frequently shifts the element to the left, add an own stylesheet, using !important.
<style>
#comm100_FloatImageButton {
    position: fixed;
    top: 10px;
    left: auto !important; /* This style will not be overridden by the script */
    right: 0 !important; /* This property will neither be overridden*/
}
</style>

Fiddle: http://jsfiddle.net/PzRmk/


text:
Q: Noncancelable Task that Restores Interruption Before Exit I was reading some java thread interruption and I don't understand some stuff. Hope someone will explain me. So, it's done the following code
public Integer getInteger(BlockingQueue<Integer> queue) {
    boolean interrupted = false;
    try {
        while (true) {
            try {
                return queue.take();
            } catch (InterruptedException e) {
                interrupted = true;
                // fall through and retry
            }
        }
    } finally {
        if (interrupted)
            Thread.currentThread().interrupt();
    }
}

The explanation is as follows :

Activities that do not support cancellation but still call
  interruptible blocking methods will have to call them in a loop,
  retrying when interruption is detected. In this case, they should save
  the interruption status locally and restore it just before returning,
  as shown in listing. rather than immediately upon catching
  InterruptedException. Setting the interrupted status too early could
  result in an infinite loop, because most interruptible blocking
  methods check the interrupted status on entry and throw
  InterruptedException immediately if it is set. (Interruptible methods
  usually poll for interruption before blocking or doing any significant
  work, so as to be as responsive to interruption as possible.)

I don't understand why we should save the interrupted status locally.
I would be glad to hear some explanation.

A: By the design the method could not ever throw the InterruptedException. So it means we always expect take a value from the queue. But somebody could want the thread to be interrupted, that's why we have to save-restore the interrupted state after we have finally took a value from the queue.
So, the thread get finished only after taking a value from the queue.
UPDATE: Look into the take() method implementation. It has the following as the first statements:
public final void acquireInterruptibly(int arg) throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
...
}

A: The loop will finish because of the statement
return queue.take();

This is not a tight loop even though it looks like one. It just blocks for one element and and returns as soon as it is available and retries if an interruption occurs.


text:
Q: Is DataGridDragDropTarget gone from the latest version of Silverlight toolkit? I'm using Silverlight 4 and Silverlight Toolkit April 10 release (dll is referenced from this folder: %Program Files%\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Bin). However, after registering the namespaces, adding toolkit:DataGridDragDropTarget to XAML results in this error:

`The tag 'DataGridDragDropTarget' does not exist in XML namespace 'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit'.`

Though, other DragDropTargets are available: ListBoxDragDropTarget, PanelDragDropTarget, TreeViewDragDropTarget.

A: I suspect it was some kind of omission mistake by the toolkit team when preparing the distribution package: if you download the toolkit source code (from here: http://silverlight.codeplex.com/releases/view/43528) and check the archive's Bin folder, System.Windows.Controls.Data.Toolkit.dll dll is there - that's the one that now contains the DataGridDragAndDrop itself. Just copy it to the rest of your tollkit distribution dlls and reference from your project:
    <dataToolkit:DataGridDragDropTarget
                x:Name="DragAndDrop"
                xmlns:dataToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Toolkit"
                AllowDrop="True" >

A: I don't know why it is gone from the toolkit, since there are lots of online samples that still use DataGridDragDropTarget. I got around this problem by wrapping the grid inside PanelDragDropTarget from the toolkit. Works like a charm.

<toolkit:PanelDragDropTarget x:Name="DragAndDrop" AllowDrop="True" AllowedSourceEffects="Move" >
   <Grid x:Name="LayoutRoot" Width="400" Height="400" />
</toolkit:PanelDragDropTarget>

A: It is actually still in the binaries of the toolkit (at least those distributed via nuget), however it is in a different assembly to the other dragdrop helpers.
You will just need to add the following namespace definition:
xmlns:dragdrop="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Toolkit"


text:
Q: Manually giving the twisted (web) network stack a packet to process? I am running an HTTP server using the twisted framework.  Is there any way I can "manually" ask it to process some payload?  For example, if I've constructed some Ethernet frame can I ask twisted's reactor to handle it just as if it had just arrived on my network card?

A: You can do something like this:
from twisted.web import server
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ClientFactory

class SomeWebThing(Resource):
    def render_GET(self, request):
        return "hello\n"

class SomeClient(Protocol):
    def dataReceived(self, data):
        p = self.factory.site.buildProtocol(self.transport.addr)
        p.transport = self.transport
        p.dataReceived(data)

class SomeClientFactory(ClientFactory):
    protocol = SomeClient
    def __init__(self, site):
        self.site = site

if __name__ == '__main__':
    root = Resource()
    root.putChild('thing', SomeWebThing())
    site = server.Site(root)
    reactor.listenTCP(8000, site)

    factory = SomeClientFactory(site)
    reactor.connectTCP('localhost', 9000, factory)

    reactor.run()

and save it as simpleinjecter.py, if you then do (from the commandline):
echo -e "GET /thing HTTP/1.1\r\n\r\n" | nc -l 9000  # runs a server, ready to send req to first client connection
python simpleinjecter.py

it should work as expected, with the request from the nc server on port 9000 getting funneled as the payload into the twisted web server, and the response coming back as expected.
The key lines are in SomeClient.dataRecieved(). You'll need a transport object with the right methods -- in the example above, I just steal the object from the client connection. If you aren't going to do that, I imagine you'll have to make one up, as the stack will want to do things like call getPeer() on it.

A: What is the use-case?
Perhaps you want to create your own Datagram Protocol

At the base, the place where you
  actually implement the protocol
  parsing and handling, is the
  DatagramProtocol class. This class
  will usually be decended from twisted.internet.protocol.DatagramProtocol.
  Most protocol handlers inherit either
  from this class or from one of its
  convenience children. The
  DatagramProtocol class receives
  datagrams, and can send them out over
  the network. Received datagrams
  include the address they were sent
  from, and when sending datagrams the
  address to send to must be specified.

If you want to see wire-level transmissions rather than inject them, install and run WireShark, the fantastic, free packet sniffer.


text:
Q: Get first image after one special sting with PHP I have a simple question. Just imagine we have this HTML string bellow :

            KEYHERE

            Some text
            Lorem ipsum ...

Now, there is a KEYHERE in the top HTML code.
I have a php variable like this :
$key = "KEYHERE";

Now, i want to get the first image src (address) exactly after that key.
For example , about that top code, i need to get the address.png address in my php codes to use it.
How can i do it?

A: The following code uses the native DOM parser in PHP (DOMDocument) and the XPath implementation to find nodes.
This piece of code will first find your keyword. Once it has found the keyword it will check the siblings of the node to find the first img tag (if any) on the same level.
// gets the first matching sibling (first image found in the dom tree on the same level)
function getFirstImageTag(DOMNode $node) {
    while ($node->nextSibling) {
        $node = $node->nextSibling;

        if ($node->nodeName !== 'img') continue;

        return $node->getAttribute('src');
    }
}

// parses the document / finds the keyword in the html string
function parse($html, $keyword) {
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom);

    // you can use a more strict check here if you are sure the keyword is the only thing in the textnode
    $textNodes = $xpath->evaluate("//text()[contains(.,'$keyword')]");

    foreach ($textNodes as $textNode) {
        if (trim($textNode->textContent) === $keyword) {
            return getFirstImageTag($textNode);
        }
    }
}

echo parse($content, 'KEYHERE');

The above example is based on your example HTML where the keyword is in a textnode. If this isn't the case the above code should be easy to "fix" to your needs.
Note: this answer makes a lot of assumptions. Will it always be a textnode? Will the img tag always be in the same branch of the tree (even on the same level)? Will there be any possibility there are other nodes between the keyword and the img tag.
Demo: http://codepad.viper-7.com/8GkLhW

A: <?php

$key = 'Test';
$html = 'Test ';

$tmp = substr($html, strpos($html, $key));
$start = strpos($tmp, 'src="')+5;
$tmp = substr($tmp, $start);
$end = strpos($tmp, '"');

echo substr($tmp, 0, $end);

http://runnable.com/U8behz5Pfi4HipDa/get-first-image-after-one-special-sting-with-php

A: You should use regular expressions here.
You can use the following code:
<?php

$content = '

            KEYHERE

            Some text
            Lorem ipsum ...

';

preg_match('/(?:KEYHERE\s*)<img(?:\s*)src="(\S*)"/i',$content, $matches);

echo $matches[1];

to get address.png


text:
Q: HP Probook 4530s fan constantly running I have installed Ubuntu 11.10 successfully and everything works perfectly except the fan, it is working constantly and it has nothing to do with the CPU because if I don't open any programs it will remain at high speed.
I figured it may be because of AMD/ATI, I tried different ways of installing it manually and even automatically via Ubuntu itself but never worked!
Is there a (basic if possible) way of fixing this? Maybe controlling the fan speed would do the trick.

A: This is normal functioning for a laptop. Remember that the external temperature of the laptop is not necessarily a guide as to the temperature of the CPU, and naturally manufacturers are cautious when it comes to keeping the hardware cooled!

A: Are you using VmWare ?
If so you are using more of the RAM then normal, it will take 1GB to run the OS image then if your using Win 7 at lest 2GB will need to be working just to keep that running
So it could be the RAM thats going over drive

A: Just installed Ubuntu 20.04 on this notebook with some upgrades like:

*

*now it has 4GB RAM total

*SSD 240GB

the fan goes up and down, so it looks that Ubuntu manages the fan but in the reality it doesn't go to minimum , neither while idle
When I have installed the SSD, 1 hour ago, I took the occasion to make a deep clean of the fan and the air circuit
I have the HDD with windows 7 and so I'm just testing ubuntu 20. So I have pretty sharp the fan speed when Windows 7 is idle:
it is hard to ear the fan
Please read carefully: just installed ubuntu 20 and I'm using Firefox to write in this question
Any idea or hint to make this usable, otherwise it is a pain earing the fan all the time
thank you


text:
Q: Issue with opening csv file Hey guys I have the following:
session_start();
$seterror = 0;

function returnBack(){

    header("Location:../memberinterface.php?getmsg=15");
    exit;

}
function returnBackfile(){

    header("Location:../memberinterface.php?getmsg=16");
    exit;
}
if (!empty($_FILES['csvfile']['error'] ) )
    {

        $seterror = 1;
        returnBack();

    }
    if (empty($_POST['firstname'])){

        $seterror =1;
        returnBack();
    }
    if (empty($_POST['lastname'])){
        $seterrro =1;

        returnBack();
    }
    if (empty($_POST['email'])){
        $seterror =1;

        returnBack();
    }
    if ($seterror !== 1){

    $file = $_FILES['csvfile']['tmp_name'];

    $handle = fopen($file , "r");

    $fileop = fgetcsv($handle,0,"\t");
    echo '
'; var_dump($fileop); var_dump($_POST); echo '
';
    exit;
    $fileop=array_map("strtoupper",array_map("trim",$fileop));

    $firstname_index = array_search(strtoupper($_POST["firstname"]),$fileop);
    if ($firstname_index===false){
        returnBack();
    }
    $lastname_index = array_search(strtoupper($_POST["lastname"]),$fileop);
    if ($lastname_index===false){

        returnBack();
    }
    $email_index = array_search(strtoupper($_POST["email"]),$fileop);
    if ($email_index===false){

        returnBack();
    }
        //open file and store values
        $j = 0;
        while (($fileop=fgetcsv($handle,0,"\t")) !== false)
        {

            $fileop=array_map("trim",$fileop);
            $firstname[$j] = $fileop[$firstname_index];
            if (empty($firstname[$j])){

            returnBackfile();

            }

            $lastname[$j] = $fileop[$lastname_index];
                if (empty($lastname[$j])){

            returnBackfile();

            }
            $email[$j] = $fileop[$email_index];
                if (empty($email[$j])){

            returnBackfile();

            }
            $j++;
        }
        //create sessions, send back to memberinterface.php and open table to display the results to delete
        $_SESSION['CSVRfirstnames'] = $firstname;
        $_SESSION['CSVRlastnames'] = $lastname;
        $_SESSION['CSVRemails'] = $email;

        header("Location:../memberinterface.php?RemoveCSV=1");
    }

And the section where I echo out the columns: echo '
'; var_dump($fileop); var_dump($_POST); echo '
'; - a weird thing happens.
For some CSV files I get this outprinted:
array(4) {
  [0]=>
  string(726) "PK!|l˜l [Content_Types].xml ¢( Ì"]KÃ0†ïÿCÉ4Ù&ˆÈº]øq©çˆÍé–&!'›Û¿÷4û@¤nzÓÐæœ÷}'4ïp¼jL¶"€ÚÙ'õye`K§´ìmú"ß²£´Jg¡`k@6]^§k˜Q·Å'Õ1ú;!°¬¡'ÈK3•ŒôfÂËr.g ½Þ(`c[
6>@%&f+ú¼!"
  [1]=>
  string(71) "`e÷›ÂÖ«`Ò{£K‰T,úæ'o8u¦¬µÇ+Â`¢Ó¡ùÙ`Û÷B[´'l"C|–
aˆ•.Ìß›óÃ""®ªt"
  [2]=>
  string(951) "v€£ Ö±1<¼'Úî¸ø§bi蟤]_>'cðO8®ÿˆ#Òÿ"=$IæÈ`\À3¯v#z̹–Ôk"gøª}ˆƒîÑ$8"(Nß…]d´Ý¹'!QÃ>4º.ßÞ'ÒètÃo·Ú¼S :¼EÊ×Ñ'ÿÿPK!µU0#õL_rels/.rels ¢( Œ'ÏNÃ0ÆïH¼CäûênH¡¥»LH»!TÀ$îµ£$@÷ö"'JcÛÑöçÏ?[ÞîæiTb/Nú(A±3b{×jxŸV b"giÇŽaWÝÞl_x¤"›b×û¨²‹‹º"ü#b4Oñìr¥'0QÊahÑ"¨eÜ"å=†¿P-<ÕÁj{ª>ú<ù²·4Mox/æ}b—NŒ@ž;ËvåCf©ÏÛ¨šBËIƒóœÓÉû"cž&Ú\Oôÿ¶8q"K‰ÐHàó<ߊs@ëë.Ÿh©ø½Î<⧄áMdøaÁÅT_ÿÿPK!Þ"
  [3]=>
  string(530) "(Ôxl/_rels/workbook.xml.rels ¢( ¼"ÏjÃ0ÆƒÑ}q'ne":½ŒA¯[÷&QâÐÄ6–ö'o?"Cº@É.¡ƒ$ü}?Чýá§ïÄjU%)´¥«ZÛ(ø8½><ƒ Ö¶Ò³¨`@'Cq·ÃNsüD¦õ$¢Š%†Ù襤Ò`¯)qmœÔ.ôšcéuyÖ
Ê
  string(9) "Firstname"
  ["lastname"]=>
  string(8) "lastname"
  ["email"]=>
  string(5) "Email"
}

And other csv files I get it nicely organized:
array(3) {
  [0]=>
  string(9) "firstname"
  [1]=>
  string(8) "lastname"
  [2]=>
  string(5) "email"
  [3]=>
}
array(3) {
  ["firstname"]=>
  string(9) "Firstname"
  ["lastname"]=>
  string(8) "lastname"
  ["email"]=>
  string(5) "email"
}

Now I don't know why I am getting the weird symbols for some, and I don't want those so if you could help me that would be great!
David

A: Make sure your .CSV file is saved as "comma delimited" or "tab delimited" in Excel. Cheers!

A: Some of yours "CSV" files are not CSV files. This ackward structure you are printing is potentially the content of a .xlsx file or some of the many other Microsoft Office 2007 formats.
If I create a blank .docx or .xlsx file and see in the hexadecimal editor I will see something like this:
00000000h: 50 4B 03 04 14 00 06 00 08 00 00 00 21 00 DD FC ; PK..........!.Ýü
00000010h: 95 37 66 01 00 00 20 05 00 00 13 00 08 02 5B 43 ; •7f... .......[C
00000020h: 6F 6E 74 65 6E 74 5F 54 79 70 65 73 5D 2E 78 6D ; ontent_Types].xm
00000030h: 6C 20 A2 04 02 28 A0 00 02 00 00 00 00 00 00 00 ; l ¢..( .........
00000040h: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ; ................
00000050h: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ; ................
00000060h: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ; ................

Quite familiar, isn't it?
Those files are actually .zip files contenting a tree of .xml files and other resources belonging to your document.

A: can you try utf8_encode() on the string?


text: Q: Windows 8 Application Timeout Anyone know if there is a way to disable a Windows Metro app from timing out.  I'm looking for something similar to IdelDetectionMOde in WP7?  I have an application that needs to constantly stay up until the user dismisses or closes it.


text:
Q: Using  with a FTP value Is it possible to get access to a file on my FTP doing the following?
<input type="file" name="final" id="final" value="http://www.blah.com.au/artwork/<?=$OrderID?>/<?=$ItemID?>/Final/Final.pdf">;

I know that this specifically didn't work for me, but is there a way to get the file from the FTP so I can send the information to the next page to use?

A: There is no way. Why not use PHP to retrieve the file from your FTP or HTTP site yourself? A simple file_get_contents() will suffice (yes, it works for FTP and HTTP links).
$file_contents = file_get_contents('http://www.blah.com.au/artwork/'.$OrderID.'/'.$ItemID.'/Final/Final.pdf');

Edit
Based on new information, you might want to provide a select box with all the files on the ftp folder. You may do so by using ftp_connect(), ftp_login(), ftp_nlist() and ftp_close()
<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>

A: No. This is not possible. File type input elements are used for uploading files from the client's machine to the web server. They cannot pull remote content. This is a restriction of the HTML standard.
What do you want to accomplish with this? Perhaps there is an alternative solution.

A: I am automating a proofing system for artwork, but we keep having people selecting the wrong files to uploading (through incompetence?). So I am writing it so the users will not have to select the file to attach the e-mail.
All they will have to do is select the client, it will write the e-mail and attach the image from the FTP which is where the artists uploads the final image to.
So I just need to be able to attach the file directly from FTP to an e-mail made by PHPMailer. The only other way I see of doing this is to store the image in the database as data, but I don't think I want to explore that option.


text:
Q: Constraints are affected when changing size class I am using auto-layout & size class concept for my project.I have requirement to displaying different layouts for different screen orientation.So I have used concept of size class.
When my size class is Any X Any I applied constraints for all fields and when I change story board size class for Regular X Regular this constrains effecting there how can I stop them

A: After selecting different classes you can go to attribute inspector, there you can see size classes on some attributes. Just change the size classes over there and updated the properties for that particular classes.

A: For each size class combination you can define a whole new set of constraints by deleting the existing constraints and adding new ones if you wanted to.
When you change the selected size class from the selector at the bottom of a storyboard, your changes to constraints will only affect those for this size class combination.
So, as an example, if you change your storyboard's size class to Regular X Regular, and then delete a constraint, it would not be removed, as it is needed for the ANY x ANY combination, but instead it would set it as 'not installed'. Similarly if you add new constraints at this point, they will be 'installed' only for Regular X Regular, not for Any X Any.
If you are new to Auto Layout and Size Classes, I would strongly suggest watching related WWDC videos, such as this one on the concepts of size classes, as they run through demos which should give you a solid understanding of what is actually happening. It is a bit of a minefield if you try and just hack it together!


text:
Q: RestTemplate GET request with custom headers and parameters resulted in 400 (null) I am writing a client for my REST service using Spring. When I try to consume the service I get 400 response error. It's Bad Request so there must be something wrong with my headers or parameters but I can't figure out what in particular.
My REST controller method:
@RequestMapping(value = "/menu/{count}", method = RequestMethod.GET)
    public String showMenu(@RequestHeader(required = false) String locale, @RequestParam boolean includeVegan,
                           @RequestParam boolean includeMeat, @RequestParam boolean includeGlutenFree,
                           @PathVariable(value = "count") int count) {

        List<Meal> filteredMeals = new ArrayList<>();

        if (count == 0) count = menuService.getMeals().size();

        // Tworzenie przefiltrowanego menu.
        for (Meal meal : menuService.getMeals()) {
            if (count <= 0) break;
            if (meal.isVegan() && includeVegan) filteredMeals.add(meal);
            if (!meal.isVegan() && includeMeat) filteredMeals.add(meal);
            if (meal.isGlutenFree() && includeGlutenFree) filteredMeals.add(meal);
            count--;
        }

        // Tworzenie nazw pozycji posiłków w wybranym języku.
        List<String> menu = new ArrayList<>();
        for (Meal meal : filteredMeals) {
            if (locale == null) {
                // BOTH LANGUAGES
                menu.add(meal.toString(true));
                menu.add(meal.toString(false));
            } else if (locale.equals("pl-PL")) {
                // POLISH LANG
                menu.add(meal.toString(true));
            } else if (locale.equals("en-US")) {
                // ENGLISH LANG
                menu.add(meal.toString(false));
            }
        }

        return menu.toString();
    }

Client fetch method:
private void fetchMenu() {

        String locale = languageComboBox.getSelectedItem().toString();
        boolean includeVegan = includeVeganCheckBox.isSelected();
        boolean includeMeat = includeMeatCheckBox.isSelected();
        boolean includeGlutenFree = includeGlutenFreeCheckBox.isSelected();
        int limit = (int) limitSpinner.getValue();

        System.out.println("DEBUG: locale: " + locale + ", vegan " + includeVegan + ", meat: " + includeMeat +
                ", glutenFree: " + includeGlutenFree + ", limit: " + limit);

        HttpHeaders headers = new HttpHeaders();
        headers.add("locale", locale);

        HttpEntity entity = new HttpEntity(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("includeVegan", includeVegan);
        parameters.put("includeMeat", includeMeat);
        parameters.put("includeGlutenFree", includeGlutenFree);

        RestTemplate template = new RestTemplate();
        ResponseEntity<String> response = template.exchange(
                "http://localhost:8080/menu/" + limit,
                HttpMethod.GET,
                entity,
                String.class,
                parameters
        );

        menu.setText(response.getBody());
    }

Console when calling fetchMenu()
DEBUG: locale: pl-PL, vegan false, meat: true, glutenFree: false, limit: 0
16:57:37.082 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://localhost:8080/menu/0"
16:57:37.082 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
16:57:37.097 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/menu/0" resulted in 400 (null); invoking error handler
Exception in thread "AWT-EventQueue-0" org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:540)
    at ait.lab3.SwingClient.fetchMenu(SwingClient.java:101)
    at ait.lab3.SwingClient.access$000(SwingClient.java:16)
    at ait.lab3.SwingClient$5.actionPerformed(SwingClient.java:65)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:308)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Service method response is String as you can see. This is for my college classes so I need to use @RequestHeader and @PathVariable. I think something might be wrong with my headers/parameters or with path variable count which in fetchMenu() method is represented as limit.
I have no idea what might be wrong with my code. Please developers, help ;)

A: Please make the following change in the fetchMenu() method.
ResponseEntity<String> response = template.exchange(
                    "http://localhost:8080/menu/" + limit +"?includeVegan={includeVegan}&includeMeat={includeMeat}&includeGlutenFree={includeGlutenFree}",
                    HttpMethod.GET,
                    entity,
                    String.class,
                    parameters
            );


text:
Q: can't connect to wireless network on hp mini after installing ubuntu 12.10 i got a used hp mini yesterdayand installed ubuntu 12.10 today. like others, i cannot connect to a wireless network. "enable networking" is checked but no connection options appear. ethernet works. network settings only gives the options "wired" and "network proxy".
i tried the command "sudo lshs -c network" but get "command not found".
in addition, suddenly my arrow keys aren't working (pretty sure they were working yday though). so when i reboot, i can't choose ubuntu since i can't go down... (not sure if i should open a different thread for this). sorry, i rechecked. it's only the "up" and "down" arrows that don't work. it's hardware problem then?
thanks!

A: I have this wireless problem too in HP mini 110 1013tu, install additional driver for broadcom wireless device fix the problem.

A: I have run Ubuntu 12.04 LTS on an HP Mini 210-1000, with no issues.

However, there are issues with Ubuntu 12.10 (and similar for 210-2000 and 210-3000) - due to newer kernels and different chipsets for WiFi.
For better results (regardless of Ubuntu version), you should also upgrade to 2GB RAM.

A: Thanks Nur, I install UbuntuStudio 16.04 x386 in HP Mini 110 3000 and not working Wi-Fi, for this reason I put the ethernet cable to have internet.
Follow your instructions I search in synaptic with:
broadcom
and I found:
bcmwl-kernel-source

I install it and rebot, I remove ethernet cable and working fine Wi-fi


text:
Q: Bootstrap login form text box overlap I've checked out some other answers for this but didn't work for me. Really puzzled by this one.

As you can see the right side overlaps the border. my .css for the box:
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}

I tried using max-width: 100%; but it doesn't seem to chance it.
Code for the form:

form {
border: 3px solid #f1f1f1;
}

input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}

button:hover {
  opacity: 0.8;
}

.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
}

img.avatar {
  width: 40%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

Login To Your Account

  <form action="/action_page.php">

      Username
      <input type="text" placeholder="Enter Username" name="uname" required>

      Password
      <input type="password" placeholder="Enter Password" name="psw" required>

      <button type="submit">Login</button>
      <input type="checkbox" checked="checked"> Remember me

      <button type="button" class="cancelbtn">Cancel</button>
      Forgot password?

  </form>

A: I would maybe add a width to the container.
.container {
    width: 100%;
    padding: 16px;
}

this might fix it.
And then if that fails, you could also add a smaller width to the input textboxes:
input[type=text], input[type=password] {
width: 75%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}

I do not recommend using !imporatant but you could also try adding it to the width:
input[type=text], input[type=password] {
width: 75%!important;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}

I just also noticed your login button is to overlapping. So you need to also add the above width: 75%; to the imput submit too. I do not see if you have a submit imput class you haven't posted it


text:
Q: ¿Cómo hacer un JTextArea que complete con sugerencias? Quiero hacer un programa en el que al escribir en el JTextArea, pero al ir escribiendo una palabra me dé una sugerencia de como completarla. Intenté con AutoCompleteDecorator de Swingx, pero cuando le daba terminar una palabra ya no me dejaba escribir más cuando tenía en true el modo strict, y si lo tenía en "false" ya no me daba más sugerencias después. Usaba la siguiente función:
AutoCompleteDecorator.decorate(textArea, keys, false);


text:
Q: RadFilter - How to Apply Expression programmatically I have a RadFilter that response to the RadGrid. I've successfully do the RadFilter.SaveSettings to save the RadFilter state into the database and RadFilter.LoadSettings to load the RadFilter back.
However, after loaded the RadFilter, I need to click on the 'Apply' button to refresh my RadGrid list. May I know if there is any way I can trigger the filtering of the RadGrid automatically after the RadFilter.LoadSetting?
Thanks.

A: Couldn't find any useful function on this, I do a workaround. In which on Apply Expression event, always store the filter expression in a hidden field.
protected void rftWarehouseItem_ApplyExpressions(object sender, RadFilterApplyExpressionsEventArgs e)
        {
            RadFilterSqlQueryProvider provider = new RadFilterSqlQueryProvider();
            provider.ProcessGroup(e.ExpressionRoot);

            hdfFilterExpression.Value = provider.Result;

            rgdWarehouseItem.MasterTableView.FilterExpression = provider.Result;
            rgdWarehouseItem.Rebind();
        }

During the saving into database, I will store the hdfFilterExpression.Value in the database. When the record is retrieve again from the database, just rebind the gridview.
rgdWarehouseItem.MasterTableView.FilterExpression = record.FilterExpression;
rgdWarehouseItem.Rebind();

A: Just do :
this.RadFilter1.FireApplyCommand();

P.s. Change RadFilter1 for your object name.


text:
Q: Chef - no resource or method named windows_http_acl I'm trying to use the windows_http_acl lwrp inside one of my cookbooks.
When I try and use it, I get this error.
================================================================================
  Recipe Compile Error in c:/chef/cache/cookbooks/foo/recipes/bar.rb
  ================================================================================

  NoMethodError
  -------------
  No resource or method named `windows_http_acl' for `Chef::Recipe "bar"'

  Cookbook Trace:
  ---------------
    c:/chef/cache/cookbooks/foo/recipes/bar.rb:26:in `from_file'

  Relevant File Content:
  ----------------------
  c:/chef/cache/cookbooks/foo/recipes/bar.rb:

   26>> windows_http_acl 'http://+:8080/' do
   27:    user "#{node['domain']}\\foobar"
   28:  end
   29:

My module metadata.rb
....

depends          'windows', '~> 1.37.0'
depends          'iis', '~> 4.1.1'
depends          'chef_handler'

Compare to the opscode/windows metadata.rb
My Berksfile
source "https://supermarket.chef.io"

metadata

cookbook 'windows', git: 'https://github.com/opscode-cookbooks/windows.git'
cookbook 'iis', git: 'https://github.com/opscode-cookbooks/iis.git'

My default recipe
include_recipe 'windows'
include_recipe 'foo::bar'

I have tried running the chef client with debugging, which unfortunately does not reveal any information.
I have even tried to fork the opscode/windows cookbook and add a 'provides windows_http_acl' statement to the metadata.rb file.
version          '1.37.0'
supports         'windows'
source_url       "https://github.com/opscode-cookbooks/windows"
issues_url       "https://github.com/opscode-cookbooks/windows/issues"
depends          'chef_handler'

provides         'windows_http_acl'

What could be causing my cookbook to be unable to find the windows_http_acl resource? I'm pretty new to chef, so maybe there is something simple I"m missing.
Update
I have tried deleting the berksfile.lock to make sure it didn't have an older version
DEPENDENCIES
  foo
    path: .
    metadata: true
  iis
    git: https://github.com/opscode-cookbooks/iis.git
    revision: 58fffd8eb30ac34cc99672995e12289556a4a074
  windows
    git: https://github.com/opscode-cookbooks/windows.git
    revision: b469294f7581863f8d76f8b0c0fbfb5dc2617983

GRAPH
  foo(0.x.x)
    chef_handler (>= 0.0.0)
    iis (~> 4.1.1)
    windows (~> 1.37.0)
  chef_handler (1.1.9)
  iis (4.1.1)
    windows (>= 1.34.6)
  windows (1.37.0)
    chef_handler (>= 0.0.0)

A: A more correct version than the other answer would be
berks upload windows --force --no-freeze

This will force the upload even though you likely froze it on a previous upload. This is a general issue with running pre-release version of a cookbook.

A: As pointed out by coderanger on IRC. Running the following command reveled that the resource was absent from my chef server.
knife cookbook show windows 1.37.0 providers

I deleted the cookbook and reuploaded and the http_acl.rb resource is now listed.
knife cookbook delete windows
rm Berksfile.lock && berks install && berks upload


text:
Q: unable to quit for loop python 2.7. for loop going on for ever I don't know why but the following loop is infinite. I am trying to loop through i and j in sequence till nxt and nyt. but this code is looping for ever and i dont know the way out. P.S : I am not computer science student and is still figuring out coding any help is much appreciated.
    #unperturbed residuals
    for i in range(0,nxt):
      if i==nxt:
        break
      for j in range(0,nyt):
           if index[i,j]!=0:
             ronp, rwnp,
              rgnp=residual.residual(po,sw,sg,i,j,boold,bwold,bgold,
                                    swold,sgold,rsoold,rswold,index,
                                    delx, dely, depth, phi, kx, ky,
                                    ax, ay, h, delt, qo, nxt, nyt, welin,
                                    Vb, pvtgas, pvtoil, pvtw, relpermgo,
                                    relpermow, time, it,fmult)
             ronp1+= (ronp,);rwnp1+=(rwnp,);rgnp1+=(rgnp,)
             rnp+=(ronp,rwnp,rgnp)

A: you haven't said what happens during the residual.residual function with all of those parameters. This shouldn't matter in python 2 however, unless you use xrange instead of range. By definition these for loops will terminate. try setting a counter because they might just be going very slowly.
Also, you don't need the if i==nxt because, so long as nxt isn't decreasing, the for loop will have already terminated.
If you are using Python 3 (contrary to the post tag) then make sure that nxt isn't being increased.


text:
Q: Invite to play app request on Facebook using php but without using javascript FB.ui({
        method: 'apprequests',
        title: 'abc!',
        to: friendID,
        message: 'I play abc! Can you beat me?',
},fbCallback);

this works great on  javascript but how these thing is implemented in php. I tried this-
<?php
$access_token = $facebook->getAccessToken();
$response = $facebook->api(
                            '/'.$fid.'/apprequests',
                            'POST', array(
                                      'title' => 'Musical Quiz!',
                                      'message' => 'I just play musical quiz! Can you beat me?.',
                                      'access_token' => $access_token
                           ));

?>

but it request only those user who already played that game. Is there any way, through which i can invite to play any of my facebook friends?


text:
Q: What is the right syntax for MySQL TOP? Can anyone tell me what is wrong with this query? It's printing the else statement, and it's giving the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2 * FROM `sql_tbl`' at line 1.

SELECT TOP 2 * FROM `sql_tbl`

A: The equivalent "TOP" syntax in MySQL is "LIMIT":
So:
SELECT TOP 2 * FROM `sql_tbl`

becomes:
SELECT * FROM `sql_tbl` LIMIT 2


text:
Q: How to present new view in SwiftUI after login I need to know who to present a new view using SwiftUI (following MVVM design pattern).
For example, once the user enters the credentials to login, pressing the "login" button should take them to the home page of the app without being able to return to the login page.
I have been looking at the documentation from Apple, as well as other questions in Stackoverflow, but they all seem to be using navigation views (i.e. there is a navigation bar at the top which allows the user to return to the previous view).
Below is the code of how I would have accomplished this using UIKit, as well as an image to visually represent what I want to accomplish.
let vc = MainMenuController()
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil);
Sample image of desired outcome

A: this is how i implemented it in my code in ContentView.swift:
@State var loggedIn: Bool = false

var body: some View {
  VStack {
    if loggedIn {
      ShowSomeTabView()
    } else {
      ShowLoginScreen()
    }
  }.onAppear {
    self.checkAuthorized()
  }
}

private func checkAuthorized() {
  if loggedIn() {
    self.loggedIn = true
  }
}


text:
Q: I am a rookie and would appreciate assistance in solving this issue Would someone mind assisting me with the CSS code I need to have these 4 boxes with the text resizing the boxes for mobile devices (phones)..
This is the website...  http://westmetrofire.stg.colorado.gov/
Here's the code (and I apologize I don't know how to use the coding section here)..  I think the issue is here (and I need to come up with another @media section that defines the phone screen size)...
@media (max-width: 950px) and (min-width: 450px) {
    .box {
        text-align: center;
        height: 180px;

I've tried several different things and the images gets all skewed.
Thanks for any assistance.  Jim

A: Hello Jim,
   @media (max-width: 450px)
      .box {
        height: 500px;
      }

I switched the .box height and was able to get the headings, paragraphs, and the images inside the boxes on what would be an iPhone 12 Pro display. This does however lead to some whitespace below since not all the elements inside each box are taking up the same space. I am also fairly new to CSS, however if this were me I would look into adding a class for each box so you can size them individually until everything fits. For example .box-red or .box-blue. These can then be added to the HTML elements and styled under that media query.
I'm almost certain there is an easier solution, but maybe this well help in the meantime.


text:
Q: how to align bottom text to the middle of icons I want to align the bottom text to the icons and make equal spaces between all icons
Fiddle: http://jsfiddle.net/ZLkwt/3/

Smart TV

Tablet

Android

Pc

Mac

dfgdfgdfgd

dfgdfgdfgdg

A: For equal spaces between all icons (images) use padding:
img {
  padding: 0 10px; // 10px horizontal padding
}

And to align it, use:
h1 {
  float: left;
}

h2 {
  float: right;
}

For the middle border, I am not sure but if you want a border, then just add this:
#middle_border {
  border: 1px solid #999; // or anyother color
}

For middle text element use this:
#middle_txt {
  text-align: center; // to align its children to the center..
  // or use this:
  width: 100px;
  margin: 0 auto; // it will be placed in the center..
}

A: I'm going to answer on "make equal spaces between all icons part.
First off, I assume all icons (jpgs) have the same dimensions to start with.
You could try to add padding or margin (-left & -right) to let them have the same seperation width:
.icon_middle {
    float: right;
    text-align: bottom-center;
    width: 100px;
    height: 85px;
    padding-left: 20;
    padding-right: 20px;
}

But it is unclear to me whether that was your question? Could you maybe give some more context/explenation?


text:
Q: UnderscoreJS: trim array of objects based on condition I have an array of JSON object as shown below:
var data = [
  {name: '', age: 12},
  {name: 'bcd', age: 15},
  {name: 'cdf', age: 13},
  {name: '', age: 11},
  {name: 'fgh', age: 8},
  {name: '', age: 10},
];

using underscore I want to trim this object in such a way that it should return:
[{name: 'bcd', age: 15},
{name: 'cdf', age: 13},
{name: '', age: 11},
{name: 'fgh', age: 8}]

I tried with below code:
var firstIndex = _.indexOf(data, _.find(data, function(d){ return d.name !== ''; }));

var lastIndex = _.indexOf(data, _.find(data.slice().reverse(), function(d){ return d.name !== ''; }));

console.log(data.slice(firstIndex, lastIndex + 1) );

But I think, there should be a better way than this.
Here is the JSFiddle
Edit:
I want all data from the top and bottom to be trimmed where name is blank. But not in middle of the array element.
Same as string.Trim() method. when I apply trim on " one two three " text, it will remove blank space from the starting and end but not the space between words.

A: Looks like you want to return the array without first and last item, then use slice
var trimmedData = data.slice( 1, data.length - 1 );

I want all data from the top and bottom to be trimmed where name is
  blank. But not in middle of the array element.

Define a trimLeftFn
var trimLeftFn = arr => {
   var hasValue = false;
   arr = arr.filter( s => {
      hasValue = hasValue || s.name.length > 0;
      return hasValue;
   });
   return arr;
};

var trimmedData = trimLeftFn( trimLeftFn (data ).reverse() ).reverse();

Demo

var data = [
  {name: '', age: 12},
  {name: 'bcd', age: 15},
  {name: 'cdf', age: 13},
  {name: '', age: 11},
  {name: 'fgh', age: 8},
  {name: '', age: 10},
];

var trimLeftFn = arr => {
  var hasValue = false;
  arr = arr.filter(s => {
    hasValue = hasValue || s.name.length > 0;
    return hasValue;
  });
  return arr;
};

var trimmedData = trimLeftFn(trimLeftFn(data).reverse()).reverse();

console.log(trimmedData);

A: your logic is fine, just use _.findLastIndex() instead of using _.findIndex() on the reversed array:

const data = [
  {name: '', age: 7},
  {name: '', age: 12},
  {name: 'bcd', age: 15},
  {name: 'cdf', age: 13},
  {name: '', age: 11},
  {name: 'fgh', age: 8},
  {name: '', age: 10},
  {name: '', age: 12},
  {name: '', age: 14},
];

function trimArray(predicate, arr) {
  const start = _.findIndex(arr, predicate);
  const end = _.findLastIndex(arr, predicate);

  return arr.slice(start, end + 1);
}

const result = trimArray((o) => o.name !== '', data);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


text:
Q: Multidimensional array combines same key and value into already defined array element I new to php, getting mysql results storing json but its not gettng coorect format what I want.
Pease check below code
$sql = "select * from en_providers where providerEmailAddress='" . $email . "' and providerPW='" . $password . "'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (mysqli_num_rows($result) > 0) {
    $resultArray = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $providerID               = $row['providerID'];
        $resultArray['providers'] = $row;
        $resultArray['providers']['providerIDActivities'] = unserialize($row['providerIDActivities']);
        $resultArray['providers']['providerIDBodies'] = unserialize($row['providerIDBodies']);
        $resultArray['providers']['providerIDOthers'] = unserialize($row['providerIDOthers']);

        $sql1 = "select * from en_venues where providerID = $providerID ";
        $result1 = mysqli_query($con, $sql1) or die("Error in Selecting " . mysqli_error($connection));
        $i = $j = $l = $x = $m = 0;
        while ($row1[] = mysqli_fetch_assoc($result1)) {
            //$resultArray['venues'][]['venueIDFacilities'] = unserialize($row1[$j++]['venueIDFacilities']);
            $venueID                                          = $row1[$j++]['venueID'];
            $k                                                = 0;
            $venueFacilities                                  = unserialize($row1[$i++]['venueIDFacilities']);
            $resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;

            //$resultArray['venues'][$x++]['venueID'] = $venueID;
            $resultArray['venues'] = $row1;
            //echo json_encode($resultArray);

        echo json_encode($resultArray);
    }
}

Output is:
{
    0: {
        "venues": {
            "venueIDFacilities": [
                "1",
                "2",
                "3"
            ],
        }
    },
    1: {
        "venues": {
            "venueIDFacilities": [
                "4",
                "7"
            ],
        }
    }
},
"providers": {
    "providerIDActivities": [
        "218",
        "219"
    ],
    "providerIDSports": "a:1:{i:0;i:82;}",
    "providerIDBodies": [
        "112"
    ],
},
venues": {
    0: {
        "venueID": "9",
        "providerID": "2"
    },
    1: {
        "venueID": "238",
        "providerID": "2",
        "venueActive": "yes"
    }
}

But I need those VenueFailities to be in respective venues but result is getting outside. How can I append those values into venues?
I am trying for one day with different ways but it's not getting correct format.
Output I want:
"providers": {
    "providerIDActivities": [
        "218",
        "219"
    ],
    "providerIDSports": "a:1:{i:0;i:82;}",
    "providerIDBodies": [
        "112"
    ],
},
venues": {
    0: {
        "venueID": "9",
        "providerID": "2",
        "venueIDFacilities": [
            "4",
            "7"
        ]
    },
    1: {
        "venueID": "238",
        "providerID": "2",
        venueIDFacilities": [
            "4",
            "7"
        ]
    }
}

A: This line
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;

should be
$resultArray['venues'][$x++]['venueIDFacilities'] = $venueFacilities;


text:
Q: How to code html5/PHP/JS/JQuery so that we can resize or crop images in iPad's Safari? I have a website that allows user to upload images onto website via mobile safari, iOS6. Problem is that i can't find a way to allow users to crop the images.
Anyone has any solution?


text:
Q: Julia SimpleHypergraphs - Hypernetx Error I tried to compute a small example with the library SimpleHypergraphs. I followed the install instructions however, I have this error :
ERROR: "HyperNetX is not installed in Python used by this Julia. Install HyperNetX and reload SimpleHypergraphs.jl"

Here's my code:
using PyCall
using Conda
Conda.runconda(`install matplotlib --yes`)
Conda.runconda(`install networkx --yes`)
run(`$(PyCall.python) -m pip install hypernetx`)

using SimpleHypergraphs

h = Hypergraph{Float64}(5,4)

h[1:3,1] .= 1.5
h[3,4] = 2.5
h[2,3] = 3.5
h[4,3:4] .= 4.5
h[5,4] = 5.5
h[5,2] = 6.5

draw(h, HyperNetX; width=5, height=5)

I don't understand why this error occurs since hypernetx is well installed.

A: It seems that pandas has been added to the dependencies of hypernetx and now it will not load unless pandas is available.
Restart your Julia session and run
using Conda
Conda.runconda(`install pandas --yes`)

Now it will work as expected:
draw(h, HyperNetX; width=5, height=5)

Thanks for posting that out! - I will add it to the README of SimpleHypergraphs.
Finally, note that SimpleHypergraphs uses the Python only for the last step - plotting. All processing/computations always take part in Julia so do not worry about all those Python libraries.


text:
Q: Advanced Query in Elasticsearch I have started using elasticseach engine with my application, and I have encountered a problem.
I'm currently indexing as the following: each entry has its -
username
file_path
md5

My goal is to determine how many unique (count of 1 per username ) md5 are currently in the database.
I saw many approaches like using aggregations or counts operators by I havent managed to assemble the whole search query.
FYI, Im using python to execute the elasticsearch queries.
EDIT:
my script looks like this ATM:
import elasticsearch
from elasticsearch.helpers import scan

es = elasticsearch.Elasticsearch()

q = {
        "aggs" : {
            "distinct_colors" : {
                "terms" : {
                    "field" : "md5"
                    }
                }
            }
        }

res = es.search(index = "my-index", body = q, search_type="count", size = 0 )
for r in res['aggregations']['distinct_colors']['buckets']:
        print( r )

I have also used a "scan" approach but with no success:


text:
Q: SQL Drop and Create does not script indexes on recreate? I am adding new columns to a table and it is forcing me to drop create the table. Do I have to manually re-add the indexes? Or can I get the generated script to recreate the indexes for me?

A: If you're using the table designer in Management Studio, then it should recreate any indices/foreign keys automatically.
The only thing I've seen drop from this kind of operation is a schemabound view.  The schema binding (and any associated clustered/full text index) will drop from a schemabound view if you drop/recreate the source table.


text:
Q: iOS Bundle Display Name - en-GB and en-US Context:
We are developing an iOS app that has the word Math/Maths in it. This needs to change depending if the device's language is English or British English.
Problem:
So, I have two InfoPlist.string files for en-GB and en-US and in the iOS simulator the App displays either an en-GB or en-US App name depending if the language was set to English or British English. However, it's very glitchy (sometimes working, sometimes not) and according to Apple's Dev guide it's not (or shouldn't be) possible! That's not to say the doc isn't outdated or wrong.
From: https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPInternational/Articles/LanguageDesignations.html#//apple_ref/doc/uid/20002144-BBCEGGFF

Important: In iOS, the bundle interfaces do not take dialect or script
  information into account when looking for localized resources; only
  the language designator code is considered. Therefore if your project
  includes language-specific project directories with both a language
  and region designator, those directories are ignored. The bundle
  interfaces in OS X do support region designators in language-specific
  project directories.

Am I on a wild goose chase and it's not actually possible or it is, and just very buggy? If it is possible, how?

A: You are right. It is not possible automatically. For localizeng the os looks for the language, not for the region. So it just takes into account the en. But the good news is that there is a indirect solution which requires little effort: check the approved answer here.


text:
Q: Cobol program to print its executable name I am trying to find a clause by which i can get the name of executable
,is it possible to print COBOL executable name when executable is run

A: With Enterprise COBOL on z/OS, you might try looking at the prolog, either the entry name, found in PPA1 or the compilation unit name, found in PPA4 - more info about this on Knowledge Center.


text:
Q: Shapes.Rectangle или Drawing.Rectangle? Обращался к интернету, там сказано, что на WinForms сейчас программируют только дриопитеки и уже как 10 лет используют WPF.
Ок! Решил в плане самообразования сделать Rectangle с полупрозрачным контуром и заливкой на Canvas, который можно тянуть за все стороны, перетаскивать и т.д. используя Windows.Shapes.Rectangle (WPF же)
Но что то мне подсказывает, что этот прямоугольник какой то тормозной в плане отрисовки.
Даже label который прицепил к позициям курсора, немного отстаёт от самого курсора при быстром движении.
А так же BackGround.Window на 3840 точек в ширину и 1080 в высоту заливается c помощью <SolidColorBrush Opacity="0.10" Color="Black"/> тормознуто.
Не хоп и сразу залит, а прям видно как заливается при появлении окна xD
И это i7-6700k с gtx 1070
Судя по всему надо использовать всё таки System.Drawing для 2-D графики и подобных задач ?

A: Да, использование прозрачности требует серьезных затрат ресурсов. Тем более при отрисовке окна таких размеров (с высокой вероятностью 3840 х 1080 выходит за пределы максимального размера, поддерживаемого аппаратным ускорением видеоадаптера, и WPF переходит в режим программной отрисовки). Однако, в Windows Forms вообще нет поддержки прозрачности в той мере, как в WPF, поэтому такое сравнение несколько некорректно. Кроме того, WPF обладает другими преимуществами, например, векторная графика и возможность декларативного описания объектов в виде XAML. Я бы сказал, что следует изучать все же WPF, если нет какой-то особой причины оставаться с WinForms.


text:
Q: Using two cores of esp8266 I know that the esp8266 is a dual core micro controler, is there a way to use control these two cores to different codes simultanuesly using arduino ide?

A: ESP8266 is based on a Tensilica L106 32-bit RISC processor ref which is single-core processor and thus you can't do real multiprocessing on it.
I'm not sure what you are trying to achieve but there is a good Scheduler library that may help you run simultaneous functions.
P.S: In general on a multi-core microcontroller, you can't simply put multiple codes inside each core. The process of multiprocessing should handle by its firmware and you need to use its tools like SDKs to do real multiprocessing.


text:
Q: Getting percent of totals in a pandas dataframe I have a dataframe configured in the following way:
date_string | type | amount

 2015-01-01 |  a   | 500

 2015-01-01 |  b   | 300

 2015-01-01 |  c   | 200

 2015-01-02 |  a   | 400

 2015-01-02 |  b   | 600

 2015-01-02 |  c   | 100

I am looking to add a new column with the percent total broken down by date, and get something like this:
date_string | type | amount | percent

 2015-01-01 |  a   | 500    | 0.5

 2015-01-01 |  b   | 300    | 0.3

 2015-01-01 |  c   | 200    | 0.2

 2015-01-02 |  a   | 300    | 0.3

 2015-01-02 |  b   | 600    | 0.6

 2015-01-02 |  c   | 100    | 0.1

A: Use GroupBy.transform with sum, what is divided by original column by Series.div:
df['percent'] = df['amount'].div(df.groupby('date_string')['amount'].transform('sum'))
print (df)
  date_string type  amount   percent
0  2015-01-01    a     500  0.500000
1  2015-01-01    b     300  0.300000
2  2015-01-01    c     200  0.200000
3  2015-01-02    a     400  0.363636
4  2015-01-02    b     600  0.545455
5  2015-01-02    c     100  0.090909

A: This will work
import numpy as np
df.groupby(['amount', 'date_string']).sum().transform(lambda x: x/np.sum(x))


text:
Q: Choosing image from windows phone media library and set as page background I am trying to retrieve an image from the phone library and set it as the page background using the following code
    private void selectImageFromMediaLib()
    {
         selectphoto = new PhotoChooserTask();
         selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
     selectphoto.Show();
    }

    private void selectphoto_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            backgroundUri = new Uri(e.OriginalFileName, UriKind.Absolute);
            var bitmap = new BitmapImage(backgroundUri);
            ImageBrush imageBrush = new ImageBrush();
            imageBrush.ImageSource = bitmap;
            this.LayoutRoot.Background = imageBrush;
     }
    }

However, the page background turns black so the photo was not retrieved/created correctly. What is the correct path for the URI to the device library? Isn't using UriKind.Absolute enough?

A: You can't use the PhotoResult.OriginalFileName property to read the file, instead use the
PhotoResult.ChosenPhoto stream and assign it to the bitmap.ImageSource property in your code.

A: try this. It works for me
PhotoChooserTask selectphoto;
private void selectImageFromMediaLib()
{
   selectphoto = new PhotoChooserTask();
   selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
   selectphoto.Show();
}

private void selectphoto_Completed(object sender, PhotoResult e)
{
   if (e.TaskResult == TaskResult.OK)
   {
       var imageBytes = new byte[e.ChosenPhoto.Length];
       e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
       BitmapImage bitmapImage = new BitmapImage();
       MemoryStream ms = new MemoryStream(imageBytes);
       bitmapImage.SetSource(ms);
       ImageBrush imageBrush = new ImageBrush();
       imageBrush.ImageSource = bitmapImage;
       this.LayoutRoot.Background = imageBrush;
    }
}


text:
Q: How to create a Debian/Fedora live USB on Ubuntu 17.10? I tried to use Startup Disk Creator, but it seems that it can only create Ubuntu live disks. Is there any software that can help me create live USB disk for any .iso files? Please also mention how to use that software or provide a link to the guide of using that software.

A: You can use mkusb in Ubuntu to create USB boot drives for all the major linux distros. And you can use it in many other linux distros to create Ubuntu boot drives. The standard method clones the iso file to a live-only system on the target drive using dd under the hood. mkusb 'wraps a safety belt' around the powerful but dangerous dd tool.
See this link,
help.ubuntu.com/community/mkusb
sudo add-apt-repository universe  # only for standard Ubuntu

sudo add-apt-repository ppa:mkusb/ppa  # and press Enter
sudo apt-get update
sudo apt-get install mkusb mkusb-nox usb-pack-efi

There is a list of tested operating systems,
Linux distros where mkusb works

A: You could use dd from the terminal.
sudo dd if=/path/to/image.iso of=/dev/sd{device letter here}

You can get the device letter by running in the terminal
fdisk -l

and check which device is your pendrive.

A: You can use the restore disk image option in Disk Utility.

Unetbootin is also a great tool for making bootable pendrive.
Installation:
sudo add-apt-repository ppa:gezakovacs/ppa
sudo apt-get update
sudo apt-get install unetbootin

After installation, run the software and follow the on-screen instructions.


text:
Q: Unregistering Globals? I'm having trouble understading this function. I know what register_globals is and how long it has been depreciated from PHP but I'm looking at this code and I'm like, what in the?...
<?php
    //Undo register_globals
    function unregister_globals() {
        if (ini_get(register_globals)) {
            $array = array('_REQUEST', '_SESSION', '_SERVER', '_ENV', '_FILES');
            foreach ($array as $value) {
                foreach ($GLOBALS[$value] as $key => $var) {
                    if ($var === $GLOBALS[$key]) {
                        unset($GLOBALS[$key]);
                    }
                }
            }
        }
    }
?>

The part in which I'm not understanding is this...
foreach ($array as $value) {
    foreach ($GLOBALS[$value] as $key => $var) {
        if ($var === $GLOBALS[$key]) {
            unset($GLOBALS[$key]);
         }
     }
 }

This foreach loop is cycling through each value in $array we defined then the inner foreach loop is grabbing a super global array from GLOBALS whether it is _REQUEST, _SESSION, _SERVER, _ENV, _FILES, etc... Afterwords it seems like the condional is checking to see if $var is equal to a GLOBAL variable or what not. If so then we'll unset it.
But I'm still having a major difficulty wrapping my head around this one...
UPDATE
Here is the snippet of code I'm experimenting with and debugging. What happens if register_globals is on, and a hacker comes barreling along, inserts ?auth=1 into the query string? Will auth be deleted from GLOBALS or will it be echoed out?
if( true ) {
    $globals = array(
        '_COOKIE',
        '_GET',
        '_POST',
        '_REQUEST',
        '_SERVE',
        '_SESSION'
    );

    foreach($globals as $global) {
        foreach($GLOBALS[$global] as $k => $v) {
            /* $GLOBALS['_GET'] on the first loop; */
            /* IF WE SAY, $GLOBALS['app_dir'], WE GET THE VALUE */

            if( $v == $GLOBALS[$k] ) {
                echo "K=> " . $k . "
";
                echo "V => " . $v . "
";
                echo "GLOB => " . $GLOBALS[$k] . "
";
            }
        }
    }

            echo $authorized; // a intentional non-defined variable

    //print_r($GLOBALS);
}

Thanks for your time.

A: Yes, this code looks weird:
foreach ($GLOBALS[$value] as $key => $var) {
        if ($var === $GLOBALS[$key]) {//<- ?
            unset($GLOBALS[$key]);
         }
     }

You can imitate what's going in, using a simple array, and make sure, that this if is absolutely useless:
<?php
$data = array(1,2,3);

foreach ($data as $key => $var) {
    var_dump($var);
    var_dump($data[$key]);
    if ($var === $data[$key]) {
        unset($data[$key]);
    }
}

output:
int(1)
int(1)
int(2)
int(2)
int(3)
int(3)

As you can see, the values are equal every time, and in the end $data will be empty.
Update
Here is the script, you can reproduce on your machine:
<?php
extract($_REQUEST);

var_dump($auth);
$array = array('_REQUEST', '_SESSION', '_SERVER', '_ENV', '_FILES');
foreach ($array as $value) {
    if(isset($GLOBALS[$value]))
    {
        foreach ($GLOBALS[$value] as $key => $var) {
            unset($GLOBALS[$key]);
        }
    }
}
var_dump($auth);

While calling it like this: http://site/script.php?auth=1
It gives the following output for me:
string(1) "1"

Notice:  Undefined variable: auth on line 14
NULL

So, it seems, that auth variable was destroyed. But $GLOBALS array still contains a lot of data.
Update 2
I think, our error was here:
unset($GLOBALS[$key]);

Why are we unsetting the key of a foreign array. If you do it like this:
$array = array('_REQUEST', '_SESSION', '_SERVER', '_ENV', '_FILES');
foreach ($array as $value) {
    if(isset($GLOBALS[$value]))
    {
        foreach ($GLOBALS[$value] as $key => $var) {
            unset($GLOBALS[$value][$key]);
        }
    }
}

It will empty $_REQUEST, $_SESSION and all the other necessary arrays.

A: Globals ( especially $_GET, $_POST, $_COOKIE, $_ENV, ... and the $GLOBALS-Entries of this Superglobals ) are initially filled by PHP and should never be (over)written oder deleted by any application.
Any manipulation of Superglobal-Values drops the authenticity of the current request and works against the intentional behavior of PHP.
The nested foreach means that a given Array would be iterated ( outter foreach ) and each entry would be iterated too. The Array-Key is served as $key and the array-value as $var

A: Now that I was able to see how this actually works, I was able to wrap my head around it. Essentially if users are using PHP 5.3.0 or below and 'register_globals' is enabled, hackers can query common variables names such as 'authorized', 'username', etc to feed in there own values if the variable was already defined by the developer.
Example:
if( is_authorized() ) {
    $auth = 1;
}

if( $auth ) {
    // do authorization code here!!!
} else {
    show_login();
}

You can see $auth is condiotionally defined. If a hacker comes along and tries something like, index.php?auth=1 or index.php?auth=true then PHP will register that as a global value, it'll be checked in the conditional, and our hacker will have access to the application.
I found that...
foreach ($array as $value) {
    foreach ($GLOBALS[$value] as $key => $var) {
        if ($var === $GLOBALS[$key]) {
            unset($GLOBALS[$key]);
        }
    }
}

... actually unsets these values and the hacker won't have access, however, there is also a bug as I previously thought. I have two globals in my framework called $app_dir and $sys_dir pointing to two important directories. If hackers come along and say something like index.php?app_dir=application&sys_dir=system then it'll actually unset those global variables from $GLOBALS. This calls for a potential danger inside of my framework for anyone using it on PHP 5.3.0 or below.
Basically how this works is the conditional checks to see if $var (our value, 'system') is equal to the same value as what's inside $GLOBAL['sys_dir']. Anyone know how to fix this?