text:
Q: How to save and restore the content of a ListModel? I am able to save settings for list items which is statically created using Component.onComponent method. But Settings for statically created list items take affect after reopening app. I would like to save settings for dynamically created list model. I am unable to save Settings for a dynamically created list item. The code below does that a list item is on and off while clicking Show/Hide action. When I reopen the app, created list item disappears. How to save list item using Setting?
import QtQuick 2.9
import Fluid.Controls 1.0
import Qt.labs.settings 1.0
import QtQuick.Controls 1.4
ApplicationWindow {
    id:root
    visible: true
    width: 640
    height: 480
    property variant addlist
    property int countt2: 0
    Settings{
        id:mysetting4
        property alias ekranCosinus: root.countt2
    }
    function listonoff(){
        if(countt2%2==1){
            return true
          }
        else if(countt2%2==0){
            return false
        }
    }
    Connections {
        target: addlist

        onTriggered:   listonoff()

    }
    addlist: favourite2
    /* main.qml */
    menuBar: MenuBar {
            Menu {
                title: "&Edit"
                MenuItem { action: favourite2 }
            }
    }
    Action {
        id:favourite2
         text: qsTr("Show/Hide")
         onTriggered: {
            countt2++
            console.log(countt2)
               if(listonoff()===true){
                   return list_model.insert(list_model.index,{ title: "First item."} )
                }
                else if(listonoff()===false){
                   return list_model.remove(list_model.index)
                }
           }
        }
        ListView {
            id:contactlist
            width: parent.width
            height: parent.height
            focus: true
            interactive: true
            clip: true
            model: ListModel {
                id:list_model
            }
            delegate: ListItem {
                text: model.title
                height:60
            }
        }
        MouseArea {
            id: mouse
            anchors.fill: parent
        }
    }

A: Quite curious that you expect that saving a single integer value will somehow be able to store the content of an arbitrary data model... It doesn't work even for the static model data, it is only "restored" because it is static - it is part of the code, you are not really saving and restoring anything.
If you want to store all that data, you will have to serialize it when your app quits, and deserialize it when the app starts.
You could still use Settings, but to store a string value, that will represent the serialized data.
The easiest way to do it is to transfer the model items back and forth with a JS array, this way the JS JSON object functionality can be used to easily serialize and deserialize the data:
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Window 2.3
import Qt.labs.settings 1.0

ApplicationWindow {
  id: main
  width: 640
  height: 480
  visible: true

  property string datastore: ""

  Component.onCompleted: {
    if (datastore) {
      dataModel.clear()
      var datamodel = JSON.parse(datastore)
      for (var i = 0; i < datamodel.length; ++i) dataModel.append(datamodel[i])
    }
  }

  onClosing: {
    var datamodel = []
    for (var i = 0; i < dataModel.count; ++i) datamodel.push(dataModel.get(i))
    datastore = JSON.stringify(datamodel)
  }

  Settings {
    property alias datastore: main.datastore
  }

  ListView {
    id: view
    anchors.fill: parent
    model: ListModel {
      id: dataModel
      ListElement { name: "test1"; value: 1 }
    }
    delegate: Text {
      text: name + " " + value
    }
  }

  MouseArea {
    anchors.fill: parent
    acceptedButtons: Qt.LeftButton | Qt.RightButton
    onClicked: {
      if (mouse.button === Qt.LeftButton) {
        var num = Math.round(Math.random() * 10)
        dataModel.append({ "name": "test" + num, "value": num })
      } else if (dataModel.count) {
        dataModel.remove(0, 1)
      }
    }
  }
}

The application begins with a single data model value, more data items can be added or removed by pressing the left and right mouse button respectively.
As long as the application is closed properly, the data model will be copied into an array, which will be serialized to a string, which will be stored by the Settings element. So upon relaunching the app, if the data string is present, the model is cleared to remove the initial value so it is not duplicated, the data string is deserialized back into an array, which is iterated to restore the content of the data model. Easy peasy.
Of course, you could also use the LocalStorage API as well, or even write a simple file reader and writer by exposing a C++ object to QML. All this approach needs is to be able to store and retrieve a single string.


text:
Q: Extending store class in Mobx Flutter What is the correct way to extend a store class in Mobx in flutter? Wherever I try to put 'extends' i get a compilation error.

class Booking = _Booking with _$Booking;

abstract class _Booking with Store {}

class FlightBooking  = _FlightBooking with _$FlightBooking ;

abstract class _FlightBooking with Store {}

A: You can achieve that by making _FlightBooking extend Booking:
class FlightBooking  = _FlightBooking with _$FlightBooking ;

abstract class _FlightBooking extends Booking with Store {}

A: Store of mobx is a mixin, not a class. Mixins cannot be used to extend. You might want to look more into the documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: after I press home button ScheduledExecutorService does not run in the background I have created this in onCreate() and after I press home button ; ScheduledExecutorService does not run every 10 mins in the background.Why ?
Where is the mistake.
Please help me out .
Thanks in Advance.
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleWithFixedDelay(new Runnable(){

            public void run() {
//play music to check if it executes every 10 mins

                  mp3.start();
            }

    }, 0, 600, TimeUnit.SECONDS);

A: I think that AlarmManager is more well suited to repeating a task every 10 minutes than Executor is.
I would suggest setting up an AlarmManager and using a BroadCast receiver to "catch" the trigger that it fires, and inside your onReceive() method you can do whatever you like, including start your mp3. I think this way will work better for you, especially if you are intending for you sound to play even if your application is not currently the Active app on the device.


text:
Q: Azure Search - Highlights - Locating in image Just looking for guidance or even a general outline on approach here.
I am using azure search to OCR a batch of pdfs.  I have turned on hit highlighting and I am successfully getting results back there that I am looping through / displaying in my view for the end user.  I was looking on expanding that functionality to show the pdf images with the highlighting on the images themselves like in the JFK azure example.  I am not proficient in react and seem to be getting lost there.
I am assuming I need to save off the OCR images to a data store for reference using the normalized_images that are created?  I do have pdfs locally I can load but assume the OCR images maybe different.  Have turned on GeneratedNormalizedImagesPerPage and turned on cache which creates files in my storage account.
Then I assume I need to pull the associated image, display it, use the highlight results and pull a corresponding bounding box where the phrase was detected?  Problem with that approach is that I do not see any association between the highlight hit and the location (bounding box) of the hit nor the associated image file the hit was on.
Probably way off on approach here but any guidance is appreciated.
Edit 1
I did noticed the items on this page in the JFK example:  https://github.com/microsoft/AzureSearch_JFK_Files/tree/master/JfkWebApiSkills/JfkWebApiSkills
Would trying to replicate the ImageStore (so those are stored in my storage account) and then the HocrGenerator (appears to handle points in a doc) into my skillset for my index be the approach?

A: There are a few steps here:

*

*you need to save the layoutText from the OCR skill somewhere the UI can access it. The JFK Files demo converts it to a HOCR (to display in the UI) and saves it in index as a field in the index so that it is retrieved in the search results.  HOCR isn't necessary and you may find it more efficient to store the layout in blobs using a knowlege store object projection.

*save the extracted images into blob storage using a file projection into the knowledge store. Keep in mind that the images may be resized in the process and the coordinates will match the resized image saved to the store.  If you want to map the coordinates to the original image see this.

*At search time, map the highlight to the the metadata. You will find this code in the nodejs frontend, however it may be simpler to follow in the original demo by following the code here.  Essentially you just find the first occurrence of the highlighted word in the metadata, display the associated image, and calculate the bounding region of the word.


text:
Q: Conexión a db remota PSQL desde python Intento hacer una conexión con psycopg2 a mi db en LAN corriendo en windows10, pero genera un error que no logro resolver, lei la documentación y me habla del ssl.cert
psycopg2.connect(database="access_control", user="postgres", password="password", host="192.168.0.3", port="5432", sslmode='require')

Tutos en Linux varios, pero en windows poco, en localhost me funciona sin problema.


text:
Q: How to dynamically change a web page's title? I have a webpage that implements a set of tabs each showing different content. The tab clicks do not refresh the page but hide/unhide contents at the client side.
Now there is a requirement to change the page title according to the tab selected on the page ( for SEO reasons ). Is this possible? Can someone suggest a solution to dynamically alter the page title via javascript without reloading the page?

A: Update: as per the comments and reference on SearchEngineLand
 most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

You can just do something like, document.title = "This is the new
  page title.";, but that would totally defeat the purpose of SEO. Most
  crawlers aren't going to support javascript in the first place, so
  they will take whatever is in the  element as the page title.
If you want this to be compatible with most of the important crawlers,
  you're going to need to actually change the title tag itself, which
  would involve reloading the page (PHP, or the like). You're not going
  to be able to get around that, if you want to change the page title in
  a way that a crawler can see.

A: Use document.title.
See this page for a rudimentary tutorial as well.

A: The code is
document.title = 'test'

A: I can't see how changing the page title via Javascript will help SEO. Most (or all) search bots do not run Javascript and will only read the initially loaded title that is the mark-up.
If you want to help SEO, then you will need to change the page title in the back-end and serve different versions of the page.

A: You'll have to re-serve the page with a new title in order for any crawlers to notice the change.  Doing it via javascript will only benefit a human reader, crawlers are not going to execute that code.

A: Maybe you can load on your title all the tabs titles in one string, and then once you load one of the tabs change the title via javascript
ex: at first set your title to
my app | description | contact | about us |

once you load one of the tabs run:
document.title = "my app | tab title";

A: for those looking of the npm version of it, there is an entire library for this:
npm install --save react-document-meta

import React from 'react';
import DocumentMeta from 'react-document-meta';

class Example extends React.Component {
  render() {
    const meta = {
      title: 'Some Meta Title',
      description: 'I am a description, and I can create multiple tags',
      canonical: 'http://example.com/path/to/page',
      meta: {
        charset: 'utf-8',
        name: {
          keywords: 'react,meta,document,html,tags'
        }
      }
    };

    return (

        <DocumentMeta {...meta} />

Hello World!

    );
  }
}

React.render(<Example />, document.getElementById('root'));

A: Use document.title. It will be useful for most things, but it will destroy SEO on your website.
Example:

