Q: Unexpected end of MIME multipart stream in reading the second time in Web API at first step I tried to read the contents into MultipartMemoryStreamProvider with the following code
 var multipartMemoryStreamProvider = await Request.Content.ReadAsMultipartAsync();

It solve my problem in getting the input File in memory.In this case I have access to other contents Key , but not value .
I tried to get them with reading again the Contents into MultipartFormDataStreamProvider variable
string root = HttpContext.Current.Server.MapPath("~/uploads");
var provider = new MultipartFormDataStreamProvider(root);

Seems because I try to read the stream twice , it has the following error:

Unexpected end of MIME multipart stream. MIME multipart message is not
  complete

My first preference is to convert MultipartMemoryStreamProvider to MultipartFormDataStreamProvider
Is it possible to do that?


Q: type 'Future' is not a subtype of type 'Future>' Estoy teniendo un problema a la hora que quiero crear una lista para ver mis prospectos que estoy guardando en mi database sqflite, me arroja el siguiente error:

type 'Future' is not a subtype of type 'Future<List>'

El problema es que no encuentro donde esta mi error, tengo la función en la database, mi provider y el home_page que es donde lo mando llamar:
función en la base de datos:
Future<List<ProspectModel>> getAllProspects() async {
    final db = await database;
    final resp = await db.query('Prospect');

    List<ProspectModel> list = resp.isNotEmpty
        ? resp.map((p) => ProspectModel.fromJson(p)).toList()
        : [];

    return list;
  }

tambien intente:
Future<List<ProspectModel>> getAllProspects() async {
    final db = await database;
    final resp = await db.query('Prospect');

    return resp.isNotEmpty
        ? resp.map((p) => ProspectModel.fromJson(p)).toList()
        : [];
  }

prospect_provider.dart:
class ProspectProvider extends ChangeNotifier {

  List<ProspectModel> prospects = [];

  String selectType = 'http';

  Future<ProspectModel> newProspect(String valor) async {

    final newProspect = new ProspectModel();
    final id = await DBProvider.db.newProspect(newProspect);

    //asigna el ID de la db al modelo
    newProspect.id = id;
    this.prospects.add(newProspect);

    notifyListeners();
  }

  viewProspects() async {

    final prospects = await DBProvider.db.getAllProspects();

    this.prospects = [...prospects];
    notifyListeners();
  }

  deleteProspect(int id) async {

    await DBProvider.db.deletePros(id);
    this.viewProspects();
  }
}

home_page.dart:
class HomePage extends StatelessWidget {

  final prospectProvider = new ProspectProvider();