document.write("title - " + document.title + "
");
document.title = "New title here!";
// Notice: this will defeat purpose of SEO. Not useful for SEO-friendly sites.
document.write("title - " + document.title + "
");
body {
  font-family: Consolas, 'Courier New', monospace;
}
<!DOCTYPE html>

  <title>Old title</title>

    Lorem ipsum dolor sit amet, at movet detraxit mediocritatem eam, nam iusto abhorreant ne. Ei pro          debet adolescens voluptaria, eu minim scaevola conceptam vel. Vim ea torquatos constituto                complectitur, usu eu civibus insolens eleifend. Ex ubique quaerendum his.

A: There are many ways you can change the title, the main two, are like so:
The Questionable Method
Put a title tag in the HTML (e.g. <title>Hello</title>), then in javascript:
let title_el = document.querySelector("title");

if(title_el)
    title_el.innerHTML = "World";

The Obviously Correct Method
The simplest of all is to actually use the method provided by the Document Object Model (DOM)
document.title = "Hello World";

The former method is generally what you would do to alter tags found in the body of the document. Using this method to modify meta-data tags like those found in the head (like title) is questionable practice at best, is not idiomatic, not very good style to begin with, and might not even be portable. One thing you can be sure of, though, is that it will annoy other developers if they see title.innerHTML = ... in code they are maintaining.
What you want to go with is the latter method. This property is provided in the DOM Specification specifically for the purpose of, as the name suggests, changing the title.
Note also that if you are working with XUL, you may want to check that the document has loaded before attempting to set or get the title, as otherwise you are invoking undefined behavior (here be dragons), which is a scary concept in its own right. This may or may not happen via JavaScript, as the docs on the DOM do not necessarily pertain to JavaScript. But XUL is a whole 'nother beast, so I digress.
Speaking of .innerHTML
Some good advice to keep in mind would be that using .innerHTML is generally sloppy. Use appendChild instead.
Although two cases where I still find .innerHTML to be useful include inserting plain text into a small element...
label.innerHTML = "Hello World";
// as opposed to...
label.appendChild(document.createTextNode("Hello World"));
// example:
el.appendChild(function(){
    let el = document.createElement("span");
    el.className = "label";
    el.innerHTML = label_text;
    return el;
}());

...and clearing out a container...
container.innerHTML = "";
// as opposed to... umm... okay, I guess I'm rolling my own
[...container.childNodes].forEach(function(child){
    container.removeChild(child);
});

A: I want to say hello from the future :) Things that happened recently:

*

*Google now runs javascript that is on your website1

*People now use things like React.js, Ember and Angular to run complex javascript tasks on the page and it's still getting indexed by Google1

*you can use html5 history api (pushState, react-router, ember, angular) that allows you to do things like have separate urls for each tab you want to open and Google will index that1
So to answer your question you can safely change title and other meta tags from javascript (you can also add something like https://prerender.io if you want to support non-Google search engines), just make them accessible as separate urls (otherwise how Google would know that those are different pages to show in search results?). Changing SEO related tags (after user has changed page by clicking on something) is simple:
if (document.title != newTitle) {
    document.title = newTitle;
}
$('meta[name="description"]').attr("content", newDescription);

Just make sure that css and javascript is not blocked in robots.txt, you can use Fetch as Google service in Google Webmaster Tools.
1: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157

A: One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:
http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.
You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.

A: Since search engines ignore most javascript, you will need to make it so that search engines can crawl using the tabs without using Ajax.  Make each tab a link with an href that loads the entire page with that tab selected.  Then the page can have that title in the  tag.
The onclick event handler can still load the pages via ajax for human viewers.
To see the pages as most search engines see them, turn off Javascript in your browser, and try to make it so that clicking the tabs will load the page with that tab selected and the correct title.
If you are loading via ajax and you want to dynamically change the page title with just Javascript, then do:
document.title = 'Put the new title here';

However, search engines will not see this change made in javascript.

A: You can use JavaScript. Some bots, including Google, will execute the JavaScript for the benefit of SEO (showing the correct title in the SERP).
document.title = "Google will run this JS and show the title in the search results!";

However, this is more complex since you are showing and hiding tabs without refreshing the page or changing the URL. Maybe adding an anchor will help as stated by others. I may need to retract my answer.
Articles showing positive results:
http://www.aukseo.co.uk/use-javascript-to-generate-seo-friendly-title-tags-1275/
http://www.ifinity.com.au/2012/10/04/Changing_a_Page_Title_with_Javascript_to_update_a_Google_SERP_Entry
Don't always assume a bot won't execute JavaScript.
http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157
Google and other search engines know that the best results to index are the results that the actual end user will see in their browser, including JavaScript.

A: Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

A: Modern crawlers are able to parse dynamically-generated content in the DOM, so using document.title = ... is perfectly fine.

A: But in order to get the SEO befits
You need to do a page reload when the page changes so that the search engine's see the different titles etc.
So make sure the page reload works first then add document.title changes

A: I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.
Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.

A: Google mentioned that all js files rendered but in real, I've lost my title and another meta tags which had been provided by Reactjs on this website and actually lost my position on Google! I've searched a lot but it seems that all pages must have pre-rendered or using SSR(Server Side Rendering) to have their SEO-friendly protocole!
It expands to Reactjs, Angularjs , etc.
For short, Every page that has view page source on browser is indexed by all robots, if it's not probably Google can index but others skip indexing!

A: I use a seperate header and include it using php, in the header i use:
<?php
if (!isset($title)){
    $title = "Your Title";
  }
  else {
    $title = $title;
  }
 ?>

<title><?php echo $title; ?></title>

Then in each page I use:
<?php
  $title = "Your Title - Page";
  include( "./header.php" );
?>

A: The simplest way is to delete <title> tag from index.html, and include

<title> Website - The page </title>

in every page in the web. Spiders will find this and will be shown in search results :)


text:
Q: I want to denormalise two rows of two columns into 4 different columns with one row Consider the following:
Before Processing
ID1  ID2  Type Cabin Tier Fee ED
2733 2606   43     4    2 100 4.77273
2733 2606   43     4    2 140 7.90909

After Processing
ID1  ID2  Type Cabin Tier Fee1 Fee2 ED1     ED2
2733 2606   43     4    2 100  140  4.77273 7.90909

Im using Pentaho ETL for my work.
The first step is the Table input where I'm taking all the unique set of data ID1, ID2, Type, Cabin, Tier with count of rows greater than 3 as required in my case.
Then I'm taking a  Database join to get data for one set of the above arguments wherein the two ED values are closest to 1 and their Fee values.
I need to further apply some calculations on the Fees and EDs and thought it would be easy to have them as Fee1 and Fee2 along with ED1 and ED2.
I tried using Row Flattner but I can only change one column data at a time. I want two row of columns Fee and ED to be flattened to 4 different columns as in the image "After Processing".
What would be a good way to achieve this?

A: Too long for comment, so as answer (hopefully helpful):
Required:
Your data should be like in your example (the first five fields are the same for a grouping):
Based on your starting position / before processing it should work by following these instructions.
Right after the Before-Processing-situation:

*

*step: sort by (get the first 5 fields to sort for the following group by-step)

*step: group by the first 5 fields (so except the Fee and ED, these two are to be setted in the Aggregates fields with "Concatenate strings separated by ,") --> ";" or "," its nearly the same here, but will be important on the next step

*Preview: If you do a preview you get this:

ID1;ID2;Type;Cabin;Tier;Fee;ED
2733;2606;43;4;2;**100,140**;**4.77273,7.90909**

The grouped values Fee and ED are seperated with "," in one field.

*Split fields-Steps:
now it's time to split the fields Fee and ED (you will need two split fields steps for each one. The delimiter for splitting is "," here, you have to give a name for the second field in the split field-steps.

The last steps splits the fields and you have the values in one row for calculating as you want.


text:
Q: how to generate vanilla Javascript from given html code automatically this question different from following questions
How do you parse and process HTML/XML in PHP?
this question is for getting Javascript code not html or php code
i want
user pest html code in textarea and then php script print the Javascript  that can be used for generating same html code using Javascript
i have done the getting tag name, create tag code, 'adding class, attributes' but i unable write "appendChild" like code because i can't find which is parent element & which if child element of which element
i have write following code

    <form action="" method="post">
        <textarea name="data" id="code" cols="200" rows="20">
<?php
    if(isset($_POST['data']))
    {
           echo $_POST['data'];
    }
?>
</textarea>
        <input type="submit">
    </form>

<?php

    if(isset($_POST['data']))
    {
        echo "
";
        echo $_POST['data'] ;
        echo "
";
    }

?>

<?php

    if(isset($_POST['data']))
    {
        //divide start tag and end tag
        $array=str_split($_POST['data']);
        $tag=array();
        $i=0;
        $tag_close=false;
        $tag_star=false;

        foreach($array as $key => $value)
        {
            // echo "
" .$i." is value of i
";
            // echo $tag_close . $tag_star;

            //

            // if($value=' ')
            // {

            // }
            // else
             if($value == '>')
            {
                $tag_close=true;
                $tag_star=false;
                $i++;

            }
            else if($value == '<')
            {
                $tag_star=true;
            }
            else if($tag_star)
            {

                $tag_close=false;

                if(!isset($tag[$i]))
                {
                    $tag[$i]='';
                }
                $tag[$i]=$tag[$i].$value;

            }

        }
//writing javascript
        $k=1;
        $tag_name='';
        $end_tag_started=false;
        $attribut=array();
        $attribut_val=array();
        $j=0;
        $o=0;
        $attribut_value_started=false;
// one y one tag adding and it's attriut
        foreach($tag as $key => $value)
        {
            $t='tag'.$k;
            $p='tag'.$o;
            $value_aaray=str_split($value);
            $tag_name='';
            $attribut=array();
            $attribut_val=array();
            $j=0;

            foreach($value_aaray as $val)
            {

                if($val==' ')
                {
                    $attribut[$j]='';
                    $attribut_val[$j]='';
                    foreach($value_aaray as $val_array)
                    {
                        if($val_array == " ")
                        {
                            $j++;
                            $attribut_value_started=false;
                        }
                        else if($val_array == "=")
                        {
                            $attribut_value_started=true;
                        }
                        else
                        {
                            if($attribut_value_started)
                            {
                                @$attribut_val[$j]=$attribut_val[$j].$val_array;
                            }
                            else
                            {
                                @$attribut[$j]=$attribut[$j].$val_array;
                            }
                        }
                    }

                    break;
                }
                if($val == '/')
                {
                    $end_tag_started=true;
                    break;
                }

                $tag_name=$tag_name.$val;
            }

            if(! $end_tag_started)
            {
                echo "
 \t";

                echo $t ."= document.createElement(\"".$tag_name."\");";
                echo "
 \t";

                for($l=1;$l<count($attribut);$l++)
                {
                    echo "       $t.setAttribute(\"".@$attribut[$l]."\",\"".@$attribut_val[$l]."\");
";
                }

            }

            $end_tag_started=false;
            $k++;
        }

        echo "
'tag'";
        print_r($tag);
        echo "
 ' letter array ' ";
        print_r($array);

        // for appendChild code but not working
        $a=array();
        for($i=0;$i<(count($tag));$i++)
        {
            $val=str_split($tag[$i]);

                if($val[0]=="/")
                {
                    echo "
";
                    echo $a[]="             tag". ( $i-2 ) .".appendChild(tag". ($i-1).");";
                }
        }

    }

?>

i get following output
textarea is start

textarea is end

tag1= document.createElement("div");

tag2= document.createElement("div");

tag4= document.createElement("div");

tag5= document.createElement("div");
'tag'Array ( [0] => div [1] => div [2] => /div [3] => div [4] => div [5] => /div [6] => /div [7] => /div )
' letter array ' Array ( [0] => < [1] => d [2] => i [3] => v [4] => > [5] => [6] => [7] => [8] => [9] => < [10] => d [11] => i [12] => v [13] => > [14] => [15] => [16] => < [17] => / [18] => d [19] => i [20] => v [21] => > [22] => [23] => [24] => [25] => [26] => < [27] => d [28] => i [29] => v [30] => > [31] => [32] => [33] => [34] => [35] => < [36] => d [37] => i [38] => v [39] => > [40] => [41] => [42] => < [43] => / [44] => d [45] => i [46] => v [47] => > [48] => [49] => [50] => [51] => [52] => < [53] => / [54] => d [55] => i [56] => v [57] => > [58] => [59] => [60] => [61] => [62] => < [63] => / [64] => d [65] => i [66] => v [67] => > )
            tag0.appendChild(tag1);
            tag3.appendChild(tag4);
            tag4.appendChild(tag5);
            tag5.appendChild(tag6);


text:
Q: binding grid view on button click in listview I have a list view with a button for each row:
 <td> <asp:Button ID="Button2" runat="server" Text="select" CommandName="view" CommandArgument='<%# Eval("inquiry_id")%>'   onclick="buttonClick"/></td>

On click of this button i retrieve the id of the clicked row, set the session with the same id and bind the grid view.This the code behind the button click in list view:
ListViewItem item = (sender as Button).NamingContainer as ListViewItem;
    Button butDetails = (Button)item.FindControl("Button2");
    Int64 inquiryID = Convert.ToInt64(butDetails.CommandArgument);
    Session["session_view_id"] = inquiryID;
    this.BindGrid();
    return;

The session is retrieved in bindGrid function. But the problem is gridview is not displayed at first click but on second click it gets displayed but with the data of the previous id clicked.The session is set but while binding the grid it uses old session value. Where am i going wrong to bind the grid?
The code for the bindGrid() function is :
 int inquiryID = Convert.ToInt32(Session["session_view_id"]);
   MySqlConnection conn = null;
    try
    {          MySqlCommand cmd = new MySqlCommand("SELECT * FROM crm_support_inquiry inner join  crm_inquiry_perticipant on crm_support_inquiry.inquiry_id=?id inner join crm_mailer_types on crm_support_inquiry.mailer_id=crm_mailer_types.mailer_id limit 4", connect);

        using (MySqlDataAdapter sda = new MySqlDataAdapter())
        {
            cmd.Parameters.AddWithValue("?id", inquiryID);
            cmd.Connection = connect;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
           {

               sda.Fill(dt);
                lblComp.Text = dt.Rows[0]["company"].ToString();
                lblCname.Text = dt.Rows[0]["contact_name"].ToString();
              lblEmail.Text = dt.Rows[0]["email"].ToString();
                GridView1.DataSource = dt;
                GridView1.DataBind();
           }
        }

A: Are you checking for IsPostBack in your Page_Load method? You need to wrap your BindGrid call in your Page_Load in an if(!IsPostBack) statement to prevent the Page_Load from initially refreshing the data on postback. This can prevent the changes you are making later on in your event handler.
protected void Page_Load(Object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        BindGrid();
    }
}

This answer can provide additional info: How to update page data after event handling?


text:
Q: Can I upgrade ghostscript from source on 10.04 over existing gs version 8.71? I would like to upgrade to a newer version of ghostscript (latest is 9.05, but anything in the 9.x series). Can I build and install from source over the top of the existing install?
I had a dry-run of uninstalling current version, but there were a lot of other things that would be removed with it that I didn't want to remove (for example freenx??).


text:
Q: SQL View - Nesting SELECT? I am trying to create a view from the following table.  I'm looking for the output to be the CUSTOMER, the most recent or MAX(CALENDARDT) for that CUSTOMER and a SUM(QTY) field, for all records that have the same CCYYMM field as the MAX(CALENDARDT) record.
Expected result would be
1500627 03/25/2013 5

5 being the sum of the qty field for the last two records both with 201303 in the CCYYMM field
Customer  |CCYYMM   |CalendarDt|DocNumb|Qty
1500627 |201202 |02/01/2012|Z201202|0
1500627 |201203 |03/02/2012|2542484|7
1500627 |201205 |05/04/2012|2979222|3
1500627 |201206 |06/20/2012|3262548|2
1500627 |201207 |07/31/2012|3500794|1
1500627 |201208 |08/30/2012|6946730|1
1500627 |201209 |09/13/2012|3774092|1
1500627 |201210 |10/31/2012|4063932|3
1500627 |201211 |11/16/2012|Z201211|0
1500627 |201301 |01/04/2013|Z201301|0
1500627 |201301 |01/30/2013|Z201301|0
1500627 |201303 |03/01/2013|4876779|1
1500627 |201303 |03/25/2013|5044331|4

A: This should work for you. The inner SELECT is used to get the max date per customer and that is JOINed back to the original table:
SELECT MyTable.Customer,
       MaxDates.MaxDate,
       SUM(Qty) AS TotalQuantity
FROM MyTable
JOIN (SELECT Customer,
             MAX(CalendarDT) AS MaxDate
      FROM MyTable
      GROUP BY Customer) AS MaxDates
    ON MaxDates.Customer = MyTable.Customer
    AND MaxDates.MaxDate = MyTable.CalendarDT
GROUP BY MyTable.Customer, MaxDates.MaxDate

A: You can do this with judicious use of window functions:
select customer, calendardt, sumqty
from (select t.*,
             row_number() over (partition by customer order by calendardt desc) as seqnum,
             sum(qty) over (partition by ccyymm) as sumqty
      from followingtable t
     ) t
where seqnum = 1;

Note that this assumes that the phrase:  " SUM(QTY) field, for all records that have the same CCYYMM field as the MAX(CALENDARDT) record" applies across all customers, not just the one customer.  If you want to limit it to the one customer, you can make this modification:
select customer, calendardt, sumqty
from (select t.*,
             row_number() over (partition by customer order by calendardt desc) as seqnum,
             sum(qty) over (partition by customer, ccyymm) as sumqty
      from followingtable t
     ) t
where seqnum = 1;


text:
Q: WPF application mouse position corrupted after restoring window, hence triggers false IsMouseOvers on controls I've designed a custom window with "WindowStyle = None" and "AllowsTransparency = True". I've added custom buttons to implement minimize, maximize/restore and close features. I also have a transparent rectangle that I use to implement maximize/restore on double clicking the title bar region(which is also custom built)
Here's the code for maximizing/restoring on double clicking the title bar region
(this.WindowState) = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;

I wanted to add an image which exactly describes my issue, but stackoverflow doesn't allow me to. I don't know why. I'm new to this page.

A: Yes, I know what you are talking about as I've noticed the same thing on my custom window. I haven't really explored a way to fix it yet though as it corrects itself. But I can confirm it is not specific to your code, just a general issue :).


text:
Q: Alfresco Activiti script task listener current scriptnode? Is there a way to get the ScriptNode that initiated a state in an Activiti workflow in Alfresco? I have a ScriptTask in my workflow, and it has a Alfresco Script Listener set up for the Start event. When the script is called, I'd like the ScriptNode that transitioned into the ScriptTask in the workflow to be passed as a parameter to the function defined as the listener. Is that possible?
Editing for clarity:
Here's a screenshot of Eclispe with the Activiti plugin.
http://i.imgur.com/DAKtq.jpg
This workflow gets started by another workflow with webscripts.
var props = new Object();
var dd = new Date();
props[EL_PROP_WORK_UNIT_NAME] = "testNode" + DateISOString( dd );
props[EL_PROP_WORK_UNIT_SOURCE_CODE] = "ROB";
props[EL_PROP_WORK_UNIT_DELIVERY_DATE] = dd;

node = getHome().createNode(name, EL_TYPE_WORK_UNIT, props);

var EL_WORKFLOW = "activiti$The-workflow";
var activeWfs = node.activeWorkflows;
if( activeWfs === null || activeWfs.length === 0 )
{
    var workflowPackage = workflow.createPackage();
    workflowPackage.addNode( node );
    var workflowDef = workflow.getDefinitionByName(EL_WORKFLOW);
    var workflowPath = workflowDef.startWorkflow( workflowPackage, new Object());
}

So the listener calls another javascript method...
function artPDFRename()
{
    logger.log("==============================");
    logger.log("<START> artPDFRename");

    var workflowDef = workflow.getDefinitionByName(EL_WORKFLOW);
    var activeInstance = workflowDef.getActiveInstances();
        // ????
}

The goal is to have this handling be automatic. We're trying to design this with as little of manual intervention as possible, and are not assigning tasks to users to perform. Yes, there's probably another way to rename a PDF file, but I can't seem to figure out from the documentation listed here how to get a pointer to the node I put in the bpm_package object. That's the question.
Or am I so far off base on how we're developing this that it makes no sense?

A: As an example check the ScriptTaskListener class. Here all the workflow variables are put in a map.
The following code is interesting:

// Add all workflow variables to model
          Map variables = delegateTask.getExecution().getVariables();
    for (Entry<String, Object> varEntry : variables.entrySet())
    {
        scriptModel.put(varEntry.getKey(), varEntry.getValue());
    }