  @override
  Widget build(BuildContext context) {

    final bloc = Provider.of(context);
    return Scaffold(

      appBar: AppBar(title: Text('Home')),

      body: FutureBuilder<List>(
        future: prospectProvider.viewProspects(),
        initialData: List(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {

          if (snapshot.hasData) {
            final prospects = snapshot.data;

            return ListView.builder(
              itemCount: prospects.length,
              itemBuilder: (context, i) => _createItem(context, prospects[i]),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
      floatingActionButton: _createButton(context),
    );
  }

  _createItem(BuildContext context, ProspectModel prospect) {

    return new ListTile(
      title: Text(prospect.nombreNucleo),
      subtitle: Text(prospect.nombreContacto),
    );
  }

  _createButton(BuildContext context) {

    return FloatingActionButton(
        child: Icon(Icons.add),
        backgroundColor: Colors.lightGreen,
        onPressed: () {
          Navigator.pushNamed(context, '/prospecto');
        });
  }
}

porspect_model.dart
ProspectModel prospectModelFromJson(String str) =>

ProspectModel.fromJson(json.decode(str));

String prospectModelToJson(ProspectModel data) => json.encode(data.toJson());

class ProspectModel {

  ProspectModel({

    this.id,
    //this.idTp,
    this.nombreNucleo = '',
    this.nombreContacto = '',
    this.municipioProspecto = '',
    this.telefonoProspecto,
    this.emailProspecto = '',
    this.observacionesProspecto = '',
    //id usuario viene del servidor
    //this.usuAlta,
    this.fechaAlta = '',
    //this.idCliente,
    this.statusPros = true,
    this.hectareasAprox = 0.0,
  });

  int id;

  //int idTp;

  String nombreNucleo;

  String nombreContacto;

  String municipioProspecto;

  String telefonoProspecto;

  String emailProspecto;

  String observacionesProspecto;

  //int usuAlta;

  String fechaAlta;

  //int idCliente;

  bool statusPros;

  double hectareasAprox;

  factory ProspectModel.fromJson(Map<String, dynamic> json) => ProspectModel(

        id: json["id"],
        //idTp: json["id_tp"],
        nombreNucleo: json["nombre_nucleo"],
        nombreContacto: json["nombre_contacto"],
        municipioProspecto: json["municipio_prospecto"],
        telefonoProspecto: json["telefono_prospecto"],
        emailProspecto: json["email_prospecto"],
        observacionesProspecto: json["observaciones_prospecto"],
        //usuAlta: json["usu_alta"],
        fechaAlta: json["fecha_alta"],
        //idCliente: json["idCliente"],
        statusPros: json["status_pros"],
        hectareasAprox: json["hectareas_Aprox"],
      );

  Map<String, dynamic> toJson() => {

        "id": id,
        //"id_tp": idTp,
        "nombre_nucleo": nombreNucleo,
        "nombre_contacto": nombreContacto,
        "municipio_prospecto": municipioProspecto,
        "telefono_prospecto": telefonoProspecto,
        "email_prospecto": emailProspecto,
        "observaciones_prospecto": observacionesProspecto,
        //"usu_alta": usuAlta,
        "fecha_alta": fechaAlta,
        //"idCliente": idCliente,
        "status_pros": statusPros,
        "hectareas_Aprox": hectareasAprox,
      };
}

A: Define el tipo de dato de respuesta en tus métodos:
Cambia

viewProspects() async {

Por
Future<List<ProspectModel>> viewProspects() async {

return this.prospects;

De igual manera con el FutureBuilder, cambia
 FutureBuilder<List>(
    future: prospectProvider.viewProspects(),
    initialData: List(),

Por
 FutureBuilder<List<ProspectModel>>(
    future: prospectProvider.viewProspects(),
    initialData: List<ProspectModel>(),


Q: how do I accomodate multiple spellings in linux if/then script? I am new to coding and my Linux/Ubuntu assigment is requesting that I accomodate mulitple spellings for the argument in an if/then statement.  I can't find anything about this online, at least nothing with these search terms.  Can someone help?  I am using 15 workstation.

*

*Write a program called isyes that returns an exit status of 0 if its argument is yes, and 1 otherwise. For purposes of this exercise, consider y, yes, Yes, YES, and Y all to be valid yes arguments

*Is there a way to so thais that will not reveal all the different spellings in either the question or the response?  That is ugly.
Thank you!

A: You can write something like this:
read -p "Enter the answer in Y/N: " value

if [[ "$value" = [yY] ]] || [[ "$value" = [yY][eE][sS] ]];
then
     echo 0;   # Operation if true
else
     echo 1;   # Operation if false
fi

A: you can fix this issue in many ways.
use this code on awk to fix your problem.
#!/bin/bash

read -p "choose your answer [Y/N]: " input

awk -vs1="$input" 'BEGIN {
    if ( tolower(s1) == "yes" || tolower(input) == "y" ){
        print "match"
    }
    else{
        print "not match"
    }
}'


Q: Shiny app is disconnecting after 20 seconds on iPhone but not on onePlus I have made a shiny app that is deployed in shinyapps.io: https://hibashaban.shinyapps.io/muddakir/, I have noticed that the app disconnects from the server when I access it on my iphone (whether on chrome or safari) and leave the browser app for about 20 seconds. I have not been able to reproduce this problem in the chrome app on a onePlus phone so it seems to be an iOS or iPhone specific problem.
Is there anyway I can have it not disconnect from the server so quickly? Any ideas appreciated because I've run out of them. I have looked at timeout times on shinyapps.io/admin/#/applications/all but nothing seems to solve this specific problem.
I also tried deploying the app on an AWS instance using a shiny server. Same problem.
I've also tested this using another app I did not write and it did the same thing, so it's not a problem specific to my web app: https://jvadams.shinyapps.io/Testing/

this is what I got after 20 secs of leaving the chrome app..this is a problem because I know most of the users of my app will be using it on the phone, and lots of them have iPhones, I can't have them losing the progress just after a few seconds of leaving the browser app.


Q: IIS 7 Redirect using conditions I asked this question previously I think poorly - so here in a nutshell...
I have a chinese and australian site
First Redirect is good
http://mycompany.com/myproduct --> http://mycompany.com/products/myproduct

I also need this
http://mycompany.com/cn/myproduct --> http://mycompany.com/cn/products/myproduct

this expression matches the 1st and 2nd
    ^(cn|com)/myproduct/?
question is - under the action panel , what is the format of the Redirect Url to satisfy both?
something like
Redirect Url: {R:0}/products/myproduct  (this doesnt work..just for illustration)
cheers!
EDIT:
If this helps - here's the rule im having problems with in web.config
            <rule name="myproduct" stopProcessing="true">
                <match url="^(cn|com)/myproduct/?" />
                <conditions logicalGrouping="MatchAny" trackAllCaptures="true">
                </conditions>
                <action type="Redirect" url="{R:1}/products/myproduct" />
            </rule>

A: This should work.
<rules>
   <rule name="myproduct" stopProcessing="true">
     <match url="^([^/]{2,3}/)?myproduct(/$|$)" />
     <action type="Redirect" url="{R:1}products/myproduct" />
  </rule>
</rules>


Q: Using pgfplots, how do I arrange my data matrix for a surface plot so that each cell in the matrix is plotted as a square? I have a matrix of size MxN and I want to make a surface plot directly from above so that each cell in the matrix is drawn as a square. None of the pgfplots shaders really do what I want, since they draw squares between the cells of the matrix (i.e. a 3x3 matrix ends up as 2x2 cells when plotted). The example hopefully makes it clearer:
\documentclass{article}

\usepackage{fullpage}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\pgfplotstableread{
        0 0 0
        0 1 1
        0 2 2

        1 0 3
        1 1 4
        1 2 5

        2 0 6
        2 1 7
        2 2 8
}\data

\begin{document}
\foreach \shader in {interp, flat, flat corner} {
\begin{tikzpicture}
\begin{axis}[
        title={\texttt{\shader}},
        title style={
                at={(0.5, 1.5)},
                anchor=north,
        },
        width=.3\linewidth,
        view={0}{90},
        colormap/hot2,
        colorbar horizontal,
        colorbar style={
                at={(0.5, 1.02)},
                anchor=south,
                xticklabel pos=upper,
        },
]
\addplot3 [surf, shader=\shader] table {\data};
\end{axis}
\end{tikzpicture}
}
\end{document}

How do I arrange my data so that each cell in the matrix is drawn as a separate cell in the output?
EDIT: I realised after entering the question that the answer is very simple, so I'll just answer this myself.

A: Using the matrix plot* feature of PGFPlots v1.13 should exactly do what you want (see section 4.6.12 on page 164 of the manual).
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
    \pgfplotsset{
        compat=1.13,
    }
\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            axis on top,
            xmin=0,
            xmax=2,
            ymin=0,
            ymax=2,
            enlargelimits={abs=0.5},
            point meta=explicit,
            colormap/viridis,
            colorbar,
        ]
            \addplot [
                matrix plot*,
            ] table [meta index=2] {
                0 0 0
                0 1 1
                0 2 2

                1 0 3
                1 1 4
                1 2 5

                2 0 6
                2 1 7
                2 2 8
            };
        \end{axis}
    \end{tikzpicture}
\end{document}

A: Looking at the flat corner plot in the question, it becomes obvious that one solution is to use flat corner and simply add an extra dummy row and an extra dummy column to the table. Their actual values will not influence the plot since flat corner uses only the value from the point which is inside the original matrix.
I am still interested in knowing other solutions, however, as the pgfplots manual specifies that "it is not defined which vertex is used here", making it a somewhat unstable solution to rely on the fact that it appears to use the point that I want.


Q: Range piped to Enum.into throws warning I have a range that I am piping to Enum.into ([]) which throws a warning.  What's wrong here?
iex(1)> 1..5 |> Enum.into ([])
warning: you are piping into a function call without parentheses...

After adding parentheses
iex(2)> (1..5) |> Enum.into ([])
warning: you are piping into a function call without parentheses...

A: The problem is the space around the argument to Enum.into. It's not interpreted as parenthesis for the function call, but rather as a grouping mechanism around one of the arguments. Space is not allowed between function name and arguments.
1..5 |> Enum.into ([]) is the same as 1..5 |> Enum.into(([])) (if we fill the missing parenthesis compiler is complaining about). What you wanted is probably 1..5 |> Enum.into([]), which is a correct call, that the compiler does not complain about.

A: To get rid of the warning, put your parentheses around the whole Enum.into shebang:
(1..5) |> (Enum.into [] )

I'm not 100% sure why Elixir complains here; the warning mentions
 foo 1 |> bar 2 |> baz 3

should be rewritten as
 foo(1) |> bar(2) |> baz(3)

which - to my understanding - is exactly what you did. Probably related to the partial application of Enum.into to [].


Q: Images not loading when deploying streamlit app on GCP I created a streamlit app for data science. The user uploads an image and gets an output with an image displayed, but after deploying the app I'm getting zero rather than an image.
import streamlit as st

@st.cache(allow_output_mutation=True)
def load_image(out):
    if out=='yes':
        im = PIL.Image.open("images/yes.jpg")
        return im

dis = load_image(output)
st.image(dis, channels="RGB)

but after deploying I get:

A: Solved by transforming the image (OpenCV, pillow ...) into bytes
import base64
import cv2
import streamlit as st
retval, buffer = cv2.imencode('.jpg', img )
binf = base64.b64encode(buffer).decode()
st.image("data:image/png;base64,%s"%binf, channels="BGR", use_column_width=True)


Q: Determining a website's 'root' location I need some help with concepts and terminology regarding website 'root' urls and directories.
Is it possible to determine a website's root, or is that an arbitrary idea, and only the actual server's root can be established?
Let's say I'm writing a PHP plugin that that will be used by different websites in different locations, but needs to determine what the website's base directory is.  Using PHP, I will always be able to determine the DOCUMENT_ROOT and SERVER_NAME, that is, the absolute URL and absolute directory path of the server (or virtual server).  But I can't know if the website itself is 'installed' at the root directory or in a sub directory. If the website was in a subdirectory, I would need the user to explicitly set an "sub-path" variable. Correct?

A:
Will $url and $dir always be pointing to the same place?

Yes
<?php
$some_relative_path = "hello";
$server_url = $_SERVER["SERVER_NAME"];
$doc_root = $_SERVER["DOCUMENT_ROOT"];

echo $url = $server_url.'/'. $some_relative_path."
";
echo $dir = $doc_root.'/'. $some_relative_path;

Output:
sandbox.phpcode.eu/hello
/data/sandbox//hello

A: Answer to question 1: Yes you need a variable which explicitly sets the root path of the website. It can be done with an htaccess file at the root of each website containing the following line :
SetEnv APP_ROOT_PATH /path/to/app

http://httpd.apache.org/docs/2.0/mod/mod_env.html
And you can access it anywhere in your php script by using :
<?php $appRootPath = getenv('APP_ROOT_PATH'); ?>

http://php.net/manual/en/function.getenv.php

A: You shouldn't need to ask the user to provide any info.
This snippet will let your code know whether it is running in the root or not:
<?php
        // Load the absolute server path to the directory the script is running in
        $fileDir = dirname(__FILE__);

        // Make sure we end with a slash
        if (substr($fileDir, -1) != '/') {
            $fileDir .= '/';
        }

        // Load the absolute server path to the document root
        $docRoot = $_SERVER['DOCUMENT_ROOT'];

        // Make sure we end with a slash
        if (substr($docRoot, -1) != '/') {
            $docRoot .= '/';
        }

        // Remove docRoot string from fileDir string as subPath string
        $subPath = preg_replace('~' . $docRoot . '~i', '', $fileDir);

        // Add a slash to the beginning of subPath string
        $subPath = '/' . $subPath;

        // Test subPath string to determine if we are in the web root or not
        if ($subPath == '/') {
            // if subPath = single slash, docRoot and fileDir strings were the same
            echo "We are running in the web foot folder of http://" . $_SERVER['SERVER_NAME'];
        } else {
            // Anyting else means the file is running in a subdirectory
            echo "We are running in the '" . $subPath . "' subdirectory of http://" . $_SERVER['SERVER_NAME'];
        }
?>

A: I have just had the same problem. I wanted to reference links and other files from the root directory of my website structure.
I tried the following but it would never work how I wanted it:
$root = $_SERVER['DOCUMENT_ROOT'];
echo "Link";
echo "Link";

But the obvious solution was just to use the following:
echo "Link";
echo "Link";


Q: Updating Status Dialog from Thread in MFC I have a function performing a large amount of work and I want to be able to provide a status dialog in MFC (although I think this question is pertinent to any GUI).
Normally I would just create a thread and then post messages to the main window for updates.  However, in this case the function also needs to work from non-MFC applications, such at MATLAB and Python.  Therefore, I seem to have two choices, neither one I like.
The first option is to include the MFC code in the thread surrounded by #ifdefs.  If figure I will need about five of these, although I could probably combine some of them.
The second option is to define a variable in the main window that the thread updates.  The main window would have to create a timer to check that variable and update the GUI.  This would entirely remove the MFC code from the thread, but is still a kludge.
My question is, which do you think is the lesser of the two evils, surrounding the thread code by #ifdefs, or implementing a timer?  Better still, is there a third option that I haven't thought of?
Thank you.


Q: Calabash. Cómo obtener un elemento de una lista de items de una query, usando sólo la instrucción query Quiero hacer una query para obtener un sólo elemento. Ya sé cómo hacerlo a través del índice si la respuesta de la query es un array de varios elementos:
button = query("webView css:'button'")[position]
touch button

La respuesta de esta query es un array con varios elementos.
Pero estoy usando un patrón descrita en este enlace: https://blinkboxbooks.github.io/2015/01/21/oo-page-models-for-calabash.html
y lo que quiero es obtener el elemento a través sólo de una query específica, para luego poder generar el Element (que puedes ver en el link) y usar sus métodos asociados, como element.exists? o element.set_checked
La query concreta con la que me encuentro este problema es la siguiente:
query("webView css:'name_class'")
[
    [0] {
    "class" => "name_class",
    "nodeType" => "ELEMENT_NODE",
    "id" => "",
    "textContent" => "",
    "rect" => {
        "y" => 856,
        "x" => 44,
        "center_x" => 92,
        "height" => 96,
        "width" => 96,
        "top" => 189,
        "left" => 11,
        "center_y" => 904
    },
    "nodeName" => "DIV",
    "webView" => nil
},
    [1] {
    "class" => "name_class",
    "nodeType" => "ELEMENT_NODE",
    "id" => "",
    "textContent" => "",
    "rect" => {
        "y" => 1040,
        "x" => 164,
        "center_x" => 212,
        "height" => 96,
        "width" => 96,
        "top" => 235,
        "left" => 41,
        "center_y" => 1088
    },
    "nodeName" => "DIV",
    "webView" => nil
}
]

Esta respuesta me la da en los dispositivos iOS. En Android no tengo problema porque me da un campo "index" que puedo usar, pero en iOS no.
Como podéis ver no hay posibilidad de diferenciarlas salvo por el orden en el que aparecen. Si tuviera algún texto concreto o algún identificador podría identificar el elemento unívocamente con una query. En cualquier caso podría hacer el touch de la forma clásica:
checkbox = query("webView css:'name_class'")[1]
touch checkbox

Pero quiero usar la clase Element para hacer algo así:
checkbox = new Element("webView css:'name_class' {index LIKE 1}")
checkbox.touch

La parte de "{index LIKE 1}" me la he inventado, y es lo que necesito averiguar.
Resumiendo, necesito una forma de obtener un elemento situado en un array usando sólamente una query, sin hacer uso del índice del array.
Espero haberme explicado, porque es un tema un poco lioso.
Gracias por adelantado por vuestra ayuda.

A: Para acceder al un elemento concreto de una lista puedes hacerlo de la siguiente forma con query:
query("webView css:'name_class' index:1")

o con la sintaxis de Element que indicas
new Element("webView css:'name_class' index:1")


Q: Jqplot chart with 2 series not displayed correctly I have a jqplot graph that I'm using to display 2 series next to each other. The X-axis is based on a date element and the Y-axis on a percentage value that ranges between -10% en 10%, but that's not really relevant.
Both series have the same number of elements and the x-axis value is identical for each entry of the two series, but the result I'm getting is this.

It seems that some elements in the collection of elements that I'm passing on to the jqplot library have some corrupt data (on the x-axis, so the date value in my case), but I've checked the collection of elements and it is sorted on the date, Not sure why it's not being rendered correctly though.
Has anyone else here had a similar problem?
Thanks


Q: None of the configured nodes are available: [] In elasticsearch, when I try to create a index and type I got this exception.
"None of the configured nodes are available: []"
The following are the code which I use to create "preparIndex".
public class Test {
    static {
        CLIENT = new TransportClient().addTransportAddress(new InetSocketTransportAddress("localhost", 13101));
    }

    public static void main(String arg[]) {
        try {
            IndexResponse response = CLIENT
                                        .prepareIndex("twitter", "tweet", "1")
                                        .setSource(jsonBuilder()
                                            .startObject()
                                            .field("user", "kimchy")
                                            .field("postDate", new Date())
                                            .field("message", "trying out Elasticsearch")
                                            .endObject())
                                        .execute()
                                        .actionGet();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Can any one help me.
Thank you.

A: I had the same issue and finally found the reason, that is I used the default port 9200 (the correct is 9300 as default).


Q: sql get multiple custom post meta values

What I need is a SQL query to go through all the meta_values and look for specific custom meta tags in my case <date1>, <date2> and <date3> and see if they have any value inside the tags and retrieve the post_id and create a array to then create links to those pages (see image above).
So lets say the code goes through the SQL DB and like the image bellow has no values between the dates tags it will ignore it and only retrieve the post_id 710 and create a array of the ids to then create links.

A: SELECT post_id FROM `database_table` WHERE `meta_value` REGEXP '<date[1|2|3]>[0-9]+<\/date[1|2|3]>'

I think this will do the trick =)
Good luck!


Q: Insert grid template row (within grid) under condition In a facebook-esque fasion, I'm working in a post with comments. The comments have a int which indicates the id of the parent post. So Comment 1 and 2 both have assigned as parent Post 1.
What im working on is on displaying them as a grid within a grid. Here is that part in .zul:
<grid id="postGrid" height="550px" model="@load(vm.pcdata.posts)" emptyMessage="No Posts.">
    <template name="model">
        <row>
            <window border="normal">

                <textbox id="infoPost" readonly="true" value="@load(each.info)" multiline="true" rows="4" width="100%" mold="rounded"/>
                <separator bar="true"/>

                <hlayout>

                        <button label="Like" onClick="@command('addPLike', postid=each.postid)"/>

                        <textbox id="likeTB" disabled="true" width="40px" style="text-align:center" value="@load(each.plikes)"/>

                </hlayout>

                <separator bar="false"/>

                <window border="normal">

                    <grid id="commentGrid" height="150px" model="@load(vm.pcdata.comments)" emptyMessage="No Comments.">

                        <template name="model">

                                <row>

                                    <window border="normal">

                                        <textbox id="infoComment" readonly="true" value="@load(each.info)" multiline="true" rows="4" width="100%" mold="rounded"/>
                                        <separator bar="true"/>
                                        <hlayout>

                                                <button label="Like" onClick="@command('addCLike', commentid=each.commentid)"/>

                                                <textbox id="likeTB" disabled="true" width="40px" style="text-align:center" value="@load(each.clikes)"/>

                                        </hlayout></window></row></template></grid></window></window></row></template></grid>

In the second grid, I imagine there could be some sort of if function in which if both the postid in the father Post and the postsrc in the child Comment are the same, the comment will be displayed. Is there any way to make this work?

A: You can use shadow element <if>, e.g.
<if test="@load(vm.yourFlag)">
    <grid id="commentGrid">
    ....
</if>

please see http://books.zkoss.org/zk-mvvm-book/8.0/shadow_elements/flow_control.html

A: Do you mean commentGrid is created but inner window is hidden, so there is space inside commentGrid, right?
Since you specify emptyMessage on commentGrid, it should show no comments. Or there are still comments but all hidden? If so, you can consider hide both commentGrid with inner window.


Q: How to select only 1 record with sql query I have a website like ebay with bids, I want to make a notifications mail for users who got outbidded
For example

*

*user 1 has a bid 11$

*user 2 has a bid 10$

I have a  table for bids:
 id  auction    bidder      bid  bidwhen         quantity  auto_bid
 --  -------   ------  -------  --------------  --------  ----------
 1   150028       2  10.0000  20130719121024         0           0
 2   150028       1  11.0000  20130809122605         0           0
 3   150028       3  12.0000  20130809122605         0           0

and another table where I insert a winners like winner=3 with  =12
 id  auction  seller  winner     bid  closingdate        fee  quantity
--  -------  ------  ------  ------  --------------  ------  ----------
 1   150028  1       3           12  20130809122658       1           1

If in our case id=3 is winner I need notificate id=2 that he is outbid and lost
I start with selecting winner and join bidders table but I can't figure out how to continue.
At the end I need get last ID before Winners ID  in our case bidder 1 cuz he bid last before winner

A: Try the following
SELECT ID
FROM Bids
WHERE auction = 150028
AND Bid < (SELECT MAX(Bid) FROM Bids WHERE auction = 150028)
ORDER By bid DESC
LIMIT 0,1

With this query you select the ID for a specific auction and get only the ID for the second highest bid.
EDIT:
For getting all auctions try the following query:
SELECT DISTINCT (SELECT b1.ID
        FROM Bids b1
        WHERE b1.auction = b2.auction
        AND b1.Bid < (SELECT MAX(Bid) FROM Bids b3 WHERE b3.auction = b1.auction)
        ORDER By b1.bid DESC
        LIMIT 0,1) as ID, b2.auction
FROM Bids b2

A: To get last bidder before the winner
SELECT *
  FROM
(
  SELECT b.auction, MAX(b.bid) bid
    FROM bids b JOIN winners w
      ON b.auction = w.auction
     AND b.bidder <> w.winner
   GROUP BY b.auction
) q JOIN bids b
   ON q.auction = b.auction
  AND q.bid = b.bid

Here is SQLFiddle demo
To get all bidders before the winner
SELECT *
  FROM bids b JOIN winners w
    ON b.auction = w.auction
   AND b.bidder <> w.winner
 -- WHERE b.auction = 150028 -- use if you need to fetch for particular auction
 ORDER BY b.auction, b.bid DESC

Here is SQLFiddle demo


Q: xcode with IBAction I’m trying to make an app in xcode. I have made a class called myApp.m and .h
In my .m I have these lines of code
- (void)loadApp

AlarmItem *item1 = [[[AlarmItem alloc] initWithTitle:@"TEST2"] autorelease];
NSMutableArray *items = [NSMutableArray arrayWithObjects:item1, nil];
RootViewController *rootController = (RootViewController *) [navigationController.viewControllers objectAtIndex:0];
rootController.items = items;

and in my RootViewController I have an this method:
- (IBAction)RefreshMyApp:(id)sender {

    MyApp *myApp2 = [[[MyAppalloc] init] autorelease];
    [myApp2 loadData];
}

What I’m trying to do is calling the method from the myApp class and displayed in the tableView, but I always get an empty cell.
Any help is appreciated.

A: Is this meant to get you your UIApplication singleton? (i'm guessing MyAppalloc is a typo and should be MyApp alloc)
MyApp *myApp2 = [[[MyApp alloc] init] autorelease];

if so then you should be doing it like this:
MyApp *myApp2 = (MyApp*)[UIApplication sharedApplication];

If this is not the case you need to make it clearer what MyApp is (your app delegate?)

A: I guess, your application running in singleton instance, if this is something kind of NSView or a particular control you want to refresh, you could call its particular refresh method like,
[NSTableView reload];
[NSTextField setString];
etc...


Q: Attribute to find out a virtual instance private only or public and private How can we find out a VM has public and private IP or only private IP? Is there any particular attribute in the JSON response for  a virtual guest request?

A: Sure take a look at documentation:
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest
primaryBackendIpAddress
A guest's primary private IP address.
Type: string
primaryIpAddress
The guest's primary public IP address.
Type: string
if you do not see any value for any of those properties that means that the virtual guest does not have it.
Regards


Q: How to dynamically normalize a value based on a match from another column in Tableau Hello I am a new user of stackoverflow, so apologies if I don't follow typical conventions.

sample
Control
Value
Normalized Value (Relative to Control)

a
e
5.5
5.5/5.7

b
e
8.3
8.3/5.7

c
f
6.6
6.6/7.7

d
f
9.9
9.9/7.7

e

5.7

f

7.7

I have an example table (shown above) where I would like Tableau to automatically calculate the last column (Normalized Value) using the data from previous columns.
How do I make the normalization dynamic to the appropriate control value?
In a simpler case, I was able to normalize all the values to a single control, however this is NOT dynamic. Below is how I use LOD to normalize to "e".
[Value]/{fixed:avg(if [sample]='e' then [Value] end )}
But this is not what I want, because sometimes I need to normalize to "e" and other times it is "f".


Q: Is basis vectors orthonormality mandatory for SVD? I have been trying to understand intuitively the Singular Value Decomposition(SVD) and broadly speaking I tend to think of it as of a generalisation of Eigenvalue Decomposition(EVD), i.e., transform a linear map in a simple scaling provided the given changes of basis are done accordingly but this time between spaces with different dimensions, namely, from $\mathbb{R}^n$ to $\mathbb{R}^m$.
Mathematically speaking, for a $n \times m$ matrix $\mathbf A$  we want to find the $v_i$'s and $u_i$'s such that:
$$A v_i=\sigma_i u_i$$
where:
$$v_i \in \{v_1, v_2, ..., v_n\}$$
$$u_i \in \{u_1, u_2, ..., u_m\}$$
However, I still do not get it why $\{v_1, v_2, ..., v_n\}$ and $\{u_1, u_2, ..., u_m\}$ must be orthonormal bases, as is assumed by all the resources I have found, which jump right into finding these orthonormal bases by calculating the eigenvectors of $\mathbf A^\top \mathbf A$.
With that said, are orthonormal bases a mandatory requirement for SVD, if so, what would go wrong if you just pick two linearly independent bases not necessarily orthonormal?

A: This is a great question. Nothing will go wrong if insist on working with arbitrary (not necessarily orthonormal) bases, it just won't lead to an SVD decomposition but to a different, more trivial but still sometimes useful, decomposition.
Let's assume we start with an $n \times m$ real matrix $A$ and think about it as (defining a) linear map $T_A \colon \mathbb{R}^m \rightarrow \mathbb{R}^n$ given by $T_A(v) = Av$. You can ask two different questions:

*

*How can we pick a basis $\alpha = (v_1, \dots, v_m)$ for $\mathbb{R}^m$ and a basis $\beta = (u_1, \dots, u_n)$ for $\mathbb{R}^n$ so that, with respect to those bases, the map $T_A$ will be represented by the simplest possible matrix? It turns out that the answer to this question is quite simple. If the rank of the matrix $A$ is $k$, you can pick $\alpha$ and $\beta$ so that $Av_i = w_i$ for $1 \leq i \leq k$ and $Av_i = 0$ for $k < i \leq m$. With respect to those bases, the map $T_A$ will be represented by a rectangular diagonal matrix with $k$ ones on the diagonal and all other entries zeros. In this case, there are no "singular values" - only ones and zeroes.
How do you do it in practice? You can always perform a finite number of row and column operations on $A$ until it becomes a rectangular diagonal matrix with $k$ ones on the diagonal and all other entries are zero. Since performing row/column operations corresponds to multiplying the matrix $A$ on the left/right by elementary matrices, this gives you a decomposition of the form $P^{-1}AQ = D$ where $P,Q$ are invertible matrices and $D$ is the "diagonal" matrix. Multiplying by $P$, you get the equation $AQ = PD$. The columns of $Q$ will form the basis $\alpha$ while the columns of $P$ will form the basis $\beta$. Multiplying by $Q^{-1}$, you get the decomposition $A = PDQ^{-1}$ which is similar to the SVD decomposition, only here the matrices $P$ and $Q$ are not necessary orthogonal because we didn't insist on orthonormal bases and the entries on the diagonal of $D$ are only $1$'s and $0$'s.
Finally, it is instructive to think about the case where $n = m$ and the matrix $A$ has full rank. Then, we can pick any basis $\alpha = (v_1, \dots, v_n)$ for $\mathbb{R}^n$ and take the basis $\beta = (w_1, \dots, w_n)$ to be $w_i := Av_i$ and then trivially $Av_i = w_i$. If we take the basis $\alpha$ to be the standard basis, we get the "trivial" decomposition $A = A \cdot I \cdot A^{-1}$.

*How can we pick an orthonormal basis $\alpha = (v_1, \dots, v_m)$ for $\mathbb{R}^m$ and an orthonormal basis $\beta = (w_1, \dots, w_n)$ for $\mathbb{R}^n$ so that, with respect to those bases, the map $T_A$ will be represented by the simplest possible matrix? This is a different question which is answered by the SVD decomposition. It turns out that you can always find bases $\alpha,\beta$ so that $Av_i = \sigma_i w_i$ and if the rank of the matrix is $k$ you can arrange that $\sigma_i = 0$ for $k < i \leq m$ and that $\sigma_i > 0$ for $1 \leq i \leq k$ but now you can't make all the $\sigma_i$'s to be ones! Those will be the singular values of $A$ and they provide interesting geometric information about the linear map $T_A$. For example, the map $T_A$ will map an $m$-dimensional cube of volume one to a $k$-dimensional parallelotope of ($k$-dimensional) volume $\sigma_1 \dots \sigma_k$. If you stack the vectors $v_i$ as columns of a matrix $Q$ and the vectors $w_i$ as columns of a matrix $P$, you get the decomposition $A= P \Sigma Q^{-1} = P \Sigma Q^T$ where now, $P$ and $Q$ are orthogonal matrices and not just invertible matrices and $\Sigma$ is a rectangular diagonal matrix with non-zero entries $\sigma_1, \dots, \sigma_k$ on the diagonal.
Finally, let us think about the case where $n = m$ and the matrix $A$ has full rank. We can try and take $\alpha = (v_1,\dots,v_n)$ to be the standard basis $v_i = e_i$ which is orthonormal. Then $(Ae_1, \dots, Ae_n)$ will be a basis, but it won't necessarily be an orthogonal one so we can't just take $w_i = Av_i$.

A: There is no reason why they have to be orthonormal basis other than that this is the way the SVD is defined! If you drop the requirement of having orthonormal basis vectors in $U,V$ of the decomposition $A = U\Sigma V^t$ we can use pretty much any decomposition you like, as long as $\Sigma$ is diagonal.
What is very important though are the properties we gain by using this. For instance we can immediately find the rank of a matrix $A$ just by counting the nonzero singular values $\sigma_i$. And on that subject it is also very convenient for constructing low rank approximations as well as finding pseudo inverses and solving least squares problems, and the list could go on for quite a while. It is probably one of the most used matrix decompositions and it is not difficult to find examples.


Q: Determine which class called an IntentService I am working on a news app. I have 5 categories of news sections. Each tab or section, calls to a different URL and has a separate table in the local database, hence a different URI(using a ContentProvider), when retrieving local data.
I have one AsyncTask that services all the requests. It determines which url or uri to call based on the instance of the class passed to it. All the tabs/sections/fragments/classes inherit from a common base class..
Now, I will like to change the AsyncTask to an IntentService, so I can use the AlarmManager class. I have noticed that, there seems to be no easy way of passing an object via intents.
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken.
This class is called when the instance of the class is to be determined:
public class GetURL {
public static URL GetURL(TabsSuperClass tabs)
{
    URL url = null;
    try {
        if(tabs instanceof CultureFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "culture|local|music|books|society")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(TabsSuperClass.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());

        }
        else if(tabs instanceof LifeStyleFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "lifeandstyle|education|fashion|help")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(LifeStyleFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
        else if(tabs instanceof ScienceFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "science|environment|technology|business")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(ScienceFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
        else if(tabs instanceof SportFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "sport|football")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(SportFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
        else if(tabs instanceof WorldFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "world|opinion|media|us-news|australia-news|uk-news")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(WorldFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }

    return url;
}

public static Uri GetContentUri(TabsSuperClass tabs)
{
    Uri uri = null;

    if(tabs instanceof CultureFrag)
    {
        return NewsContract.CONTENT_URI_CULTURE;
    }
    else if(tabs instanceof LifeStyleFrag)
    {
        return NewsContract.CONTENT_URI_LIFESTYLE;
    }
    else if(tabs instanceof ScienceFrag)
    {
        return NewsContract.CONTENT_URI_SCIENCE;
    }
    else if(tabs instanceof SportFrag)
    {
        return NewsContract.CONTENT_URI_SPORT;
    }
    else if(tabs instanceof WorldFrag)
    {
        return NewsContract.CONTENT_URI_WORLD;
    }

    return uri;
}

}
urlConnection = (HttpURLConnection)GetURL.GetURL(_fragment).openConnection();

An instance where this class is called is here, when I am inserting data into the table of the class which called
private void InsertIntoTable(List<NewsFacade> data) {
    for (NewsFacade facade :
            data) {
        ContentValues values = new ContentValues();
        values.put(NewsContract.DataContract.COLUMN_NAME_DATE, facade.getDate());
        values.put(NewsContract.DataContract.COLUMN_NAME_CONTENT, facade.getText());
        values.put(NewsContract.DataContract.COLUMN_NAME_TAG, facade.getTag());
        byte[] image = EncodeImage(facade.getThumb());
        values.put(NewsContract.DataContract.COLUMN_NAME_THUMB, image);
        values.put(NewsContract.DataContract.COLUMN_NAME_TITLE, facade.getTitle());
        values.put(NewsContract.DataContract.COLUMN_NAME_WEBADDRESS, facade.getWebAddress());
        _fragment.mResolver.insert(GetURL.GetContentUri(_fragment), values);
    }
}

A:
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken.

Put an extra on the Intent that you pass to startActivity() that indicates what the IntentService should do. You get a copy of that Intent in onHandleIntent() in the IntentService, so you can retrieve the extra and take appropriate steps based upon its value.

A: At the top of the activity I add:-
private final static String THIS_ACTIVITY = "AddProductToShopActivity";

for the intent I add:
intent.putExtra("CALLER", THIS_ACTIVITY);

In the started activity :-
final String caller = getIntent().getStringExtra("Caller");


Q: How can you get the version number of your Room Database? I have some code that I would only like to run when I know for certain that the Room migrations I have have completed.  Is there a way to find out which version number my Room instance is on?  I have the latest code:
@Database(entities = [AnalyticsEvent::class, ListenItem::class, LastPositionHeard::class,
DownloadItem::class], version = 3) //I would like to retrieve this information
@TypeConverters(RoomTypeConverters::class)
abstract class MyRoomDatabase : RoomDatabase() {

  abstract fun analyticsEventsDao(): AnalyticsEventsDao

  abstract fun listeningStatsDao(): ListeningStatsDao

  abstract fun lastPositionHeardDao(): LastPositionHeardDao

  abstract fun downloadsDao(): DownloadsDao

  companion object {
    // Singleton prevents multiple instances of database opening at the
    // same time.
    @Volatile
    private var INSTANCE: MyRoomDatabase? = null

    val MIGRATION_1_TO_2 = Migration1To2()
    val MIGRATION_2_TO_3 = Migration2To3()
    const val LUMINARY_DATABASE_NAME = "room_database"

    fun getDatabase(context: Context): MyRoomDatabase {
      val tempInstance = INSTANCE
      if (tempInstance != null) {
        return tempInstance
      }
      synchronized(this) {
        val instance = Room.databaseBuilder(
          context.applicationContext,
          LuminaryRoomDatabase::class.java,
          LUMINARY_DATABASE_NAME
        ).addMigrations(MIGRATION_1_TO_2, MIGRATION_2_TO_3)
        .build()
    INSTANCE = instance
    return instance
   }
  }
 }
}

But what I would like to do is something like this:
val instanceVersionNumber = MyRoomDatabase.getDatabase().versionNumber

Is it possible?

A: Here's an extension function in Kotlin to grab the version number.  The key is to call openHelper from your Room database which returns a SupportSQLiteOpenHelper object where you can then get to the actual DB attributes.
fun Context.getDBVersion() = RoomDatabase.getDatabase(this)?.openHelper?.readableDatabase?.version.toString()


Q: Twitter+OAuth Crash on iPhone OS 2.x I'm using Ben Gottlieb's Twitter+OAuth code.
Works great on my 3.1.2 iPhone, but crashes on my 2.2.1 iPhone. I'm getting a EXC_BAD_ACCESS error in the EstimateBas64EncodedDataSize call. Here's what I'm seeing in the debugger:
#0  0x2fe1e724 in __dyld_pthread_getspecific
#1  0x2fe1eddc in __dyld___gthread_getspecific
#2  0x2fe1eec8 in __dyld__Unwind_SjLj_Register
#3  0x2fe07b14 in __dyld__ZN4dyld14bindLazySymbolEPK11mach_headerPm
#4  0x2fe15ebc in __dyld_stub_binding_helper_interface
#5  0x0003cab8 in EstimateBas64EncodedDataSize at Base64Transcoder.c:106
#6  0x0003cb04 in Base64EncodeData at Base64Transcoder.c:120
#7  0x0003e476 in -[OAHMAC_SHA1SignatureProvider signClearText:withSecret:] at OAHMAC_SHA1SignatureProvider.m:50

What am I missing? A library that's not available with 2.2.1?

A: Looks like the OAuth library is being built against 3.0 frameworks. If you want to target 2.2.1, it'll need to be built against those frameworks.


Q: Displaying decoded video stream with MTKView results in undesirable blurry output I've managed to create an app that receives a live h264 encoded video stream and then decodes and displays the video with Video Toolbox and AVSampleBufferDisplayLayer. This works as expected but I want to be able to apply filters to the rendered output so I changed to decoding with Video Toolbox and displaying/rendering the decoded video with MetalKit. The only problem I have is that my rendered output with MetalKit is noticeably more blurry than the output received with AVSampleBufferDisplayLayer and I haven't managed to find out why.
Here's the output from AVSampleBufferDisplayLayer
Here's the output from MetalKit
I've tried skipping MetalKit and rendering directly to a CAMetalLayer but the same issue persists. I'm in the middle of trying to convert my CVImageBufferRef to an UIImage that I can display with UIView's. If this also ends up blurry then maybe the issue is with my VTDecompressionSession and not with the Metal side of things.
The decoding part is pretty much like what's given here How to use VideoToolbox to decompress H.264 video stream
I'll try to just paste the interesting snippets of my code.
These are the options I give my VTDecompressionSession.
NSDictionary *destinationImageBufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                      [NSNumber numberWithInteger:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange],
                                                      (id)kCVPixelBufferPixelFormatTypeKey,
                                                      nil];

This is my view that inherits from MTKView
@interface StreamView : MTKView

@property id<MTLCommandQueue> commandQueue;
@property id<MTLBuffer> vertexBuffer;
@property id<MTLBuffer> colorConversionBuffer;
@property id<MTLRenderPipelineState> pipeline;
@property CVMetalTextureCacheRef textureCache;

@property CFMutableArrayRef imageBuffers;

-(id)initWithRect:(CGRect)rect withDelay:(int)delayInFrames;
-(void)addToRenderQueue:(CVPixelBufferRef)image renderAt:(int)frame;

@end

This is how I initialize the view from my view controller. The video I receive is of the same size, that is 666x374.
streamView = [[StreamView alloc] initWithRect:CGRectMake(0, 0, 666, 374) withDelay:0];
[self.view addSubview:streamView];

This is the content of the StreamView's initWithRect method
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
self = [super initWithFrame:rect device:device];

self.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
self.commandQueue = [self.device newCommandQueue];
[self buildTextureCache];
[self buildPipeline];
[self buildVertexBuffers];

This is the buildPipeline method
- (void)buildPipeline
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    id<MTLLibrary> library = [self.device newDefaultLibraryWithBundle:bundle error:NULL];

    id<MTLFunction> vertexFunc = [library newFunctionWithName:@"vertex_main"];
    id<MTLFunction> fragmentFunc = [library newFunctionWithName:@"fragment_main"];

    MTLRenderPipelineDescriptor *pipelineDescriptor = [MTLRenderPipelineDescriptor new];
    pipelineDescriptor.vertexFunction = vertexFunc;
    pipelineDescriptor.fragmentFunction = fragmentFunc;
    pipelineDescriptor.colorAttachments[0].pixelFormat = self.colorPixelFormat;

    self.pipeline = [self.device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:NULL];
}

Here is how I actually draw my texture
CVImageBufferRef image = (CVImageBufferRef)CFArrayGetValueAtIndex(_imageBuffers, 0);

id<MTLTexture> textureY = [self getTexture:image pixelFormat:MTLPixelFormatR8Unorm planeIndex:0];
id<MTLTexture> textureCbCr = [self getTexture:image pixelFormat:MTLPixelFormatRG8Unorm planeIndex:1];
if(textureY == NULL || textureCbCr == NULL)
   return;

id<CAMetalDrawable> drawable = self.currentDrawable;

id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor;
renderPass.colorAttachments[0].clearColor = MTLClearColorMake(0.5, 1, 0.5, 1);

id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass];
[commandEncoder setRenderPipelineState:self.pipeline];
[commandEncoder setVertexBuffer:self.vertexBuffer offset:0 atIndex:0];
[commandEncoder setFragmentTexture:textureY atIndex:0];
[commandEncoder setFragmentTexture:textureCbCr atIndex:1];
[commandEncoder setFragmentBuffer:_colorConversionBuffer offset:0 atIndex:0];
[commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 instanceCount:1];
[commandEncoder endEncoding];

[commandBuffer presentDrawable:drawable];
[commandBuffer commit];

This is how I convert a CVPixelBufferRef into an MTLTexture
- (id<MTLTexture>)getTexture:(CVPixelBufferRef)image pixelFormat:(MTLPixelFormat)pixelFormat planeIndex:(int)planeIndex {
    id<MTLTexture> texture;
    size_t width, height;

    if (planeIndex == -1)
    {
        width = CVPixelBufferGetWidth(image);
        height = CVPixelBufferGetHeight(image);
        planeIndex = 0;
    }
    else
    {
        width = CVPixelBufferGetWidthOfPlane(image, planeIndex);
        height = CVPixelBufferGetHeightOfPlane(image, planeIndex);
        NSLog(@"texture %d, %ld, %ld", planeIndex, width, height);
    }

    CVMetalTextureRef textureRef = NULL;
    CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, _textureCache, image, NULL, pixelFormat, width, height, planeIndex, &textureRef);
    if(status == kCVReturnSuccess)
    {
        texture = CVMetalTextureGetTexture(textureRef);
        CFRelease(textureRef);
    }
    else
    {
        NSLog(@"CVMetalTextureCacheCreateTextureFromImage failed with return stats %d", status);
        return NULL;
    }

    return texture;
}

This is my fragment shader
fragment float4 fragment_main(Varyings in [[ stage_in ]],
                              texture2d<float, access::sample> textureY [[ texture(0) ]],
                              texture2d<float, access::sample> textureCbCr [[ texture(1) ]],
                              constant ColorConversion &colorConversion [[ buffer(0) ]])
{
    constexpr sampler s(address::clamp_to_edge, filter::linear);
    float3 ycbcr = float3(textureY.sample(s, in.texcoord).r, textureCbCr.sample(s, in.texcoord).rg);

    float3 rgb = colorConversion.matrix * (ycbcr + colorConversion.offset);

    return float4(rgb, 1.0);
}

Because the view and the video I encode are both 666x374 I tried changing the sampling type in the fragment shader to filter::nearest. I thought it would match the pixels 1:1 but it was still as blurry. Another weird thing I noticed is that if you open the uploaded images in a new tab you'll see that they are way larger than 666x374... I doubt that I'm making a mistake on the encoding side and even if I did then AVSampleBufferDisplayLayer still manages to display the video without blur so they must be doing something right that I'm missing.

A: It looks like you have the most serious issue of view scale addressed, the other issues are proper YCbCr rendering (which it sounds like you are going to avoid by outputting BGRA pixels when decoding) and then there is scaling the original movie to match the dimensions of the view. When you request BGRA pixel data the data is encoded as sRGB, so you should treat the data in the texture as sRGB. Metal will automatically do the non-linear to linear conversion for you when reading from a sRGB texture, but you have to tell Metal that it is sRGB pixel data (using MTLPixelFormatBGRA8Unorm_sRGB). To implement scaling, you just need to render from the BGRA data into the view with linear resampling. See the SO question I linked above if you want to have a look at the source code for MetalBT709Decoder which is my own project that implements proper rendering of BT.709.


Q: Is it possible to specify user specific pre commands in VS Code? We have a slew of folks doing development through the same GitLab repo. We are using VS Code tasks to execute internal commands. The main command is the same for everyone: internal_command on Windows and internalCommand on Linux.
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label" : "do it",
            "type" : "shell",
            "windows": {
                "command": "internal_command"
            },
            "linux": {
                "command": "internalCommand"
            }
        }
    ]
}

This works as expected.
Some users need/want to run a specific command before the main command. For example, one use wants to rename a file, another user wants to change an environment variable, etc...
We don't want to have multiple versions of .vscode/tasks.json cause that is a mess when pushing things to GitLab.
So I am wondering if there is a way to specify user specific tasks in the project's .vscode/tasks.json file?

A: You can with the help of the extension Command Variable it allows you to use the content of a file as a command in the terminal. The file can also contain Key-Value pairs or be a JSON file.
Say you store this userTask.txt or userTask.json file in the .vscode folder and add the file to the .gitignore file.
With the current version of the extension the file userTask.txt has to exist, I will add an option to supply alternative text in case the file does not exist. You can fill the file with a dummy command like echo No User Task
Set up your task.json like
{
  "version": "2.0.0",
  "tasks": [
    {
      "label" : "do it",
      "type" : "shell",
      "windows": {
        "command": "internal_command"
      },
      "linux": {
        "command": "internalCommand"
      },
      "dependsOrder": "sequence",
      "dependsOn": ["userTask"]
    },
    {
      "label" : "userTask",
      "type" : "shell",
      "command": "${input:getUserTask}"
    }
  ],
  "inputs": [
    {
      "id": "getUserTask",
      "type": "command",
      "command": "extension.commandvariable.file.content",
      "args": {
        "fileName": "${workspaceFolder}/.vscode/userTask.txt"
      }
    }
  ]
}


Q: How to redirect to another page after 2 clicks? I have a question about javascript. That is:
When I click first click anywhere in the website, this code will be executed

When I click secondary click anywhere in the website, I will be redirect to another page.
How to do that ?
Thank you very much ! Sorry for my poor English and programmer !

A: Put this in your page:

Sorry, I am unable to create a fiddle for this, as jsfiddle prevents iframe page redirects out of its domain.


Q: como eliminar texto de un archivo html con java estoy tratando de eliminar una parte del texto de un archivo html (el archivo es una pagina descaragda.
 Necesito indicarle el punto donde comience a borrar y de ahi hasta el final. hay alguna forma de indicarle en que palabra comenzar o la ubicacion segun el numero de byte o linea? que se utilizaria?
Gracias, saludos

A: Puedes usar un java.io.RandomAccessFile.
Con esta clase puedes leer del archivo y también escribir para modificarlo o extenderlo.
Con el método setLength(long len) puedes truncar el archivo al tamaño que quieras borrando el resto o también puedes extenderlo.
Te pongo un ejemplo pero no es para que lo uses sino para que veas como funciona y leas más de la clase.
https://docs.oracle.com/javase/8/docs/api/
truncaArchivoDespuesDe("<body>");

public void truncaArchivoDespuesDe(String etiqueta) throws IOException {
    RandomAccessFile raf = new RandomAccessFile("ArchivoDescargado.html","rw");
    String linea = raf.readLine();
    while (linea != null) {
       if (linea.equals(etiqueta)) {
           raf.setLength(raf.getFilePointer()); //aqui truncamos el archivo a su
                  // nuevo tamaño que será el de la posición
                  // actual (en el siguiente renglón de la etiqueta encontrada)
           return;
       }
       linea = raf.readLine();
    }
}


Q: VB .NET 2008 datagridview object reference not set to an instance of an object Receiving System.NullReferenceException with my code:
Private Sub dsplay()
        ds.Clear()
        dgv_tran.DataSource = ds
        da = New OleDbDataAdapter("SELECT p.prod_id, p.prod_name, b.cost_ave " & _
                                   "FROM tbl_products p " & _
                                   "INNER JOIN tbl_balance b " & _
                                   "ON p.ID = b.p_id", con)
        da.Fill(dt)
        dgv_tran.DataSource = ds
        dgv_tran.DataMember = "table1"
call dgv_tran_CellClick(Nothing,Nothing)
end sub

Private Sub dgv_tran_CellClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgv_tran.CellClick
        Try
            Dim i As Integer = dgv_tran.CurrentRow.Index 'error starts in this line
            txtid.Text = dgv_tran.Item(0, i).Value
            txtname.Text = dgv_tran.Item(1, i).Value
            txtcost.Text = dgv_tran.Item(2, i).Value
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

My datagridview displays the data that I need, I can proceed with the project just fine when I remove the MessageBox.Show(ex.ToString) but I can't just ignore this error can I?
Already spent 4hours trying to figure this one out. Any help pointing out the problem would be much appreciated.


Q: Could the neo4j-bolt-python driver work on remote windows? I ran the Quick Example on https://github.com/neo4j/neo4j-python-driver with two environment.
 1. local linux => works well
 2. remote windows => seems like run well, however does not create graph.db.
What' wrong with me?
My Debug Log on remote windows :
2018-03-09 12:40:56,212  ~~ [CONNECT] ('192.168.1.90', 7687)
2018-03-09 12:40:56,213  ~~ [SECURE] 192.168.1.90
2018-03-09 12:40:56,221  C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:40:56,224  S: [HANDSHAKE] 1
2018-03-09 12:40:56,227  C: INIT ('neo4j-python/1.5.3', {...})
2018-03-09 12:40:56,228  S: SUCCESS ({'server': 'Neo4j/3.3.2'})
2018-03-09 12:40:56,229  ~~ [CLOSE]
2018-03-09 12:40:56,231  C: RUN ('BEGIN', {})
2018-03-09 12:40:56,232  C: PULL_ALL ()
2018-03-09 12:40:56,234  C: RUN ('MERGE (a:Person {name: $name}) MERGE (a)-[:KNOWS]->(friend:Person {name: $friend_name})', {'name': 'Arthur', 'friend_name': 'Guinevere'})
2018-03-09 12:40:56,234  C: PULL_ALL ()
2018-03-09 12:40:56,237  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,238  S: SUCCESS ({})
2018-03-09 12:40:56,239  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,240  S: SUCCESS ({'stats': {'labels-added': 2, 'relationships-created': 1, 'nodes-created': 2, 'properties-set': 2}, 'result_consumed_after': 0, 'type': 'w'})
2018-03-09 12:40:56,241  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,241  C: PULL_ALL ()
2018-03-09 12:40:56,245  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,245  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx829'})
2018-03-09 12:40:56,246  C: RUN ('BEGIN', {'bookmark': 'neo4j:bookmark:v1:tx829', 'bookmarks': ['neo4j:bookmark:v1:tx829']})
2018-03-09 12:40:56,247  C: PULL_ALL ()
2018-03-09 12:40:56,247  C: RUN ('', {'name': 'Arthur', 'friend_name': 'Lancelot'})
2018-03-09 12:40:56,248  C: PULL_ALL ()
2018-03-09 12:40:56,250  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,251  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx829'})
2018-03-09 12:40:56,251  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,252  S: SUCCESS ({'stats': {'labels-added': 1, 'relationships-created': 1, 'nodes-created': 1, 'properties-set': 1}, 'result_consumed_after': 0, 'type': 'w'})
2018-03-09 12:40:56,253  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,253  C: PULL_ALL ()
2018-03-09 12:40:56,256  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,256  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx830'})
2018-03-09 12:40:56,257  C: RUN ('BEGIN', {'bookmark': 'neo4j:bookmark:v1:tx830', 'bookmarks': ['neo4j:bookmark:v1:tx830']})
2018-03-09 12:40:56,258  C: PULL_ALL ()
2018-03-09 12:40:56,259  C: RUN ('', {'name': 'Arthur', 'friend_name': 'Merlin'})
2018-03-09 12:40:56,259  C: PULL_ALL ()
2018-03-09 12:40:56,262  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,263  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx830'})
2018-03-09 12:40:56,264  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,265  S: SUCCESS ({'stats': {'labels-added': 1, 'relationships-created': 1, 'nodes-created': 1, 'properties-set': 1}, 'result_consumed_after': 0, 'type': 'w'})
2018-03-09 12:40:56,265  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,266  C: PULL_ALL ()
2018-03-09 12:40:56,269  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,269  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx831'})
2018-03-09 12:40:56,270  C: RUN ('BEGIN', {'bookmark': 'neo4j:bookmark:v1:tx831', 'bookmarks': ['neo4j:bookmark:v1:tx831']})
2018-03-09 12:40:56,271  C: PULL_ALL ()
2018-03-09 12:40:56,271  C: RUN ('MATCH (a:Person)-[:KNOWS]->(friend) WHERE a.name = $name RETURN friend.name ORDER BY friend.name', {'name': 'Arthur'})
2018-03-09 12:40:56,273  C: PULL_ALL ()
2018-03-09 12:40:56,275  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,276  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx831'})
2018-03-09 12:40:56,277  S: SUCCESS ({'result_available_after': 1, 'fields': ['friend.name']})
2018-03-09 12:40:56,277  S: RECORD * 3
2018-03-09 12:40:56,278  S: SUCCESS ({'result_consumed_after': 0, 'type': 'r'})
Guinevere
Lancelot
Merlin
2018-03-09 12:40:56,279  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,279  C: PULL_ALL ()
2018-03-09 12:40:56,281  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,282  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx831'})

A: If I change to driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password")) from driver = GraphDatabase.driver("bolt://192.168.1.90:7687", auth=("neo4j", "password")), then it works well.  Who can explain WHY?
Debug Log changed TO
2018-03-09 12:55:47,944  ~~ [CONNECT] ('::1', 7687, 0, 0)
2018-03-09 12:55:47,945  ~~ [SECURE] ::1
2018-03-09 12:55:47,951  C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:55:47,953  S: [HANDSHAKE] 1

FROM
2018-03-09 12:40:56,212  ~~ [CONNECT] ('192.168.1.90', 7687)
2018-03-09 12:40:56,213  ~~ [SECURE] 192.168.1.90
018-03-09 12:40:56,221  C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:40:56,224  S: [HANDSHAKE] 1


Q: Best way to display pdf embedded in browser (chrome, IE11/Edge, Safari) I am trying to display a pdf which is created by the GET call of a RESTful service. In the HTML I am using a object tag as below
<object data={{$ctrl.miEstimatePdfData}} type="application/pdf"
    width="100%" height="100%" alt="pdf" class="view-pdf_document">

Estimate Preview Cannot be displayed.

</object>

In the js file
miEstimateService.getMitchellEstimate(response.estimate.id)
    .then(function (response) {
    var blob = new Blob([(response.data)], { type: 'application/pdf' });
    if (window.navigator.msSaveOrOpenBlob) {
        $window.navigator.msSaveOrOpenBlob(blob, "estimatePreview.pdf");
    } else {
        var fileUrl = URL.createObjectURL(blob);
        $scope.miEstimatePdfData = $sce.trustAsResourceUrl(fileUrl);
    }
});

This works flawlessly in chrome
Since IE11/ Edge does not allow displaying of the blob URL, I am using the .msSaveOrOpenBlob, but this does not open the pdf inside the browser window. It promts the user to save or open the pdf and opens it in Acrobat Reader (IE11) or in a new browser window (Edge).
In Safari, the PDF is rendered correctly in the browser but is not free flowing or scrollable, so most of the second page is not visible.
I have researched a lot and looked at a lot of the SO questions. Is there some solution which works for all the browsers - chrome, IE11/Edge and Safari?
Thanks,
SDD


Q: Xcode 7: UINavigationController's child view controller does not resize to fit parent's bounds I have a UIViewController subclass that I am pushing on to a navigation controller stack within a larger UISplitViewController. However, when I build with Xcode 7, I am finding the that the UIViewController subclass is not resizing to fit the bounds of its parent navigation controller. This was not an issue when building with previous SDKs.
When I inspect the view of the child view controller, I am getting the standard 600x600 size.
The child view controller is entirely defined in code; I am not using IB for its layout or anything like that. What gives?


Q: Variable name depending on a value I would like to create as many vecs according to a variable in a for loop. Is there an easy way?
In the example below, I would like to get 2 different Vec, the first called vec_0 and the second vec_1. Any ideas on how to do it or how can I overcome this situation in another way?
 for i in 0..2 {
        let vec_i = Vec::<i32>::with_capacity(100);
    }

A: Vecs can contain Vecs too:
let mut vecs: Vec<Vec<i32>> = vec![];  // or Vec::with_capacity(2)

for _ in 0..2 {
    vecs.push(Vec::with_capacity(100));
}


Q: fetch logs for an application in RStudio Connect? Is there a way to pulls the jobs from the logs in RStudio Connect? I know that we can go to the application, click on each job under the logs and look for info but is there a way I can pull all the logs as an API or anything? I am trying to pull the logs, tweak them and display in another app for some users.
TIA


Q: Jquery menu close after click on link I'm using http://www.hongkiat.com/blog/responsive-web-nav/ this tutorial exactly for my site menu, but the only problem is I am making a one page website. I want the mobile menu to close after I click on 'about' for example. so that it will scroll to the bottom.
I hope you can help me.
This is my cod:

k

How-to

Icons

Design

Web 2.0

Tools

                Menu

And this is the javascript:

A: The selecor is wrong
if you have
var pull        = $('#pull');

Wouldn't it be
    pull.on('click', function(e) {...

or just
$('#pull').on(...)

A: Try this. It'll execute the slideToggle function when a nav item is clicked.
menu.find('a').click(function(){
    menu.slideToggle();
});

A: If you want slideUp the Menu when you click outside of it you can use the method
stopPropagation();

http://jsfiddle.net/Joseph82/jwNEZ/


Q: How to match two tables and insert it into another table in laravel 5.4? I need to match two tables and insert it into the disbursment table, so this is my code...
    public function store(Request $request)
{
    //Approved Request
    $approvedRequest= DB::table('request')
    ->where('users_MemId',Auth::user()->MemId)
    ->where('requestStatus','Approved')
    ->join('requestdetails','request.requestId','=','requestdetails.request_requestId')
    ->join('itemattribute','requestdetails.RequestDetailsId','=','itemattribute.RequestDetailsId')
    ->join('exudeinventory', 'itemattribute.AttrName', '=', 'exudeinventory.ItemName')
    ->select('itemattribute.AttrName', 'exudeinventory.InventoryId', 'request.requestId')
    ->get();
    // dd($approvedRequest);

store function.

I've tried matching the tables and I can't figure out on how to insert the values in another table or if I am doing it right.

I've been looking for solutions but still I can't figure it out, Hope that someone would help me and explain it to me, I am new to laravel T,T

A: Maybe you can do this:
        public function store(Request $request)
        {
            //Approved Request
            $approvedRequest= DB::table('request')
            ->where('users_MemId',Auth::user()->MemId)
            ->where('requestStatus','Approved')
            ->join('requestdetails','request.requestId','=','requestdetails.request_requestId')
            ->join('itemattribute','requestdetails.RequestDetailsId','=','itemattribute.RequestDetailsId')
            ->join('exudeinventory', 'itemattribute.AttrName', '=', 'exudeinventory.ItemName')
            ->select('itemattribute.AttrName', 'exudeinventory.InventoryId', 'request.requestId')
            ->get()
            ->each (function ($request, $key) {
                $dis = new Disbursment;
                $dis->DisbursmentId = rand(1, 999999);
                $dis->ItemImage = 'default.jpg';
                $dis->ItemTypeId = $request->AttrName;
                $dis->exudeinventory_InventoryId = $request->InventoryId;
                $dis->request_requestId = $request->requestId;
                $dis->save();
            });
        }


Q: What does "But I don’t think I will. Now." mean in this paragraph? “Now. I’m an artisan,” he said. “Like a cat who makes – tables. I don’t like the word artist. Maybe I never did. I sure the fuck don’t know what it means. I’m a cat who works from his balls, with his hand. I know what it’s about now. I think I really do. Even if I go under. But I don’t think I will. Now.”
It's from James Baldwin's "If Beale Street Could Talk"
At the end of the paragraph, the character is saying "But I don’t think I will. Now." I didn't quite understand what he wouldn't do. Is it art that he wouldn't do? Or the character is just talking nonsense at that moment?

A: “Now. I’m an artisan,” he said. “Like a cat who makes – tables. I don’t like the word artist. Maybe I never did. I sure the fuck don’t know what it means. I’m a cat who works from his balls, with his hand. I know what it’s about now. I think I really do. Even if I go under. But I don’t think I will. Now.”
The last main verb is: go under, which means to fail at something.
The auxiliary "will" goes with that verb: I don't think I will [go under or fail].
This is a good example of how auxiliary verbs are used in conversation. You don't need to repeat the main verb and can have an entire conversation with auxiliaries.
Here is my own example:
John: I really wanted to go ski-diving but the ski-diving school was closed.
Mary: You did? Why would you? It's scary and dangerous.
John: Yes, that's true. But even so, I would. That's what makes it exciting.
Mary: It does? Wow. Well, some people love danger.
John: They do, they really do. People like me. For sure.
Mary: Well, I never have and never will.
There are two main verbs in that paragraph and the auxiliaries go with them. [I think I pointed them out correctly. :)]


Q: How to draw a line according to screen weight in HTML How can I draw the line showing in the picture below?

my current page looks like this:

I want to add that line at the top with the same title
(just to mention I'm using bootstrap 5)

Business

Calculator

OOG Permits

Services

Career

A: You can use flexbox. Then, you have to play with the borders. Here is an example

    <meta charset="utf-8" />
    <title>Example App</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />

FAST NAVIGATOR

Your content here

A:

fieldset {
  padding: 0;
  height: 8px;
  border-bottom: none;
}
<fieldset>
  <legend align="center">Title</legend>
</fieldset>


Q: Get index of regex match in pandas dataframe not working I have an excel worksheet that I am reading into pandas for parsing and later analysis. It has the following format. All values are strings. They will be converted to floats/ints later but having them as strings helps with parsing.
column1  |  column2 | column3 |
-----------------------------
12345   |10         |20       |
txt     |25         |65       |
35615   |15         |20       |
txt     |35         |20       |

I need to get the index of all 5 digit, numerical values in column1. It will always be a 5 digit. I am using the following regex.
\b\d{5}\b

I am having problems getting pandas to properly match the 5 digits when using any of the built in string methods.
I have tried the following.
df.column1.str.contains('\b\d{5}\b', regex=True).index.list()
df.column1.str.match('\b\d{5}\b').index.list()

I am expecting it to return
[0,2]

Both of these return an empty list. What am I doing wrong?

A: Add r before string, filter by boolean indexing and get index values to list:
i = df[df.column1.str.contains(r'\b\d{5}\b')].index.tolist()
print (i)
[0, 2]

Or if want parse only numeric values with length 5 change regex with ^ and $ for start and end of string:
i = df[df.column1.str.contains(r'^\d{5}$')].index.tolist()


Q: Get values of XML nodes with foreach I am working on a programm with C# and a XML-File. I want to read the values of the xml-nodes but I get an issue with that. In the second part, where I am trying to get the content, it only does one loop and not three. The first values are correct. I don't know why it only makes the first loop. I hope someone can help me.
My XML-File:
<?xml version="1.0" encoding="utf-8"?>
<lagerverwaltung>
  <article>
    <inventory id="1">
    </inventory>
    <orders>
      <order id="1">
        <id>1</id>
        <idposition>1</idposition>
        <content>
          <idarticle amount="4">2</idarticle>
          <idarticle amount="3">3</idarticle>
          <idarticle amount="2">1</idarticle>
        </content>
        <idcustomer>2</idcustomer>
        <orderdate>05.01.2018 15:10:44</orderdate>
        <paydate>05.02.2018</paydate>
        <mwst>7.7</mwst>
        <total>1781.358</total>
      </order>
    </orders>
  </article>
</lagerverwaltung>

My C#-Code:
List<Order> orderList = new List<Order>();
XmlDocument xml = new XmlDocument();
xml.Load(xmlFilePath);
XmlNodeList xnList = xml.SelectNodes("/lagerverwaltung/article/orders/order");
foreach (XmlNode xn in xnList)
{
    // Is working
    string id = xn["id"].InnerText;
    string bestellPositionId = xn["idposition"].InnerText;
    string kundeId = xn["idcustomer"].InnerText;
    string bestelldatum = xn["orderdate"].InnerText;
    string rechnungsDatum = xn["paydate"].InnerText;
    string mwst = xn["mwst"].InnerText;
    string rechnungsTotal = xn["total"].InnerText;

    XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[@id='" + id + "']/content");
    Dictionary<string, string> content= new Dictionary<string, string>();
    foreach (XmlNode xmlNode in xnInhalt) // Does only one loop
    {
        string articleid = xmlNode["idarticle"].InnerText;
        string amount = xmlNode["idarticle"].GetAttribute("amount");
        content.Add(articleid, amount);
    }
}

A: There is a single content node, use content/idarticle to get the inner collection:
XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[@id='" + id
+ "']/content/idarticle");

You would then modify the following code because xmlNode now refers to an idarticle. For example,
string articleid = xmlNode.InnerText;


Q: The correct way to OAuth from a desktop client without a server I am working on an extension which must connect with Facebook to download some user data. I am somewhat new to the details of the OAuth dance, and have not been able to implement this with a desired level of security. In the current setup (which works) I am concerned about evildoers hijacking my application's name and using it to post spam.
I have tried many different techniques to implement OAuth (Login With Facebook in particular) in my extension. The current setup uses Facebook's Manual Login flow.

*

*Open OAuth popup window in sandboxed tab.

*Set redirect_url to special, internal facebook page which does not require configured redirect URLs, set the auth_token parameter to return an auth_token, not temp code.

*Inject javascript into the special redirect page which posts a message to the extension with the auth_token.

This works as expected. I am able to retrieve user auth_tokens after they give my app permission via popup.
I am concerned about security since the extension does not have a server to store a secret key, nor does it have a valid domain to limit redirect_urls and verify the authenticity of authorization requests. Due to this flow: a hacker could simply download the source to my extension, steal the Facebook App ID, generate popup windows for my app from their own websites, and obtain auth_tokens which can post on behalf "via" my application.
Even more concerning, the official Google Chrome gudie to OAuth in Extensions recommends embedding your consumer_secret in the extension. This seems counter-intuitive.
I am reasonably confident this can be solved in two ways:

*

*Creating my own server which acts as a proxy between my extension and Facebook. I could set the redirect_url to my custom domain, store the consumer_secret on my server, and define a narrow API between the client and my own server.

*Restrict the authorization redirect to my Chrome Extension ID (sort of like how Facebook iOS SDK uses App store bundle identifiers). Unfortunately, I can not associate my Facebook app with a Chrome extension ID. It says "invalid URL."

I would prefer the 2nd option, as running a server can be costly and introduces another point of failure for the extension. Users also have to deal with "black box" code holding their auth_tokens, which sucks.
Interestingly, it looks like Facebook makes special exception for ms-app:// URLs (Windows 8 applications). Why not chrome-extension:// urls?
So my question: -- Is this possible? Am I missing something? Secondly: Am I being paranoid about this type of hijacking attack? It seems fairly benign, but I would rather not allow hackers to hijack my app's oauth dialog.
Thank You

A: Your intuition is correct. According to facebook's developer doc's:

Never include your App Secret in client-side or decompilable code.

The reason for this is exactly what you said, even in compiled, obfuscated byte code, it is fairly trivial using modern methods to reverse engineer the app secret, even if you are using https.
The best practice in this situation would be to have a hosted api that would be used to proxy all logins through an external source, and to hide your app id and app secret in a separate config file.


Q: Elasticsearch aggregation group by using elastic4s I want to query total sum of sales grouped by product name in Elasticsearch
How do I do that using elastic4s?
client.execute {
      search ("sales"/ "sales_type")
        .query {rangeQuery("date") gte "01-01-2018"   lte "31-12-2018" }
          .aggs { termsAgg("s1","product_name")}
             .aggs  (sumAgg("sums","total_sum"))
}

currently my code just sums up all in given date range, not grouping by product name

A: You've probably found an answer by now anyway, but here's my 2p worth for anyone else who comes across this.... you probably want to use a sub-aggregation on product_name rather than a second aggregation on the whole dataset.
Something like this (untested code, but based on a working part of one of my projects):
.query {rangeQuery("date") gte "01-01-2018"   lte "31-12-2018" }
  .aggs { termsAgg("s1","product_name").subAggregations(
             sumAgg("sums","total_sum")
          )
        }

The results come back as a bunch of nested Map[String,Any] which take a bit of sorting through, but some logging/print statements and a bit of trial and error sorted it out for me.
Reference is here: https://github.com/guardian/archivehunter/blob/47372d55d458cfe31e5d9809910cc5d9a4bbb9bf/app/controllers/SearchController.scala#L203, in that case I am processing it down for rendering in a browser frontend with ChartJS.
Apologies for brevity, but I'm on the hop at the moment and haven't got long to post :)


Q: Match NSDictionary Key Value Pairs I have the following NSDictionary with the following data structure:
Food Count (values) - Food Name (key)

I sort that NSDictionary's food count like so:
    NSArray *sortedFood = [[detailDictionary allValues] sortedArrayUsingComparator:^(id obj1, id obj2) {
    if ([obj1 intValue] < [obj2 intValue])
        return (NSComparisonResult)NSOrderedDescending;
    if ([obj1 intValue] > [obj2 intValue])
        return (NSComparisonResult)NSOrderedAscending;
    return (NSComparisonResult)NSOrderedSame;
}];

It has sorted it the following way
100
98
50
30
etc.

I am trying to use that new sortedFood array to then only show the top 5 value, key pairs for the food.
For example, if Apple's is the name of the food that has the value of 100, it would appear first.
So far I have the loop, but nothing else.
for (int i = 0; i <= 5; i++) {
}

Not sure what else to do. I think this is more difficult because the whole dictionary isn't sorted in the same way as the new array, but I could be wrong.

A: I think you should try
-[keysSortedByValueUsingSelector:] in NSDictionary, it is sorted by value and get the key results.


Q: I want to lock a part of a async method in python basically it should be a(name based lock) where name is passed as argument to the method In the below code the test() function waits for the request from UI as the request is received in  JSON form it creates a task for every request by calling handle() fucntion
async def test():
     loop = asyncio.get_running_loop()
     req = await receiver.recv_string()
     logger.debug(f"Request received {req}")
     req_json = json.loads(req)
     logger.debug("Await create_task")
     loop.create_task(handle(req_json))

async def handle(req_json_):
     req_name = req_json_.get(req_name)
    # acquire lock here based on req_name if request comes with different name acquire the lock
    # but if the request comes with same name block the request
    # untill the req for that name is completed if the request is already completed then acquire
    # the lock  with that name
     logger.info(f"Request finished with req name {req_name} for action patch stack")

How can achieve this with asyncio  module or any other way in python

A: It seems to me that all you need to do is maintain a dictionary of locks whose keys are the names given by variable req_name and whose values are the corresponding locks. If the key reg_name is not already in the dictionary, then a new lock for that key will be added:
import asyncio
from collections import defaultdict

# dictionary of locks
locks = defaultdict(asyncio.Lock)

async def handle(req_json_):
    req_name = req_json_.get(req_name)
    # acquire lock here based on req_name if request comes with different name acquire the lock
    # but if the request comes with same name block the request
    # untill the req for that name is completed if the request is already completed then acquire
    # the lock  with that name
    # Get lock from locks dictionary with name req_name. If it
    # does not exit, then create a new lock and store it with key
    # req_name and return it:
    lock = locks[req_name]
    async with lock:
        # do whatever needs to be done:
        ...
    logger.info(f"Request finished with req name {req_name} for action patch stack")

Update
If you need to timeout the attempt to acquire a lock, then create a coroutine that acquires the passed lock argument in conjunctions with a call to asyncio.wait_for with a suitable timeout argument:
import asyncio
from collections import defaultdict

async def acquire_lock(lock):
    await lock.acquire()

# dictionary of locks
locks = defaultdict(asyncio.Lock)

async def handle(req_json_):
    req_name = req_json_.get(req_name)
    lock = locks[req_name]
    # Try to acquire the lock but timeout after 1 second:
    try:
        await asyncio.wait_for(acquire_lock(lock), timeout=1.0)
    except asyncio.TimeoutError:
        # Here if the lockout could not be acquired:
        ...
    else:
        # Do whatever needs to be done
        # The lock must now be explicitly released:
        try:
            ...
            logger.info(f"Request finished with req name {req_name} for action patch stack")
        finally:
            lock.release()


Q: EmguCV detect keypoints from 3D Model Is there a way i can retrieve the observed keypoints from a 3D model instead from an image. This is since i need to track an uneven object (simple spaceship right now: http://i.msdn.microsoft.com/dynimg/IC129855.jpg) that can be visible from any side. Currently the system works somewhat fine when using an image but like i said i need it be able to identify the model if being viewed from any side. Currently using an implementation of the SURF tutorial found over here:
http://www.emgu.com/wiki/index.php/SURF_feature_detector_in_CSharp
Moreover is there a way to specify the detail of the keypoints or the number?


Q: Positioning 2 QDialog forms relative to one each other I have created 2 QDialogs forms, D1 and D2. How is it possible to make D1 and D2 have a constant distance from each other (If I move D1, D2 also moves and vise versa)?

A: I think it'll end up being a bit tedious but one thing you might try is to have both dialogs parented by a minimalist container using a window mask.  So something like...
class minimalist_container: public QWidget {
  using super = QWidget;
public:
  explicit minimalist_container (QWidget *parent = nullptr)
    : super(parent)
    {}
protected:
  virtual void resizeEvent (QResizeEvent *event) override
    {

      /*
       * Start with an empty mask.
       */
      QRegion mask;

      /*
       * Now loop though the children and add a region to
       * the mask for each child based on its geometry.
       */
      for (const auto *obj: children()) {
        if (const auto *child = dynamic_cast<const QWidget *>(obj)) {
          mask += child->geometry();
        }
      }
      setMask(mask);
      super::resizeEvent(event);
    }
};

Then you can add a layout and children to this in the usual way but the parent itself should be essentially invisible...
minimalist_container minimalist_container;
auto *minimalist_container_layout = new QHBoxLayout;
minimalist_container_layout->addWidget(new QColorDialog);
minimalist_container_layout->addStretch(1);
minimalist_container_layout->addWidget(new QFontDialog);
minimalist_container.setLayout(minimalist_container_layout);
minimalist_container.show();

The code above links all children within the masked parent widget so that they appear visually distinct but move together when the parent is moved.
There are a few niggles however.  The title bar of the parent is, by default, the only one visible whereas what I think you really want is for the parent title bar to be the only one that isn't visible.  It can certainly be hidden by setting the window flags and/or configuring your window manager but you'll probably then have to write code to handle the usual move, resize functions etc.
So, as I say... tedious, but it could certainly work.

A: You can install an event filter to monitor the moving/resizing of the source window and propagate changes to the target window. On OS X, you also need to monitor the non-client area button press, since the window move events are not sent while the window is moving, but only after it has stopped for a short time.
I leave the propagation in opposite direction as an exercise to the reader :)
// https://github.com/KubaO/stackoverflown/tree/master/questions/win-move-track-42019943
#include <QtWidgets>

class WindowOffset : public QObject {
   Q_OBJECT
   QPoint m_offset, m_ref;
   QPointer<QWidget> m_src, m_dst;
   void adjust(QEvent * event, const QPoint & delta = QPoint{}) {
      qDebug() << "ADJUST" << delta << event;
      m_dst->move(m_src->geometry().topRight() + m_offset + delta);
   }
protected:
   bool eventFilter(QObject *watched, QEvent *event) override {
#ifdef Q_OS_OSX
      if (watched == m_src.data()) {
         if (event->type() == QEvent::NonClientAreaMouseButtonPress) {
            m_ref = QCursor::pos();
            qDebug() << "ACQ" << m_ref << event;
         }
         else if (event->type() == QEvent::NonClientAreaMouseMove &&
                  static_cast<QMouseEvent*>(event)->buttons() == Qt::LeftButton) {
            auto delta = QCursor::pos() - m_ref;
            adjust(event, delta);
         }
      }
#endif
      if ((watched == m_src.data() &&
                (event->type() == QEvent::Move || event->type() == QEvent::Resize)) ||
               (watched == m_dst.data() && event->type() == QEvent::Show)) {
         if (event->type() == QEvent::Move)
            m_ref = QCursor::pos();
         adjust(event);
      }
      return false;
   }
public:
   WindowOffset(const QPoint & offset, QObject * parent = nullptr) :
      QObject{parent},
      m_offset{offset}
   {}
   WindowOffset(QWidget * src, QWidget * dst, const QPoint & offset, QObject * parent = nullptr) :
      WindowOffset{offset, parent}
   {
      src->installEventFilter(this);
      dst->installEventFilter(this);
      m_src = src;
      m_dst = dst;
   }
};

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QLabel d1{"Source"}, d2{"Target"};
   WindowOffset offset{&d1, &d2, {200, 50}};
   for (auto d : {&d1, &d2}) {
      d->setMinimumSize(300,100);
      d->show();
   }
   return app.exec();
}

#include "main.moc"


Q: Contact form 7 dropdown not working All of a sudden my drop down lists in Contact Form 7 are not working and cannot for the life of me figure it out. there are two spots where this happens as you can see in the form.
I have already looked into the code but no idea
http://www.aimbookingagency.com/offer-form/
its not listing them all and the box is SUPER tall. I am not a form expert by ANY means so I appreciate the help!

A: I did not find the problem but I re created the problem sections "SELECT dropdown menus" and it seemed to format fine. So I deleted the bad versions.
not sure if this will help anyone in the future.


Q: Code delimiter in Visual Studio I've forgot the reserved word before the # (or is it after?) for delimiter code snippets as I'd like.
You know the ones with the + for expanding the code and - for closing the code snippet. The ones the comes automatically in a class a method etc'...

A: You are looking for #region
#region foo

public static foo()
{
}

#endregion foo

However, using regions is frowned upon.

A: the name comes after the #
 #region MyClass definition
 public class MyClass
 {
 ....
 }
 #endregion

Reference: https://msdn.microsoft.com/en-us/library/9a1ybwek.aspx


Q: Read list of large .asc type files in python .memory related issue I have a folder with 50 large .asc type files each with size ~2.5Gb. These contains data from CAN signals ,how to read these files using python.I tried using numpy genfromtxt for reading files but having issues related to memory .What is the efficient way to read all the .asc files in folder into python for analysis purpose.
Thanks
Akshay

A: You would feed the data into chunks with a for loop.
Cory Schafer's video demonstrates this in his video:
https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=607s


Q: Adding suffix to labels on x-axis I need to plot some values referred to time, with specific labels.
You can think of my data like the sample below:
ID     Time     Clock
260    21 hours 20:30 # this should be referred to yesterday
127    21 hours 20:30
7      5 hours  12:30
10     6 hours  11:30
8      6 hours  11:30
... ... ...
62  NaN NaN
82  NaN NaN

Time refers to time ago looking at the current one (approx UK 17:40), while Clock should be the 'watch time', i.e., the current one (approx. 17:40) minus the number of hours given by the Time column.
In Time the sorting should be from the highest to the lowest, similarly to Clock.
The column types are both objects.
In a plot, should I have the ID on the vertical axis and Clock on the x-axis.
This means on the x-axis should I have clock time, looking at Clock column. For example, 48:00 would mean 48 hours ago.
I would like to have, instead of 20:30 or 48:00, the following labels, for example: 20 hours ago, 48 hours ago.
import matplotlib.pyplot as plt

plt.scatter(df['Clock'], df['ID'])
plt.show()

However, I need some help to add a suffix (i.e., hours ago) or replace time's labels on x-axis.

A: Currently you are passing the values from the Clock column to be plotted on the x-axis and since these are strings, matplotlib interprets them as a categorical variable. If you are okay with this, then each of the x-ticks will be spaced equally apart regardless of their value (but we can sort the DataFrame before passing it), and then to get the desired tick labels you can take the portion of the string before the colon symbol (for example '20' from the string '20:30') and add the string ' hours ago' to that string to get '20 hours ago'. Then pass each of these strings as labels to the plt.xticks method, along with the original ticks in the Clock column.
import matplotlib.pyplot as plt
import pandas as pd

## recreate the data with times unsorted
df = pd.DataFrame({
    'ID':[260,127,7,10,8],
    'Time':['21 hours','21 hours','5 hours','6 hours','6 hours'],
    'Clock':['20:30','20:30','12:30','11:30','11:30',]
    })

df_sorted = df.sort_values(by='Clock',ascending=False)
plt.scatter(df_sorted['Clock'], df_sorted['ID'])

## avoid plotting duplicate clock ticks over itself
df_clock_ticks = df_sorted.drop_duplicates(subset='Clock')

## take the number of hours before the colon, and then add hours ago
plt.xticks(ticks=df_clock_ticks['Clock'], labels=df_clock_ticks['Clock'].str.split('\:').str[0] + ' hours ago')
plt.show()


Q: Using md-progress-linear inside md-dialog I am trying to use md-progress-linear inside an md-dialog. The code for my progress bar is like below.

    <md-progress-linear md-mode="determinate" value="{{testCounter}}"></md-progress-linear>

      Loading application libraries...

Normally its working fine, but when i use it inside a md-dialog its not working.
plunker link
In the above link the code i used is available, the liner bar in the home page is working fine. But when i click on open the modal is getting open, but the liner bar is not appearing.

A: Reason that your visual didn't recognized right.
Main div in dialog.html doesn't have sizes.
Put in md-dialog:
 style="width: 100px; height: 100px;"

You will see that else works correctly.