So with this you could use bpm_package as an object within your script within the workflow script task.
So if you need the node were the workflow has run on, the following code should work (where task is your delegateTask from your notify method of the Listener:

delegateTask.getVariable("bpm_package");
  // or like the example above
  delegateTask.getExecution().getVariable("bpm_package");

This will be a list so take the first one and that will be your node.
---------update
If you're using the javascript from alfresco then you can directly use the parent object bpm_package.
So in your case it would be best to do the following:

var node = bpm_package.children[0]; //or you could check if the
  package isn't null
  // Then send the node into your
  artPDFRename(node); //or you could just add the bpm_package code in
  your js file


text:
Q: Fully Delete Row in JSON I'm using a method to delete specific lines in a JSON. The user presses a button and the button determines which line to remove. I know that the correct index is being passed in, but my problem is that when I try to remove the row it just replaces it with null, so there's still something there. How do I remove it entirely?
function removeTest(place) {
    var parsedObject = JSON.parse(localStorage["flexuralStrengthSamples"]);
    delete parsedObject[parseInt(place.data.text)];

    localStorage["flexuralStrengthSamples"] = JSON.stringify(parsedObject);

    console.log(JSON.stringify(parsedObject));

    displaySamples();
}

And my resulting JSON:
[{"Result":"Fail","Method":"T97E-v1","Beam1":{"TestingMachineId":"1","BeamAge":"1","WidthUpper":1,"WidthCenter":1,"WidthLower":1,"WidthAverage":1,"DepthRight":1,"DepthCenter":1,"DepthLeft":1,"DepthAverage":1,"MaxLoad":1,"FS":18,"PSI":"18.00000","BreakOutside":"No"},"Beam2":{"BeamAge":"","WidthUpper":null,"WidthCenter":null,"WidthLower":null,"WidthAverage":null,"DepthRight":null,"DepthCenter":null,"DepthLeft":null,"DepthAverage":null,"MaxLoad":null,"FS":null,"PSI":"NaN"},"WaitForCuring":"No","AverageOfBeams":"NaN"},null]

In this instance I tried to remove the second of two.

A: Based on your resulting JSON, you have an Array [] of Objects {}.
In order to remove an item from an Array (and update it's length) you will have to use splice
More reading on the delete operator:

Deleting array elements
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

Example
var arr = [ {name: "Hello"}, {name: "World"} ];

// Delete does not modify an array's length, hence the "undefined"
delete arr[1]; // => [Object, undefined × 1]

// Splice will change the contents of an array and update its length
arr.splice(1,1); // => [Object]


text:
Q: Question about the generated Hibernate Queries in 3 situation I want to learn relations among tables and i met a question about data persistance.
I created 2 entities, User and Dog. Suppose it's a single-direction many-to-one relation, one user can have many dogs, one dog can only have one user.
In DogEntity Class:
    @ManyToOne
    @JoinColumn(name = "user_id")
    private UserEntity user;

And no private field in UserEntity class.
When I test like below:

    @Test
    public void saveManyFirst(){
        UserEntity user1 = new UserEntity("user2@qq.com", "123qwe",
                "zhangsan2",null,
                null,null,
                null);
        DogEntity dog1 = new DogEntity("Sakura","Akita",null,user1);
        DogEntity dog2 = new DogEntity("Sakura2","Akita2",null,user1);

        dogDao.save(dog1);
        dogDao.save(dog2);
        userDao.save(user1);
    }

It's reasonable to get an error as "object references an unsaved transient instance - save the transient instance before flushing".
Then I added @Transactional as below:
    @Test
    @Transactional
    public void saveManyFirst(){
        UserEntity user1 = new UserEntity("user2@qq.com", "123qwe",
                "zhangsan2",null,
                null,null,
                null);
        DogEntity dog1 = new DogEntity("Sakura","Akita",null,user1);
        DogEntity dog2 = new DogEntity("Sakura2","Akita2",null,user1);

        dogDao.save(dog1);
        dogDao.save(dog2);
        userDao.save(user1);
    }

I got three Inserts, and table of dog,table of user.
The FKs in table of Dog are null.
Then I added @Rollback(false)  (the defalut value is true).
    @Test
    @Transactional
    @Rollback(false)
    public void saveManyFirst(){
        UserEntity user1 = new UserEntity("user2@qq.com", "123qwe",
                "zhangsan2",null,
                null,null,
                null);
        DogEntity dog1 = new DogEntity("Sakura","Akita",null,user1);
        DogEntity dog2 = new DogEntity("Sakura2","Akita2",null,user1);

        dogDao.save(dog1);
        dogDao.save(dog2);
        userDao.save(user1);
    }

I got 3 Inserts and 2 more updates, and the FKs in table of Dog are updated as wished.
table of dog
Of course I know I should better save the one who has the FK first, but I'm learning Spring Data Jpa, I really want to know why this happend. Could you please help me? Thanks in advance.

A: When you have one transaction spanning over all operations, because at the end of the trasaction, it sees that Dog references a User which is already what JPA calls managed.
When you have no transaction, Spring-Data JPA create a transaction per call i.e. each call to save. So you have 3 transactions. Now the first transaction when it is about to commit tries to flush and sees that the dog does not have a managed User reference but a transient one, which is why you get the error.
Note that a flush can be triggered when loading/querying as well, so it's important that you either use proper cascades on your associations or make sure the flushing happens in the appropriate order.


text:
Q: Reset Cuda Context after exception I have a working app which uses Cuda / C++, but sometimes, because of memory leaks,  throws exception. I need to be able to reset the GPU on live, my app is a server so it has to stay available.
I tried something like this, but it doesnt seems to work:
try
{
    // do process using GPU
}
catch (std::exception &e)
{
    // catching exception from cuda only

    cudaSetDevice(0);
    CUDA_RETURN_(cudaDeviceReset());
}

My idea is to reset the device each times I get an exception from the GPU, but I cannot manage to make it working. :(
Btw, for some reasons, I cannot fix every problems of my Cuda code, I need a temporary solution. Thanks !

A: The only method to restore proper device functionality after a non-recoverable ("sticky") CUDA error is to terminate the host process that initiated  (i.e. issued the CUDA runtime API calls that led to) the error.
Therefore, for a single-process application, the only method is to terminate the application.
It should be possible to design a multi-process application, where the initial ("parent")  process makes no usage of CUDA whatsoever, and spawns a child process that uses the GPU.  When the child process encounters an unrecoverable CUDA error, it must terminate.
The parent process can, optionally, monitor the child process. If it determines that the child process has terminated, it can re-spawn the process and restore CUDA functional behavior.
Sticky vs. non-sticky errors are covered elsewhere, such as here.
An example of a proper multi-process app that uses e.g. fork() to spawn a child process that uses CUDA is available in the CUDA sample code simpleIPC.  Here is a rough example assembled from the simpleIPC example (for linux):
$ cat t477.cu
/*
 * Copyright 1993-2015 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

// Includes
#include <stdio.h>
#include <assert.h>

// CUDA runtime includes
#include <cuda_runtime_api.h>

// CUDA utilities and system includes
#include <helper_cuda.h>

#define MAX_DEVICES          1
#define PROCESSES_PER_DEVICE 1
#define DATA_BUF_SIZE        4096

#ifdef __linux
#include <unistd.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <linux/version.h>

typedef struct ipcDevices_st
{
    int count;
    int results[MAX_DEVICES];
} ipcDevices_t;

// CUDA Kernel
__global__ void simpleKernel(int *dst, int *src, int num)
{
    // Dummy kernel
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    dst[idx] = src[idx] / num;
}

void runTest(int index, ipcDevices_t* s_devices)
{
    if (s_devices->results[0] == 0){
        simpleKernel<<<1,1>>>(NULL, NULL, 1);  // make a fault
        cudaDeviceSynchronize();
        s_devices->results[0] = 1;}
    else {
        int *d, *s;
        int n = 1;
        cudaMalloc(&d, n*sizeof(int));
        cudaMalloc(&s, n*sizeof(int));
        simpleKernel<<<1,1>>>(d, s, n);
        cudaError_t err = cudaDeviceSynchronize();
        if (err != cudaSuccess)
          s_devices->results[0] = 0;
        else
          s_devices->results[0] = 2;}
    cudaDeviceReset();
}
#endif

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

    ipcDevices_t *s_devices = (ipcDevices_t *) mmap(NULL, sizeof(*s_devices),
                                                    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
    assert(MAP_FAILED != s_devices);

    // We can't initialize CUDA before fork() so we need to spawn a new process
    s_devices->count = 1;
    s_devices->results[0] = 0;

    printf("\nSpawning child process\n");
    int index = 0;

    pid_t pid = fork();

    printf("> Process %3d\n", pid);
    if (pid == 0) { // child process
    // launch our test
      runTest(index, s_devices);
    }
    // Cleanup and shutdown
    else { // parent process
            int status;
            waitpid(pid, &status, 0);
            if (s_devices->results[0] < 2) {
              printf("first process launch reported error: %d\n", s_devices->results[0]);
              printf("respawn\n");
              pid_t newpid = fork();
              if (newpid == 0) { // child process
                    // launch our test
                 runTest(index, s_devices);
                  }
    // Cleanup and shutdown
              else { // parent process
                int status;
                waitpid(newpid, &status, 0);
                if (s_devices->results[0] < 2)
                  printf("second process launch reported error: %d\n", s_devices->results[0]);
                else
                  printf("second process launch successful\n");
                }

            }

    }

    printf("\nShutting down...\n");

    exit(EXIT_SUCCESS);

}
$ nvcc -I/usr/local/cuda/samples/common/inc t477.cu -o t477
$ ./t477

Spawning child process
> Process 10841
> Process   0

Shutting down...
first process launch reported error: 1
respawn

Shutting down...
second process launch successful

Shutting down...
$

For windows, the only changes need should be to use a windows IPC mechanism for host interprocess communication.


text:
Q: Context.Items clears during page refresh/transfer I am working on a class project and I've run into a problem I can't figure out. I have a feeling it's actually pretty easy, but I've been working on stuff so long I can't think straight anymore.
I have a login page that allows a user to login and pass 2 data items to the next page using Context.Items and Server.Transfer. Here is the code snippet:
Context.Items["preferred"] = true;
Context.Items["pageNum"] = 1;
Server.Transfer("ProductsShelf.aspx");

On the "ProductsShelf" page I can access those two items and use the data like so:
pageNumber = (int)Context.Items["pageNum"];

I am then using a switch-statement with pageNumber to display certain information:
switch (pageNumber)
{
    case 1:
        imgProd.ImageUrl = "assets/laptop.bmp";
        lbl_Name.Text = "Laptop";
        lbl_desc.Text = "This is a cheap laptop!";
        lbl_price.Text = "199.99";
        break;
}

Obviously there's other entries I'm omitting. What I want to do is click a next or previous button and use the event to change the Context.Items["pageNum"] data so the Page_Load() event uses different data in the switch-statement. Hope that makes sense. Here is one of the button click events:
protected void btn_Prev_Click(object sender, EventArgs e)
{
        if (pageNumber == 1 || pageNumber == 2)
        {
            Context.Items["pageNum"] = 1;
        }
        else if (pageNumber == 3)
        {
            Context.Items["pageNum"] = 2;
        }
        Context.Items["preferred"] = preferredCustomer;
        Server.Transfer("ProductsShelf.aspx");
}

The problem is that before the button click event fires, the form posts and clears the Context.Items and pageNumber values. This means that the button event if-statements never fire and it results in:
pageNumber = (int)Context.Items["pageNum"];

Being null, throwing an exception and making me very sad. So my question is, how can I go about retaining the values? Should I switch to Response.Redirect and have something like ?page=1 in the URL? Or will that clear too when the form posts? Hopefully I'm not doing this completely wrong.
If TL;DR, here's a quick summary:

*

*Context.Items has 2 values passed with Server.Transfer

*These values determine what's shown on the next page

*The form clears Context.Items and variables before button click event fires

*The values are null, the if-statement doesn't run, and the app throws an exception

*Question: how should I go about retaining those values?

Thanks a lot. :)

A: HttpContext items can be used within one request only - it will be recreated for next request so your values are bound to lose. You should use view-state to preserve data across post-backs. In page load, you should check if data exists in context and then copy it to view-state. Then in button click events, you can read the data from view-state, put into the context items and do server.transfer.
Here's simple sample code:
private int PageNumber
{
   get
   {
    var value = ViewState["pageNum"];
    return null == value? 1: (int)value;
   }
   set
   {
     ViewState["pageNum"] = value;
   }
}

private bool IsPreferredCustomer
{
   get
   {
    var value = ViewState["preferred"];
    return null == value? false: (bool)value;
   }
   set
   {
     ViewState["preferred"] = value;
   }
}

protected void Page_Load(object sender, EventArgs e)
{
    var preferred = Context.Items["preferred"];
    if (null != preferred)
    {
      IsPreferredCustomer =  (bool)preferred;
    }
    var pageNum = Context.Items["pageNum"];
    if (null != pageNum )
    {
      PageNumber =  (int)Context.Items["pageNum "];
    }
}

Use the same PageNumber property in event code.


text:
Q: Laravel 8 not validating pdf file I am using laravel version 8 and I wanted to validate the uploaded file should be a pdf file, I am using the below code
$request->validate([
      'cv'=> 'required|mimes:pdf|max:2048'
]);

but the problem is that I still get the error of "The cv must be a file of type:  pdf" even though I am uploading a pdf file.
solved by adding enctype="multipart/form-data" atrribute in form tag

A: you can use mimetypes validation:
$request->validate([
      'cv'=> 'required|mimetypes:application/pdf|max:10000'
]);

A: Before 5.2
$rules  = [
    "file" => "required|mimes:pdf|max:10000"
]

From laravel Docs:
Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.
After 5.2 Update:
Starting from Laravel 5.2, you could validate file upload against full MIME type, new validation rule called: mimetypes.
$rules  = [
    "file" => "required|mimetypes:application/pdf|max:10000"
]


text:
Q: Finding nearest station index on the grid from given data points in lat/lon on a grid in Python I have 30000 data points on a grid and 4000 data points of stations of which, data is known. I need to find out which station index is closest to all the 30000 grid point. Please note that the locations of all the points are in lat/lon and I am writing the code in Python.
P.S.- I think, calculating the distance of a point from all the stations and then finding the minimum would not be feasible for 30000 points.
# Pseudo-Code!
station_location = a list of 4000 lat, long points
data_points = a list containing lat & long of 30000 grid points

Required output
# Pseudo-Code!
for i in range(data_points):
   which station_location index is nearest to data_points[i]

Thanks


text:
Q: Undo apt-get remove open* ubuntu 12.04 I am running a Linux instance on ec2, snap sorting of image is disabled.
While trying to un-install open-jdk from the system. I stupidly run the command
sudo apt-get remove open*
It started removing many packages, so I stopped the process by CTRL + c.
I did it twice:

*

*sudo apt-get remove open*

*sudo apt-get remove openjdk*

I stopped the process( CTRL + c) in between for both of them.
Now I see that my other application are not working, because of the packages removed.
Please advice,how can I go back to the state before apt-get remove.
Thanks in advance.

A: While using the logfiles you might also be able to 'manually' undo, there's an operation worth trying before spending hours on it: apt-get -f install
Edit: from debian's man page:

  -f, --fix-broken
      Fix; attempt to correct a system with broken dependencies in place. This option, when used with install/remove, can omit any packages to permit APT to deduce a
      likely solution. If packages are specified, these have to completely correct the problem. The option is sometimes necessary when running APT for the first time; APT
      itself does not allow broken package dependencies to exist on a system. It is possible that a system's dependency structure can be so corrupt as to require manual
      intervention (which usually means using dselect(1) or dpkg --remove to eliminate some of the offending packages). Use of this option together with -m may produce an
      error in some situations. Configuration Item: APT::Get::Fix-Broken.


text:
Q: String format specifier handling float variable def to_celsius(self):
     """Fahrenheit to Celsius"""

     fah = float(self.ent_fahrenheit.get())
     cel = (5 / 9) * (fah - 32)

     tkMessageBox.showinfo("Fahrenheit To Celsius",
             "%s deg F is equal to %.2f deg C" % (fah, cel))

I have a Python 2 code snippet using Tkinter to display a simple message box.
I am wondering if it is okay that the format specifier %s is handling (receiving) a float value from variable fah?
It seems like it is because I am not encountering any error of some sort when I ran the program.

A: Using %s is fine, but is still the equivalent of calling str() on the object. If you want to be able to specify float width and precision then you should use one of the float specifiers (e, E, f, F, g, G) instead.


text:
Q: In the figure, $ABCD$ is a parallelogram. In the figure, $ABCD$ is a parallelogram. $E$ is the mid point of $AB$. $DF$ and $CF$ are intersected at $F$. Prove that $4\triangle AEF=Quadrilateral ABCD$

My Attempt
$\triangle DEC=\frac {1}{2} parallelogram ABCD$
$\triangle AED+\triangle EBC=\frac {1}{2} parallelogram ABCD$
Now what should I do next?

A: If you look at triangles $FEB$ and $FDC$, you should be able to see that $FB=BC$. This gives you immediately that $\triangle FEB = \triangle BEC$. Also, $\triangle FEB = \triangle AEF$.
Now your own observations are enough to finish the job.

A: Let the area  ABCD be 4.
By drawing the line thru E parallel to AD, intersecting DC at G, we see that the  triangles AED , GDE are congruent to each other,and that the triangles BEC , GCE are congruent to each other. Also, the areas of AED and  BEC are equal because the heights of D,C above the line AB are equal, and the bases AE,BE are equal. So each of AED, GDE,BEC, GCE has area 1.
Triangles AEF and BEF have equal area because their bases AE,BE are equal and they share the vertex F.
Now BE is parallel to DC, so  the triangles BEF and CDF are similar,in a ratio BE:CD=1:2. So the ratio of their areas is 1:4. So the ratio of the area BEF to that of quadrilateral BEDC is 1:3.
So.... AEF=BEF=(1/3)BEDC=(1/3)(ABCD -AED)=(1/3)(4-1)=1=(1/4)ABCD.


text:
Q: estimote beacons - could not bind service i try to develop app with using Becons. I have this small Estimote Beacon. I made steps described in this short instruction. I downloaded the library from github, I added it to myproject.
My code look like this,
public class MainActivity extends Activity {

 BeaconManager beaconManager;

  private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
  private static final Region ALL_ESTIMOTE_BEACONS = new Region(ESTIMOTE_PROXIMITY_UUID, null, null);

  final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.e(TAG, "onCreate");

    beaconManager = new BeaconManager(getApplicationContext());

    if(beaconManager.isBluetoothEnabled())
    {
        Toast.makeText(getApplicationContext(), "Bl włączone", Toast.LENGTH_LONG).show();
    }
    else
    {
        Toast.makeText(getApplicationContext(), "Bl wyłączone", Toast.LENGTH_LONG).show();
    }

      beaconManager.setRangingListener(new BeaconManager.RangingListener() {
        @Override public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
          Log.d(TAG, "Ranged beacons: " + beacons);
          Toast.makeText(MainActivity.this,"Ranged beacons: " + beacons, Toast.LENGTH_LONG).show();
        }
      });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.e(TAG, "onStart");
    beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
        @Override public void onServiceReady() {
          try {
            beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
            Toast.makeText(getApplicationContext(), "try start ranging", Toast.LENGTH_LONG).show();

          } catch (RemoteException e) {
            Log.e(TAG, "Cannot start ranging", e);
            Toast.makeText(getApplicationContext(), "Cannot start ranging", Toast.LENGTH_LONG).show();
          }
        }
      });
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
      // Should be invoked in #onStop.
      try {
        beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS);
      } catch (RemoteException e) {
        Log.e(TAG, "Cannot stop but it does not matter now", e);
        Toast.makeText(getApplicationContext(), "Cannot stop but it does not matter now", Toast.LENGTH_LONG).show();
      }

}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
     // When no longer needed. Should be invoked in #onDestroy.
      beaconManager.disconnect();
}

}
and manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.beacon"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="18"
    android:targetSdkVersion="18" />

 <!-- Needed permissions in order to scan for beacons. -->
 <uses-permission android:name="android.permission.BLUETOOTH"/>
 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

 <!-- Declaration that this app is usable on phones with Bluetooth Low Energy. -->
  <uses-feature android:name="android.hardware.bluetooth_le"
    android:required="true"/>

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
      <service android:name="com.estimote.sdk.service.BeaconService"
     android:exported="false"/>
    <activity
        android:name="com.example.beacon.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
       </activity>
   < /application>
</manifest>

showed on the page and I get this message
02-22 05:27:08.711: A/BeaconManager(7227): Could not bind service

For me it means like it's problem with creating BeaconManager, but have no idea how to fix it. There is no problem with device cause I see all beacons when I scanned it by iBeacon Locate app. I would be grateful for any suggestion

A: Which version of Estimote SDK are you using? Is it the newest 0.4 version? Checking it as newest has different log tags.
If logs says "Could not bind service" that means that com.estimote.sdk.service.BeaconService could not have been found. Note that early version of the SDK BeaconService was in com.estimote.sdk package and not in com.estimote.sdk.service one.
BTW were you able to run Demos in the Estimote SDK?


text:
Q: Css jittery text translate [SOLUTION]
Solution is to use the will-change CSS property taht forces GPU rendering:
will-change: transform;

[ORIGINAL QUESTION]
I've been digging a lot internet and found no solution to a problem that seems rather simple which is, translating a holder containing text, and having this text moving smoothly.
Here is an example of the problem, you can see the text is following its holder step by step, not smoothly:

I also made a small codepen to see the effect live :
https://codepen.io/Durss/pen/ExgBzVJ?editors=1111

var angle = 0;
var radius = 100;
function renderFrame() {
        requestAnimationFrame(renderFrame);
    var cx = document.documentElement.clientWidth / 2;
    var cy = document.documentElement.clientHeight / 2;
    var div = document.getElementById("text");
    var px = cx + Math.cos(angle) * radius;
    var py = cy + Math.sin(angle) * radius;
    angle += .001;
    div.style.transform = "translate3d("+px+"px, "+py+"px, 0)";
}

renderFrame();
body {
  background-color:black;
  width:100%;
  height:100%;
}

#text {
  position:absolute;
  left:0;
  top:0;
  border: 2px solid white;
  background-color: #2f9da7;
  padding: 10px;
  border-radius:20px;
  color: white;
  font-weight: bold;
}

blah blah

Basically, the problem is that the holder is moving at a subpixel level but the text position seems rounded no matter what i try.
I used translate3d() so it uses GPU rendering which fixes the holder's displacement but not its text content.
div.style.transform = "translate3d("+px+"px, "+py+"px, 0)";

I've seen here and there the following CSS "solutions" that didn't work for me:
text-rendering: geometricPrecision;
-webkit-font-smoothing: antialiased;
transform-style: preserve-3d;
backface-visibility: hidden;
-webkit-font-smoothing:none;

I've had this problem many time in the past but always gave up fixing it,i think it's time to seek for help as a last bullet !
Thanks for reading me!

A: CSS transitions help on making sub-pixels animations smoother.
transition: all 0.001s linear;

It works fine on chrome, but seems a bit less effective on firefox.
This article may help :
Firefox CSS Animation Smoothing (sub-pixel smoothing)

A: will-change: contents;

resolved my own jittery text issues when doing transform rotations.  This tells the browser that the contents of an element are expected to change therefore should not be cached.
This must be applied immediately before the transform.

A: As a workaround you can Math.round the px values. This would prevent the text from jittering on its own (makes the whole containing div jittery).

var angle = 0;
var radius = 100;
function renderFrame() {
        requestAnimationFrame(renderFrame);
    var cx = document.documentElement.clientWidth / 2;
    var cy = document.documentElement.clientHeight / 2;
    var div = document.getElementById("text");
    var px = Math.round(cx + Math.cos(angle) * radius);
    var py = Math.round(cy + Math.sin(angle) * radius);
    angle += .001;
    div.style.transform = "translate3d("+px+"px, "+py+"px, 0)";
}

renderFrame();
body {
  background-color:black;
  width:100%;
  height:100%;
}

#text {
  position:absolute;
  left:0;
  top:0;
  border: 2px solid white;
  background-color: #2f9da7;
  padding: 10px;
  border-radius:20px;
  color: white;
  font-weight: bold;
}

blah blah


text:
Q: AdMob mediation (Android and iOS) : how to force a network to test it? I am implementing AdMob mediation with several third party networks. I would like to test that the mediation with each of these networks is well implemented (ads well displayed).
I would like to force the display of an ad from a defined network to test its implementation, and then switch quickly to another network.
One way to do that should be to change the bids in the AdMob mediation interface. For example put 100$ on the network I want to test and 0.1 $ on the other ones.
But the problem is it seems that there is some delay before the changes are taken into account and even after a long delay, it seems that I do not have 100% of ads from the network at 100$.
How can I force a network (any test mode ?) in a manner that I will have immediately ads from this networks on 100% of the requests ? It could be test ads from this network.
Thanks !

A: Most of the third part ad networks don't have a test mode via AdMob mediation.
The only way I have found so far is via the
AdMob dashboard->Monetize->'Your App's Mediation page'.
In that page when you click on the ad sources:

It will show you an edit option, from where you can pause/enable ads from individual ad networks:

I do share your pain of the delay it takes for those dashboard changes to propagate to the actual test device.
Hope this was of some help.
Kind regards,
Mukund Agarwal


text:
Q: Pd.read_sql add zero to int number from table sql server I'm wondering why pandas.read_sql add .zero at the end of my data please ?
In SQL Server, the data are number indicated like int.

Someone knows why please?
And when I look type of data, it's indicated like float64.

A: According to this solution, this happens because your data might contains NaN values, so in order to handle this, int data type is automatically converted to float.
When introducing NAs into an existing Series or DataFrame via reindex or some other means, boolean and integer types will be promoted to a different dtype in order to store the NAs. These are summarized by this table:
Typeclass   Promotion dtype for storing NAs
floating    no change
object      no change
integer     cast to float64
boolean     cast to object


text:
Q: `python setup.py upload_docs` succeeds but nothing changes online I am trying to publish documentation on pythonhosted.org using setuptools, but while python setup.py upload_docs succeeds, nothing changes online, and no update of the documentation is reported in my package's journal on PyPI either.
Yet, I can still manually upload a ZIP file using the PyPI web interface, and this works just fine.
I used to build and deploy the documentation with MkDocs using:
$ mkdocs build --clean
$ python setup.py upload_docs

None of them reports any error. The new website is properly generated and can be served locally by MkDocs.
I tried Python 3.4.2, 3.5 and 3.6, as well as with several versions of setuptools. I must be missing something obvious.
Below is the output of the upload_docs command (with debug info). Note that the content of the website is stored under "./site", as detected. See also my project configuration, especially setup.py and setup.cfg.
$ python setup.py upload_docs
options (after parsing config files):
options (after parsing command line):
option dict for 'aliases' command:
{}
option dict for 'metadata' command:
{'description_file': ('setup.cfg', 'README.adoc')}
option dict for 'upload_docs' command:
{'upload_dir': ('setup.cfg', 'site')}
running upload_docs
Distribution.get_command_obj(): creating 'upload_docs' command object
setting options for 'upload_docs' command:
upload_dir = site (from setup.cfg)
Upload_docs command is deprecated. Use RTD instead.
Submitting documentation to https://pypi.python.org/pypi/
Server response (200): OK

Thanks in advance for any help.

A:
None of them reports any error.

Technically true, but you appear to be ignoring a simple warning. From your output:

Upload_docs command is deprecated. Use RTD instead.

The "deprecated" part is clear enough: this command is no longer recommended for use.
The "Use RTD instead" part is unclear, I grant you. It should be more explicit: it is referring you to the Read the Docs service.
This is because there is a (poorly documented as of 2017-04-05) plan to remove the PyPI documentation hosting service.


text:
Q: Loop through multiple CSV files and run a script I have a script which pulls in data from a csv file, does some manipulations to it and creates an output excel file. But, its a tedious process as I need to do it for multiple files.
Question: Is there a way for me to run this script across multiple csv files together and create a separate excel file output for each input file?
I'm not sure what to try out here. I've read that I need to use a module called glob but I'm not sure how to go about it.
This script works for a single file:
# Import libraries
import pandas as pd
import xlsxwriter

# Set system paths
INPUT_PATH = 'SystemPath//Downloads//'
INPUT_FILE = 'rawData.csv'

OUTPUT_PATH = 'SystemPath//Downloads//Output//'
OUTPUT_FILE = 'rawDataOutput.xlsx'

# Get data
df = pd.read_csv(INPUT_PATH + INPUT_FILE)

# Clean data
cleanedData = df[['State','Campaigns','Type','Start date','Impressions','Clicks','Spend(INR)',
                  'Orders','Sales(INR)','NTB orders','NTB sales']]
cleanedData = cleanedData[cleanedData['Impressions'] != 0].sort_values('Impressions',
                                                                       ascending= False).reset_index()
cleanedData.loc['Total'] = cleanedData.select_dtypes(pd.np.number).sum()
cleanedData['CTR(%)'] = (cleanedData['Clicks'] /
                         cleanedData['Impressions']).astype(float).map("{:.2%}".format)
cleanedData['CPC(INR)'] = (cleanedData['Spend(INR)'] / cleanedData['Clicks'])
cleanedData['ACOS(%)'] = (cleanedData['Spend(INR)'] /
                          cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
cleanedData['% of orders NTB'] = (cleanedData['NTB orders'] /
                                  cleanedData['Orders']).astype(float).map("{:.2%}".format)
cleanedData['% of sales NTB'] = (cleanedData['NTB sales'] /
                                 cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
cleanedData = cleanedData[['State','Campaigns','Type','Start date','Impressions','Clicks','CTR(%)',
                           'Spend(INR)','CPC(INR)','Orders','Sales(INR)','ACOS(%)',
                           'NTB orders','% of orders NTB','NTB sales','% of sales NTB']]

# Create summary
summaryData = cleanedData.groupby(['Type'])[['Spend(INR)','Sales(INR)']].agg('sum')
summaryData.loc['Overall Snapshot'] = summaryData.select_dtypes(pd.np.number).sum()
summaryData['ROI'] = summaryData['Sales(INR)'] / summaryData['Spend(INR)']

# Push to excel
writer = pd.ExcelWriter(OUTPUT_PATH + OUTPUT_FILE, engine='xlsxwriter')
summaryData.to_excel(writer, sheet_name='Summary')
cleanedData.to_excel(writer, sheet_name='Overall Report')
writer.save()

I've never tried anything like this before and I would appreciate your help trying to figure this out

A: You can use Python's glob.glob() to get all of the CSV files from a given folder. For each filename that is returned, you could derive a suitable output filename. The file processing could be moved into a function as follows:
# Import libraries
import pandas as pd
import xlsxwriter
import glob
import os

def process_csv(input_filename, output_filename):
    # Get data
    df = pd.read_csv(input_filename)

    # Clean data
    cleanedData = df[['State','Campaigns','Type','Start date','Impressions','Clicks','Spend(INR)',
                    'Orders','Sales(INR)','NTB orders','NTB sales']]
    cleanedData = cleanedData[cleanedData['Impressions'] != 0].sort_values('Impressions',
                                                                        ascending= False).reset_index()
    cleanedData.loc['Total'] = cleanedData.select_dtypes(pd.np.number).sum()
    cleanedData['CTR(%)'] = (cleanedData['Clicks'] /
                            cleanedData['Impressions']).astype(float).map("{:.2%}".format)
    cleanedData['CPC(INR)'] = (cleanedData['Spend(INR)'] / cleanedData['Clicks'])
    cleanedData['ACOS(%)'] = (cleanedData['Spend(INR)'] /
                            cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
    cleanedData['% of orders NTB'] = (cleanedData['NTB orders'] /
                                    cleanedData['Orders']).astype(float).map("{:.2%}".format)
    cleanedData['% of sales NTB'] = (cleanedData['NTB sales'] /
                                    cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
    cleanedData = cleanedData[['State','Campaigns','Type','Start date','Impressions','Clicks','CTR(%)',
                            'Spend(INR)','CPC(INR)','Orders','Sales(INR)','ACOS(%)',
                            'NTB orders','% of orders NTB','NTB sales','% of sales NTB']]

    # Create summary
    summaryData = cleanedData.groupby(['Type'])[['Spend(INR)','Sales(INR)']].agg('sum')
    summaryData.loc['Overall Snapshot'] = summaryData.select_dtypes(pd.np.number).sum()
    summaryData['ROI'] = summaryData['Sales(INR)'] / summaryData['Spend(INR)']

    # Push to excel
    writer = pd.ExcelWriter(output_filename, engine='xlsxwriter')
    summaryData.to_excel(writer, sheet_name='Summary')
    cleanedData.to_excel(writer, sheet_name='Overall Report')
    writer.save()

# Set system paths
INPUT_PATH = 'SystemPath//Downloads//'
OUTPUT_PATH = 'SystemPath//Downloads//Output//'

for csv_filename in glob.glob(os.path.join(INPUT_PATH, "*.csv")):
    name, ext = os.path.splitext(os.path.basename(csv_filename))
    # Create an output filename based on the input filename
    output_filename = os.path.join(OUTPUT_PATH, f"{name}Output.xlsx")
    process_csv(csv_filename, output_filename)

os.path.join() can be used as a safer way to join file paths together.

A: Something like:
import os
import glob
import pandas as pd

os.chdir(r'path\to\folder') #changes folder path to working dir
filelist=glob.glob('*.csv') #creates a list of all csv files
for file in filelist:       #loops through the files
    df=pd.read_csv(file,...)
    #Do something and create a final_df
    final_df.to_excel(file[:-4],+'_output.xlsx',index=False) #excel with same name+ouput

A: you can run this scrip inside a for loop:
for file in os.listdir(INPUT_PATH):
    if file.endswith('.csv') or file.endswith('.CSV'):
        INPUT_FILE = INPUT_PATH + '/' + file
        OUTPUT_FILE = INPUT_PATH  + '/Outputs/' + file.[:-4] + 'xlsx'

A: try this:
import glob

files = glob.glob(INPUT_PATH + "*.csv")

for file in files:
    # Get data
    df = pd.read_csv(file)

    # Clean data
    #your cleaning code

   # Push to excel
   writer = pd.ExcelWriter(OUTPUT_PATH + file.split("/")[-1].replace(".csv","_OUTPUT.xlxs", engine='xlsxwriter')


text:
Q: sencha touch :: useClearIcon listener in searchfield is there a way to listen to the event, when the user clicks/tabs on the clearIcon in a seachfield?
unfort. the keyup and change listeners are ignored then...
thnx!

A: I have put the following code on the onFirstActivate method of the panel:
var clearIconEl = this.getEl().down('[class="x-field-clear-container"]');
clearIconEl.on('click', this.handleClearIconClick, this);

this catches the clear icon click, though it depends on its undocumented css class.
UPDATE:
I see two much more elegant solutions to this same problem at sencha touch textfield clear event
I think I will use one of them myself...


text:
Q: 3 positional argument(s) expected, but 0 found. 1 import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
import './quiz.dart';
import './result.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
//class MyAppState extends State{
  final _questions = const [
    {
      'questionText': "What\'s your favourite color?",
      'answer': ['Black', 'Red', 'Green', 'White'],
    },
    {
      'questionText': 'What\'s your fav animal?',
      'answer': ['Wolf', 'Cat', 'Dog', 'Tiger'],
    },
    {
      'questionText': 'Who is your fav instructor?',
      'answer': ['Max', 'Max', 'Max', 'Max'],
    }
  ];
  var _questionIndex = 0;

  void _answerQuestion() {
    if (_questionIndex < _questions.length) {
      print("We have more question!");
    }
    setState(() {
      _questionIndex = _questionIndex + 1;
    });
    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('My first App'),
          ),
          body: _questionIndex < _questions.length ?
          Quiz(
              answerQuestion: _answerQuestion,
              questions: _questions,
              questionIndex:_questionIndex
          ),
              :Result(),
    ),);
  }
}

hello guys,
I am here with a dart program problem,
please help me out
I am having error at:

Quiz(answerQuestion: _answerQuestion,questions: _questions,            questionIndex:_questionIndex

A: Your Quiz constructor expect positional arguments, where you are  passsing as named arguments,
Do it like
 Quiz( _answerQuestion, _questions, _questionIndex ),

If you like to use named argument, change your Quiz constructor.
Check more about using using-constructors

A: I assume your Quiz widget has a constructor as follows:
Quiz(this.answerQuestion, this.questions, this.questionIndex)

These are using positional arguments. In your example however, you are trying to use named arguments. If you want to used named arguments, change your constructor to:
Quiz({required this.answerQuestion, required this.questions, required this.questionIndex})

A: It is because you have passed named arguments instead of positional arguments.
Quiz(
               _answerQuestion,
              _questions,
             _questionIndex
          ),


text:
Q: WIndows Phone Runtime app sms I need send sms from my app. I find many articles how to do that, but, not work for me.
        try
        {
            ChatMessage msg = new ChatMessage {Body = "C# is the best!!"};
            msg.Recipients.Add("number");
            ChatMessageStore cms = await ChatMessageManager.RequestStoreAsync();
            await cms.SendMessageAsync(msg);
        }
        catch (Exception e)
        {
        //TODO: There I want show user sms app, but do not know how
        }

I do not have permission to do that, in documentation I found I need cellularMessaging capability https://msdn.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations . But I do not have in visual studio this option I have Contacts, Internet, Locations and others here but not celllurar. I try add it handly, but not work to.
<Capability Name="cellular" />
<uap:Capability Name="cellular" />
...

How can I do that? I have windows phone 8.1 runtime app project. I want get work this on W10m and WP8.1

A: Sending SMS messages programmatically isn't available to everyone - you have to request special permissions to Microsoft to be able to do it (and it is usually restricted to high profile clients like mobile operators). See the following remark taken from https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.sms.smsdevicemessagestore.aspx

Note  This functionality is only available to mobile operator apps and Windows Store apps given privileged access by mobile network operators, mobile broadband adapter IHV, or OEM. For more information, see Mobile Broadband: Windows Store device apps.

However, you can call ChatMessageManager.ShowComposeSmsMessageAsync to tell the OS to show the native SMS composing app with the data you have already filled in - then the user will be able to confirm the message for sending.


text:
Q: Stop Video.JS falling back to Flash? I am using video.js to display a HTML5 video on my site. For some reason FireFox (v31, Mac) displays it as a fallback Flash video. I would rather this didnt happen and just showed an image instead as I am using CSS width: 100% to scale the <video> tag.
Does anyone know of a way to stop this from occurring?
My video.js is set up as such:
 <video class="video-js"
  controls autoplay preload="auto" width="auto" height="auto"
  data-setup='{"example_option":true}'>
 <source src="video/rad3.mp4" type='video/mp4' />
 </video>


text:
Q: How to custom render a ZF2 Collection with matching fieldset I've created a standard application using collections to map one to many relationships (without using Doctrine) pretty much the way it is being described in http://framework.zend.com/manual/2.2/en/modules/zend.form.collections.html and I have something like the following code:
class Person {
  protected $attrributes;
}

class Attribute {
  protected $attr1;
  protected $attr2;
}

I've created the AttributeFieldset and the matching AttributeForm required and I've added the AttributeFieldset on my PersonForm:
$this->add(
  array(
    'type' => 'Zend\Form\Element\Collection',
    'name' => 'attributes',
    'options' => array(
      'label' => _("Add person attribute"),
      'count' => 1,
      'should_create_template' => true,
      'allow_add' => true,
      'target_element' => array(
        'type' => 'Persons\Form\AttributesFormFieldset'
      )
    )
  ));

Calling the $this->formCollection() view helper will generate the default HTML for the collection and the data template to add new attributes dynamically via javascript as specified in the documentation.
However what I would like to accomplish is to have a table listing with all the existing attributes of the person, with an edit/delete option and create a modal window with the collection fieldset to add new attributes to the Person.
Imagine the following html:
Add new attribute

  <? foreach( $this->person->attributes as $attribute ): ?>

      <?= $attribute['attr1']; ?>

        Edit | Delete

  <? endforeach; ?>

I know I can skip the formCollection entirely and add <input type="hidden"> tags the way ZF2 Collection would expect them (e.g. attribute[0][attr1] etc) on each row I add to my table and have the form created dynamically but I am guessing that I will be missing out on the ZF2 InputFilters.
Is there a better way to accomplish this? Has anyone done it before?

A: Working with Collections and requiring custom Markup is annoying. But it's not difficult:
$collections = $form->get('collection-element');
echo '
'
// render thead and tbody open if needed
foreach ($collections as $col) : ?>

        <?php echo $this->formInput($col->get('input-from-collection-name'); ?>
        <?php echo $this->formInput($col->get('other-input-from-collection-name'); ?>

<?php endforeach;
echo '
';

It is as simple as that. It's just annoying. Furthermore going by the default examples within configuration: the easiest way to add a template for additional elements is to just render the form once, then copy the generated HTML and then just paste this into your data-template.


text:
Q: Limit definition of second derivative in vector spaces Given the second derivative of a function on $\Bbb R$ can be written as $$f''(x) = \lim_{h\to0} \frac{f(x+h) - 2f(x) + f(x-h)}{h^2}$$
then in analogy to how we generalize the first derivative, could we say a function $f: \Bbb R^m \to \Bbb R^n$ is twice differentiable at $x$ if there exists a bilinear function $B$ such that $$\lim_{h\to 0} \frac{\|f(x+h)-2f(x)+f(x-h)-B(h,h)\|_{\Bbb R^n}}{|\langle h,h\rangle|} = 0$$ where $\langle \cdot, \cdot\rangle$ is the Euclidean norm on $\Bbb R^m$?  Then $B$ would be the second derivative?

A: The trouble with that approach is that
$$
\lim_{h\to0} \frac{f(x+h) - 2f(x) + f(x-h)}{h^2}
$$
may exist even if the function has no second derivative at $x$. Consider for example $f(x)=|x|\,x$ and $x=0$.


text:
Q: GCP Internal Load Balancer with ngnix ingress controller as nodeport : Connection Refused Background:
We hosted application in a GKE cluster, the application running on the GKE cluster has an ingress resource containing the rules to point to our application services. We are using ingress-nginx as the ingress controller for this cluster..
We have now created a GCP Internal Load Balancer(TCP) to point to the nodeport where the ingress-controller service is listening.
(Note: nginx ingress controller service" is of type node port)

*

*When we try to access application with http://ILB-IP:80 (http-port), it throws connection refused exception but gets a desired response when we access directly with nodeport http://ILB-IP:31380 (nodeport)

*When we give ingress service as type load balancer, GCP creates an ILB in the background.
In this case application is accessible over http port and all the request is being served.
Can anyone help us to figure out when we explicitly creates ILB and sends the request, why application is not accessible when we are hitting the ILB front end on http port while the same is accessible when ILB front end is ILB-IP:?
Thanks in advance!

A: The ingress controller needs to be configured as type:LoadBalancer as described in this help center article, which will create an external LB to route the traffic to the services that are exposed via an Ingress resource, which is the expected way to do it.
When exposing the ingress controller as type:NodePort then the service is accessible on each Node's IP at a static port as explained in here.

A: Over discussion with google support came to know that service type as LoadBalancer creates an IP table entry on each nodes, which allow traffic to redirect from port 80 to the defined node port.
So, if our use-case requires to create ILB explicitly and our application to be accessible over Node Port,
Then "we have to manually edit the IP tables on each kubernetes node in order to traffic to be redirect from the port 80 to the node port"

A: Checkout this : https://medium.com/google-cloud/internal-load-balancing-for-kubernetes-services-on-google-cloud-f8aef11fb1c4
GCP has started supporting internal LB creation for K8S services.


text:
Q: Why am i getting Error inflating class fragment in my android test? When i run my application i receive no errors, but when i try to run a test using the activity that includes the fragment i receive the inflation error.
I have been trying to resolve this for the past few hours and i am getting no where.
This is my fragment part of my xml.
<fragment
    android:layout_marginTop="30dp"
    android:layout_gravity="center_horizontal"
    android:layout_width="300dip"
    android:layout_height="300dip"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    />

And this is the test that fails.
public class testResultsActivity extends ActivityUnitTestCase<ResultsPage>
{

ResultsPage resultsPage;
public testResultsActivity()
{
    super(ResultsPage.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();
    Intent intent = new Intent(getInstrumentation().getTargetContext(),
            ResultsPage.class);
    startActivity(intent, null, null);
    resultsPage = getActivity();
}

@SmallTest
public void testResultsPage()
{
    assertNotNull(resultsPage.findViewById(R.id.map));
    assertNotNull(resultsPage.findViewById(R.id.ratingBar));
}

}

Can anyone tell me what is actually causing this and how i can go about fixing/ avoiding it?


text:
Q: Want to display error message if value increases max value in kendo numeric textbox I have a kendo numeric textbox. I have set the Min value to that as 1 and Max value as 31.If I enter a value greater than 31 I want to display an error message that "value must be between 1 and 31".If You enter greater value the widget will round it to the max value. So if You enter a value of 50 with the keyboard and lose focus from the input or save the form, the value will be rounded to the max value of 31.
I want when You enter a greater value in the widget text box an error message to be displayed. Here is my code:
        @(Html.Kendo().NumericTextBox<int>()
        .Name("month_day_1")
        .Format("#")
        .Min(1)
        .Max(31)
        .Events(evnt => evnt.Change("Change"))

Can anyone please tell me how to Implement that.I tried to apply the condition on change event of kendo numeric textbox.But I got the error as  change is not defined on console.
Here is my javascript function:
    function Change(e) {
    debugger;
    var numerictextbox = $("#month_day_1").data("kendoNumericTextBox");
    var value = numerictextbox.value();

    if (value > 31) {
        alert("Month Day value must be between 1 and 31");
        return false;
    }
}
      )

A: This should do exactly what you need:
    @(Html.Kendo().NumericTextBox<int>()
    .Name("month_day_1")
    .Format("#")
    .Min(1)
    .Events(e => e.Change("ChangeInput"));

function ChangeInput(e) {
    var value = this.value;
    //This should work too
    //Using jQuery --> to use, delete value = this.value and uncomment the line below
    //var value = $("#month_day_1").val();

    if (value > 31) {
        alert("Month Day value must be between 1 and 31");
        return false;
    }
}

Since you are in a event called by the input itself, the keyword this refers to the input. Retrieving the value with this.value should work. Make sure your JavaScript is on the page and loaded.


text:
Q: Как спарсить массив строк к нужному типу? Пишу метод, который будет получать массив строк и проверять их на некоторые типы, есть идея как реализовать логику, но кажется она не очень удачна. Вот пример моего кода:
private Type GetColumnType(List<string> columns)
{
    int matches = 0;
    foreach (var col in columns)
    {
        if (!DateTime.TryParse(col, out var res))
            break;
        else
            matches++;
    }
    if (matches == columns.Count)
        return typeof(DateTime);
}

Идея в том что бы проверять сначала на DateTime, потом на int, потом на double. И если ничего из этого не получится оставлять строку.
Мне не нравится, что получается простыня if'ов. Может быть, есть какая то идея по-лучше?

A: bool areAllDateTime = columns.Any(x => !DateTime.TryParse(x, out _));

И т.д.


text:
Q: Terminating thread on DLL unload I'm trying to write a DLL plug-in for a third-party software.In the plug in i'm creating a thread in an initialization function which is called by the hosting program. However, there is no shutdown routine in which I could properly terminate the thread. I'm tried this code:
DLL_EXPORT void InitFunction() // is called by the host application
{
    myThread = std::move(std::thread{myThreadFunction});
}
bool WINAPI DllMain( HINSTANCE hDll, DWORD fdwReason, LPVOID lpvReserved )
{
    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
    {
        DisableThreadLibraryCalls(hDll);
    }   break;
    case DLL_PROCESS_DETACH:
    {
        IsRunning.store(false); // tell the thread it's time to terminate;
        if(myThread.joinable())
            myThread.join();
    }break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    }
    return true;
}

I know this won't work, because windows would call DllMain upon thread termintation, but the DllMain is still running and therefore would deadlock. I tried using DisableThreadLibraryCalls() in different places in the Dll, but that didn't work either. So, How can I terminate the threads in my DLL properly?


text:
Q: Is webRTC codes already in the chromium codes? I'm trying to study webRTC and want to learn about how it encodes and transport the media stream.
Are codes of this part of webRTC already included in the chromium source codes?
http://code.google.com/p/chromium/wiki/LinuxBuildInstructions
Thanks~!

A: yes and no.

*

*The core of webrtc (including all the transport) is in the third party libwertc code, you can find information at webrtc.org.

*The codec and other libraries are shared with Chrome, and libwebrtc import a copy of chromium when building from source. THe exact list of libs that are shared are in this file

*The "capturer" is in the chrome code, more info there.


text:
Q: How to define a section(subsection) with custom background colorpage? Is it possible to redefine certain \section or \subsection to have custom pagecolor?
There are certain solutions like:
How to change the background color only for the current page?,
underline and background color for section or subsection
Change background color for only a section of the page?
and so on.
However, this does not quite solve what I want. Some of these solutions need predefined color boxes at fixed positions etc.
What would be nice to have is, whenever this section (say \newsection) starts, the page color from that point onwards including the section title becomes different until the section ends (which means a new normal \section starts. Basically within the environment of the \newsection ). For that, the whole page does not need to be a different color and the texts in this \newsection might continue over the next page and so does the background color.
The complete page in the range of \newsection can have a different background including possibly the page numbers, left-right margins, etc. or, it will also be sufficient to have the text and equations area in \newsection.
The second example link above is much similar but that is only on the name of the section not on the content of the section.

A: You can do this with snugshade of frame package. You need to define the desired color just before the use of snugshade.  This way yo can change color for all one section or one fraction of this one. You can apply this method to a chapter. Here is un example of code:
\documentclass[10pt,a4paper]{book}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[italian]{babel}
\usepackage{graphicx,color,framed,lipsum}
\definecolor{shadecolor1}{RGB}{236,236,236}
\begin{document}
    \chapter{Test chapter}
    \begin{oframed}
        \lipsum
    \end{oframed}
\definecolor{shadecolor}{RGB}{236,236,236}
    \begin{snugshade}
        \section{Uno}
        \lipsum[1-3]
    \end{snugshade}
\section{Due}
\lipsum[5-7]
\definecolor{shadecolor}{RGB}{124,124,0}
\begin{snugshade}
    \section{Tre}
    \lipsum[10-15]
\end{snugshade}
\definecolor{shadecolor}{RGB}{255,0,0}
\begin{snugshade}
    \lipsum[7]
\end{snugshade}
\section{Quattro}
\lipsum[20-21]
\end{document}

This is the result:


text:
Q: Find and get bold text in richtextbox C# Hi I'm new to C# and I need to find those text that is on bold/italic or undderline in my richtextbox. Any idea how?
The only thing I know is get using contains, but is there any way I can get it correctly.
richTextBox2.Text = browser.Div(Find.ByClass("GWTCKEditor-Disabled") && Find.ByIndex(2)).GetAttributeValue("outerHTML");

                if (richTextBox2.Text.Contains(@"<b>"))
                {

                    BoldUnderlineItalic = 0;
                }


text:
Q: How to programmatically resize process windows in Windows 10? I'm using python to open 4 videos at once with vlc and I want them to be resized automatically in each quarter of the screen (as it happens when you drag the window in the corner).
I'm using the Popen method of the subprocess library as follows:
for i in range(0,4):
    p = subprocess.Popen(['vlc location','file name'])
p.wait()

So far the videos open but I can't figure it out how to pin them in the corners like this:

A: If you are going to use the Popen subprocess method as I did you will have to remove p.wait() because it will wait for the video to end before running anymore code (it's putting the processes in a queue instead of threading them).
With the help from martineau and the answer he provided I used the following (after installing the pywin32 for python 3.5):
import pywintypes
import win32gui

displays = [[-10,0,980,530],
        [954,0,980,530],
        [-10,515,980,530],
        [954,515,980,530]] #these are the x1,y1,x2,y2 to corner all 4 videos on my res (1920x1080)

def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        print(win32gui.GetWindowText(hwnd)) #this will print all the processes title
        if name in win32gui.GetWindowText(hwnd): #it checks if the process I'm looking for is running
            win32gui.MoveWindow(hwnd,i0,i1,i2,i3,True) #resizes and moves the process

win32gui.EnumWindows(enumHandler, None) #this is how to run enumHandler

The x1,y1,x2,y2 might be different for your processes but these work just fine for vlc media player. I hope I was clear enough but if you don't get it done you should definitely check the answer provided by martineau.