text:
Q: How to add a row client side to radGrid I have a Telerik RadGrid, binded client side via a web service which returns me a list of JSON objects. The grid is grouped by Category Name, under each Category are items under the latter. If I call the page, initially, let's say there are 10 items under 3 groups, they are displayed correctly.
I have a custom group header which is generated on on the server side (not sure how to generate it on the client side but this is another question... if you have any easy answer, i'll be glad to hear from you)
I have pageLoad to bind the datasource, onRowDataBound, which updates the control for each row from the JSON list. On first load, it is working great. Now I have a feature to add an item to this list. When adding, it calls the web service which returns me a new list with the new item grouped under its own Category.
Now the updateGrid callback is called to fill the grid, and again it goes through the onRowDataBound on Client side. At some point when it reaches row 11 it can no longer find the controls to add, I'm guessing since previously we didnt have 11 rows. Am I missing something?
How would I create the new row?
Code:
function pageLoad(sender, eventArgs) {
    console.log('pageLoad');
    var tableView = $find("<%= grdSelectedList.ClientID %>").get_masterTableView();
    ApplicationLayer.WebServices.ShoppingListWS.GetData(updateGrid);
}

function rowDataBound(sender, args) {
    var gridItem = args.get_item();
    var record = args.get_dataItem();

    var lblItemDescription = args.get_item().findElement("lblItemDescription");
    var btnDeleteItem = args.get_item().findControl("btnDeleteItem");
    var hidElementId = args.get_item().findElement("hidElementId");
    var btnPriceStatus = args.get_item().findControl("btnPriceStatus");
    var btnDecrementQty = args.get_item().findControl("btnDecrementQty");
    var txtQty = args.get_item().findControl("txtQty");
    var btnIncrementQty = args.get_item().findControl("btnIncrementQty");
    var cmbSizeChoices = args.get_item().findControl("cmbSizeChoices");
    var lblSizeDescription = args.get_item().findElement("lblSizeDescription");

    console.dir(lblItemDescription);
    lblItemDescription.innerHTML = record.ItemName; // Error on this because lblItemDescription returns >null (only on the newly added Row)  when adding new item
    btnDeleteItem.set_commandArgument(record.ItemName.trim() + '|' + record.ListId + ',' + >record.ElementId + '|' + hidElementId.id);
    hidElementId.value = record.ElementId;

    if (record.ItemId == "0") {
        btnPriceStatus.set_text("Item not found in database");
        btnPriceStatus.set_enabled(false);
    }
    else if (record.StoreId != "0" && record.StoreName != "") {
        btnPriceStatus.set_text("Selected Deal from " + record.StoreName);
        btnPriceStatus.set_enabled(false);
    }
    else if (record.PriceStatus == "1") {
        btnPriceStatus.set_text("Deals Found!");
        btnPriceStatus.set_enabled(false);
    }
    else {
        btnPriceStatus.set_visible(false);
        btnPriceStatus.set_text("No Deals found (Click for suggestions)");
        btnPriceStatus.set_enabled(true);
        btnPriceStatus.set_commandArgument(record.ItemName + ',' + record.ElementId);
    }
    txtQty.set_value(record.Quantity);

    if (!IsAddedButton(btnDecrementQty.get_id())){
        btnDecrementQty.add_clicked(function (btnDecrementQty, args) { ChangeQty(btnDecrementQty, args, >"D," + record.ElementId + "," + ((record.PerPound == "1") ? "Y" : "N") + "," + txtQty.get_id() + "," + >btnDecrementQty.get_id() + "") });
        eventsButton[eventsButton.length] = btnDecrementQty.get_id();
    }
    if (!IsAddedButton(txtQty.get_id())){
        txtQty.add_blur(function (txtQty, args) { ChangeQty(txtQty, args, "Q," + record.ElementId + "," + >((record.PerPound == "1") ? "Y" : "N") + "," + txtQty.get_id() + "," + btnDecrementQty.get_id() + "") });
        eventsButton[eventsButton.length] = txtQty.get_id();
    }
    if (!IsAddedButton(btnIncrementQty.get_id())){
        btnIncrementQty.add_clicked(function (btnIncrementQty, args) { ChangeQty(btnIncrementQty, args, >"I," + record.ElementId + "," + ((record.PerPound == "1") ? "Y" : "N") + "," + txtQty.get_id() + "," + >btnDecrementQty.get_id() + "") });
        eventsButton[eventsButton.length] = btnIncrementQty.get_id();
    }

    scString = record.SizeChoices;
    scStringArray = scString.split(',');

    if (scString != "" && scStringArray.length > 1) {
        cmbSizeChoices.set_visible(true);
        lblSizeDescription.visible = false;
        cmbSizeChoices.clearItems();
        for(i=0; i < scStringArray.length; i++){
            var cmbItem = new Telerik.Web.UI.RadComboBoxItem();
            cmbItem.set_value(scStringArray[i].split('|')[0]);
            cmbItem.set_text(scStringArray[i].split('|')[1]);
            cmbSizeChoices.get_items().add(cmbItem);
        }

        if (!IsAddedButton(cmbSizeChoices.get_id())){
            if (record.SizeChoiceID != "" && record.SizeChoiceID != "0") {
                var itm = cmbSizeChoices.findItemByValue(record.SizeChoiceID);
                if (itm != null) itm.select();
            }
            cmbSizeChoices.add_selectedIndexChanged(function (cmbSizeChoices, args) { >ChangeItemSize(cmbSizeChoices, args, record.ElementId) });
            cmbSizeChoices.add_onClientFocus(function (cmbSizeChoices, args) { >SetCurrentCombo(cmbSizeChoices, args) });
            eventsButton[eventsButton.length] = cmbSizeChoices.get_id();
        }
    }
    else if (scString != "" && scStringArray.length  == 1) {
        cmbSizeChoices.set_visible(false);
        lblSizeDescription.visible = true;
        lblSizeDescription.innerHTML = scStringArray[0].split('|')[1];
    }
    else {
        cmbSizeChoices.set_visible(false);
        lblSizeDescription.visible = false;
    }
}

function updateGrid(result, userContext) {
    var tableView = $find("<%= grdSelectedList.ClientID %>").get_masterTableView();
    alert('updateGrid');

    console.dir(userContext);
    console.dir(result);

    tableView.set_dataSource(result);
    tableView.dataBind();
    var grid = $find("<%= grdSelectedList.ClientID %>");
    grid.repaint();
}

function btAddItemPlus_Clicking(sender, eventArgs) {
    var ajaxManager = $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>");
    var txtAddItem = $find("<%= txtAddItem.ClientID %>");
    var args;

    var tempVal = txtAddItem.get_value();
    tempVal = tempVal.replace(/[^a-zA-Z 0-9]+/g, '');

    var tempTxt = txtAddItem.get_text();
    tempTxt = tempTxt.replace(/[^a-zA-Z 0-9]+/g, '');

                //Adds the item calling the WebService , it returns a new list
    args = 'AddItemByID,' + tempVal;
    ApplicationLayer.WebServices.ShoppingListWS.AddItemByID(tempVal, tempTxt, updateGrid, onFailed, args);

    txtAddItem.set_text('');
    txtAddItem.clearItems();
    eventArgs.set_cancel(true);
}

function ExpandMe(n, args) {
    var type = args.target.tagName.toLowerCase();
    if (type != "input" && type != "a") {
        console.log('clicked');
        $(n).children()[0].children[0].click();
    }
}

Markup:
<telerik:RadGrid ID="grdSelectedList" runat="server" AutoGenerateColumns="False"
CellSpacing="0" GridLines="None" ShowHeader="False" Style="outline: none;" EnableViewState="false"
OnNeedDataSource="grdSelectedList_NeedDataSource"
OnItemCommand="grdSelectedList_ItemCommand" OnItemDataBound="grdSelectedList_ItemDataBound"
Height="493px" Width="595px" Skin="Default" EnableEmbeddedSkins="false" CssClass="grdSelectedList">
<ClientSettings AllowGroupExpandCollapse="True">
    <Selecting AllowRowSelect="True" />
    <Scrolling AllowScroll="True" UseStaticHeaders="True" ScrollHeight="493px" />
    <ClientEvents OnRowClick="grdSelectedList_RowClick" OnRowDataBound="rowDataBound" />
</ClientSettings>
<MasterTableView DataKeyNames="AccountId, ItemId, ListId, ElementId, DealId" ClientDataKeyNames="AccountId, ItemId, ListId, ElementId, DealId, CategoryName"
    TableLayout="Fixed" GroupLoadMode="Client">
    <GroupByExpressions>
        <telerik:GridGroupByExpression>
            <SelectFields>
                <telerik:GridGroupByField FieldName="CategoryName" />
            </SelectFields>
            <GroupByFields>
                <telerik:GridGroupByField FieldName="CategoryName" />
            </GroupByFields>
        </telerik:GridGroupByExpression>
    </GroupByExpressions>
    <NoRecordsTemplate>
        This list is empty.

        Click in "Add an Item" or "Browse Aisles" to add items to this list.
    </NoRecordsTemplate>
    <Columns>
        <telerik:GridBoundColumn FilterControlAltText="Filter CategoryCol column" UniqueName="CategoryCol"
            DataField="CategoryName" Groupable="true" Visible="False">
        </telerik:GridBoundColumn>
        <telerik:GridTemplateColumn FilterControlAltText="Filter DescriptionCol column" UniqueName="DescriptionCol"
            HeaderStyle-Width="350px">
            <ItemTemplate>

                    <asp:Label ID="lblItemDescription" runat="server" CssClass="blackHyperlink"></asp:Label>

                    <telerik:RadButton ID="btnPriceStatus" runat="server" UniqueName="PriceStatusColumn"
                        OnClientClicking="SuggestSubItems" BackColor="Transparent" ButtonType="LinkButton"
                        CssClass="dealFound" BorderStyle="None">
                    </telerik:RadButton>

            </ItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn UniqueName="QtyCol" HeaderStyle-Width="78px">
            <ItemTemplate>

                        <telerik:RadButton ID="btnDecrementQty" runat="server" CommandName="DecrementQty"
                            Width="17" Height="20" AutoPostBack="false">
                            <Image ImageUrl="../Images/btGrdMinus.gif" />
                        </telerik:RadButton>

                        <telerik:RadTextBox ID="txtQty" runat="server" CssClass="txtQtyInput" ViewStateMode="Disabled">
                        </telerik:RadTextBox>

                        <telerik:RadButton ID="btnIncrementQty" runat="server" CommandName="IncrementQty"
                            Width="17" Height="20" AutoPostBack="false">
                            <Image ImageUrl="../Images/btGrdPlus.gif" />
                        </telerik:RadButton>

            </ItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn UniqueName="QtyCol" HeaderStyle-Width="105px">
            <ItemTemplate>
                <telerik:RadComboBox ID="cmbSizeChoices" runat="server" Width="98px">
                </telerik:RadComboBox>
                <asp:Label ID="lblSizeDescription" runat="server"></asp:Label>
            </ItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn UniqueName="DelCol">
            <ItemTemplate>
                <telerik:RadButton ID="btnDeleteItem" runat="server" CommandName="DeleteShoppingListItem"
                    OnClientClicking="ConfirmDeleteItem" Width="18" Height="20" AutoPostBack="false">
                    <Image ImageUrl="..\Images\icoDeleteRedX.gif" />
                </telerik:RadButton>
                <asp:HiddenField ID="hidElementId" runat="server" />
            </ItemTemplate>
        </telerik:GridTemplateColumn>
    </Columns>
</MasterTableView>

A: We are doing this by having a row in a hidden table with all of the input elements setup there. When the user clicks the "Add" button, we do a simple append of that row to the thead of the RadGrid. This makes it the top most row and allows them to enter with all the validation in place. When they click save, ajax fires off the webservice to save and then the update is called to rebind the grid. This preserves everything quite well.


text:
Q: I need to download a lot of images in Unity but my app freezes on generating Sprite Here it is my code:
https://pastebin.com/n4dQf7WW
Basically my problem is the fact that I download something like 10/15 images in one time to fill my homepage. But generating all these images will freeze the app on both iOS and Android.
More facts:
- On iOS the download won't start immediately, on Android does.
- I used the UnityWebRequest functions, but on iOS it won't work concurrently.
- On Android it works as it should be, but when it comes to create the Sprite/Texture it freezes until it's finished.
So what I'm asking is if there is a way to handle better this situation (even with third-party library both paid and free).
I think the problem is here on the WebClient_DownloadDataCompleted function:
 var texture = new Texture2D(2, 2);
        texture.LoadImage(imageBytes);
        Rect rec = new Rect(0, 0, texture.width, texture.height);
        var spriteToUse = Sprite.Create(texture, rec, new Vector2(0.5f, 0.5f), 100);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Continuity from below for regular outer measures. We define an outer measure in a set $X$ as a function $\mu: \mathcal{P}(X) \to [0,\infty] $ that satisfies:

*

*$\mu(\emptyset) = 0$;

*$A \subset B \Rightarrow \mu(A) \leq \mu(B)$;

*$\mu(\bigcup A_n) \leq \sum \mu(A_n)$ for $(A_n) \subset \mathcal{P}(X)$.

We say that a subset $A \subset X$ is $\mu$-measurable if
$$ \mu(B) = \mu(B\cap A) + \mu(B \setminus A), \, \forall B \subset X, $$
and we denote the collection of all $\mu$-measurable sets by $\sigma(\mu)$.
Besides, if an outer measure satisfies
$$ \forall A \subset X, \, \exists E \in \sigma(\mu), \, A \subset E, \, \mu(A) = \mu(E), $$
we say that $\mu$ is regular.
I'm trying to proof the following problem

If $\mu$ is a regular outer measure and $(E_n)$ is an increasing sequence of subsets of $X$, then $\mu(\bigcup E_n) = \lim \mu (E_n)$.

The above problem is true if each $E_n$ is a $\mu$-measurable set. I'm trying to use this fact and the regularity of $\mu$ to proof that it holds. Well, the result is true if $\mu(E_n) = \infty$ of some $n$.
Then, take (E_n) an increasing sequence of subsets of $X$ with $\mu(E_n) < \infty.$ I've tried taking measurable sets $F_n$ such that $E_n \subset F_n$ and then take the unions of such $F_n$ to be an increasing sequence of measurable sets. However, I couldn't get anywhere.
Help?

A: You have taken the $F_n$ as measurable sets with $E_n\subseteq F_n$ such that $\mu(E_n)=\mu(F_n)$ through regularity. Moreover without loss of generality you can assume that the $F_n$ are an increasing sequence. Indeed, you can increase $F_n$ by redefining it as its union with $F_{n-1}$. The regularity property holds for this union still since
$$ \mu(F_n\cup F_{n-1}\setminus E_n)\leq \mu(F_n\setminus E_n)+ \mu(F_{n-1}\setminus E_n)\leq \mu(F_n\setminus E_n)+\mu(F_{n-1}\setminus E_{n-1})=0.$$
Then you have
$$ \bigcup_{n=1}^\infty E_n \subseteq \bigcup_{n=1}^\infty F_n,$$
so you can use property 2 of your outer measure to get
$$ \mu\left(\bigcup_{n=1}^\infty E_n\right) \leq \mu\left(\bigcup_{n=1}^\infty F_n\right)=\lim_{n\to\infty}\mu(F_n)=\lim_{n\to\infty}\mu(E_n),$$
with the equalities following from your observation that the claim holds for measurable sets and the regularity condition. To get the lower inequality, note that for each $n$ you trivially have $E_n\subseteq \bigcup_{j=1}^\infty E_j$ and so by property 2 of your outer measure
$$\mu(E_n)\leq \mu\left(\bigcup_{j=1}^\infty E_j\right),$$
taking the limit $n\to\infty$ then gives the result.


text:
Q: Importing Tilemill produced mbtiles to CouchDB I'm using MapProxy to seed a CouchDB with tile images on a FreeBSD server.
My workflow is Tilemill -> mbtiles export -> mapproxy seed -> CouchDB.  For zoom levels 10 - 17, rendering takes ~ 2-3 days, but produces a quite small db file @ ~2mb.  I attribute this to the large spaces with no data and the use of link_single_color_images: true
In an effort to speed the rendering process up, I have tried rendering with mapnik.xml as my source instead of the mbtiles produced by Tilemill.  All good with a tremendous speed up, but at the cost of a database that is 20x larger due to MapProxy producing a tile for every z/x/y.  Most of the thousands of tiles produced are transparent with no data.
Aka link_single_color_images: true does not seem to be working with Mapnik source, but does with mbtiles as a source.
Is there a way to use link_single_color_image with Mapnik?

A: So completely changed my workflow and I have compact couchdb databases in a matter of seconds/minutes from mbtiles.  Reduced Tilemill -> Couchdb rendering by days.
New workflow:
Tilemill -> mbtiles -> cdbtiles -> couchdb
Using more of the great open-source software by MapBox et al (https://github.com/mapbox and mapbox.com)
Couple of gotchs to installing cdbtiles, at least for my PCBSD/FreeBSD 10.0 system.
See: https://www.npmjs.org/package/cdbtiles or the github
npm install cdbtiles doesn't work, use git clone as below.  Had to make ln -s python2 python for mbtiles install or fix the python env
Install - FreeBSD 10.0:

*

*install node

*install npm (separate in FreeBSD ports)

*setenv CXX clang++

*setenv CC clang

*install devel/gmake

*npm install tilelive -g

*git clone https://github.com/mapbox/node-mbtiles.git

*cd to node-mbtiles dir

*npm install -g (gave me some grief, just fix errors - see above)

*git clone https://github.com/vsivsi/cdbtiles.git

*cd to cdbtiles dir

*npm install -g

see: https://www.npmjs.org/package/cdbtiles
Use cmd:
/usr/local/lib/node_modules/tilelive/bin/copy -s pyramid --minzoom=10 --maxzoom=18  "mbtiles:///Users/user/maps/Columbus.mbtiles" "cdbtiles://127.0.0.1:5984/columbus_tiles/"
Obviously sorted for your parameters and system.
Yields CouchDB of tiles same size as mbtiles imput file after compaction.
Access tiles from ol3:
my_tiles_couchdbLayerXYZ = new ol.layer.Tile({
    source: new ol.source.XYZ({url: "http://127.0.0.1:5984/xxxxx_cdbtiles
        /tile_{z}_{x}_{y}/tile"
    })
});


text:
Q: Проблема с require_once при подключении phpspreadsheet в Joomla!, PHP Пишу скрипт в своем простом модуле Joomla, который с помощью jQuery находит необходимый мне элемент по его классу, отправляет ajax запрос файлу php с содержимым тега, выполняет необходимую обработку и отправляет мне html разметку в определенный тег.
файл index.php:

Файл getTable.php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];

}
if($action == "test2"){
    echo '
Полученное содержимое 2
';
}
if($action == "test1"){
    echo '
Полученное содержимое 1
';
}
?>

Вот так если смотреть я получаю то, что мне нужно в теории. На практике же я использую библиотеку phpspreadsheet для Joomla!, которая позволяет читать Excel с помощью PHP.
Я научился в помощью нее читать и выводить Excel-содержимое. Но цель моя заключается в том, чтобы делать разную обработку, разных файлов в зависимости от содержимого класса panel-title.
Что я делаю, я в файл getTable.php подключаю phpspreadsheet, использую классы из этой библиотеки:
require_once JPATH_LIBRARIES . '/libraries/phpspreadsheet/phpspreadsheet.php';
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\IOFactory;

В соответствующее условие я заношу обработку:
if($action == "test2"){

    $file = 'test.xlsx';
    $excel = IOFactory::load($file);
    $excel->setActiveSheetIndex(18);

    $sheet = $excel->getActiveSheet();
    $html = '

      Колонка1
      Колонка2
      Колонка3

';
    foreach ($sheet->getRowIterator(2) as $row) {
        $html .= '
';
        $cellIterator = $row->getCellIterator();
        foreach ($cellIterator as $cell) {
            $value = $cell->getCalculatedValue();
            if(!empty($value)){
                if (Date::isDateTime($cell)) {
                    $value = date('d.m.Y', Date::excelToTimestamp($cell->getValue()));
                }

                $html .= ''.$value.'	';
            }
            // если дата, то преобразовать в формат PHP

        }
        $html .= '
';
    }
    $html .= '

';
    echo $html;
}

По итогу я разметку в переменной $html, но я ничего не получаю.
Я решил проверить подключение require_once и добавить в первый пример файла getTable.php:
Снова файл getTable.php
<?php
require_once JPATH_LIBRARIES . '/libraries/phpspreadsheet/phpspreadsheet.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];

}
if($action == "test2"){
    echo '
Полученное содержимое 2
';
}
if($action == "test1"){
    echo '
Полученное содержимое 1
';
}
?>

Теперь у меня даже рабочий пример не работает. Я понял, что все дело в require_once я выводил ошибки с помощью:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

Была одна ошибка и я ее устранил.
Как мне устранить данную проблему или хотя бы помогите разобраться в тех местах, где я неправ. Спасибо заранее!
PS: ссылка на библиотеку для joomla! : https://github.com/ivanramosnet/PhpSpreadsheet-Joomla-Library?ysclid=lb39sgwv28663316531

A: В общем проблема заключалась в файле библиотеки autoload.php, в строке defined( '_JEXEC' ) or die;. В общем, файл getTable.php не мог провериться Jooml'ой, что открывается из среды Joomla. Для решения проблемы я перед require_once в getTable.php вставил следующее:
if (!defined('_JEXEC')) {
    define( '_JEXEC', 1 );
    define('JPATH_BASE', dirname(__FILE__) );
}

Таким образом, я проверил наличие файла в корне Joomla! и не нарушил безопасности, можно было также просто убрать или закомментировать строку JEXEC...


text:
Q: Passing Data into a Custom View While In ForEach Iteration (SwiftUI) A background to the issue: I am creating a simple app which stores activity data in a struct. I have created a custom view called "CardView" (held in a separate file within the project) which is to appear onto a basic ContentView. The CardView is populated with Text labels which are to be bound to corresponding data within the aforementioned activity data struct. A ForEach handles the dynamic creation of these cards according to how many activity "items" exist. See following code...
struct ActivityItem: Identifiable, Codable {
let id = UUID()
let name: String
let description: String
let type: String
var amount: Int
}

class AppData: ObservableObject {
@Published var activites: [ActivityItem] {
    didSet {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(activites) {
            UserDefaults.standard.set(encoded, forKey: "Activites")
        }
    }
}

init() {
    if let foundActivities = UserDefaults.standard.data(forKey: "Activites") {
        let decoder = JSONDecoder()
        if let decoded = try? decoder.decode([ActivityItem].self, from: foundActivities) {
            self.activites = decoded
            return
        }
    }

    self.activites = []
}
}

struct ContentView: View {
@ObservedObject var appData = AppData()
@State private var showingAddActivity = false
@State private var showingMoreInfo = false

var body: some View {
    NavigationView {
        ZStack {
            Rectangle()
            .fill(Color(.gray))
            .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)

            ScrollView {
                VStack(spacing: 50) {
                    ForEach(appData.activites) { activity in
                        CardView(appData: self.appData)
                    }
                }
            }

// Below held in separate file
struct CardView: View {
@ObservedObject var appData: AppData
@State private var showingMoreInfo = false

var body: some View {
    ZStack {
        Rectangle()
            .fill(Color(.gray))
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .edgesIgnoringSafeArea(.all)
        RoundedRectangle(cornerRadius: 20)
            .fill(Color(.black))
            .frame(width: 325, height: 180)
        VStack {
            Text("Name")
                .font(.title)

            Text("Description")

            Text("Type")

            Text("Amount")
        }
        .sheet(isPresented: $showingMoreInfo) {
            Text("View")
        }
    }
}
}

The issue: Despite multiple attempts and countless hours and errors later through using @Binding and leveraging @Environmental, I cannot pass data from the current ActivityItem in the ForEach into the CardView to be used to replace the String placeholder in the Text labels (i.e. Name, Type, Amount). When trying to create and use bindings, such as something like $activity.name, it declares that "activity" cannot become a binding. What am I doing wrong? How, in the simplest way, can I get each activity to pass its data to the CardView struct, populate those Text labels and then create itself on the ContentView "main screen" and then repeat for all remaining objects in the ForEach iteration? Is there any important notes to keep in mind to avoid issues like this in the future? I must add that if I put the CardView code directly into ContentView and not call CardView() in the ForEach, I can easily refer to the data; it only becomes an issue when I use the CardView struct (a long term goal for reusability and less code clutter). Thank you for your help!

A: I assume you meant something like the following (tested with Xcode 12 / iOS 14)
struct ActivityItem: Identifiable, Codable {
var id = UUID()
var name: String            // << made `var` here and other to allow write
var description: String
var type: String
var amount: Int
}

class AppData: ObservableObject {
@Published var activites: [ActivityItem] {
    didSet {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(activites) {
            UserDefaults.standard.set(encoded, forKey: "Activites")
        }
    }
}

init() {
    if let foundActivities = UserDefaults.standard.data(forKey: "Activites") {
        let decoder = JSONDecoder()
        if let decoded = try? decoder.decode([ActivityItem].self, from: foundActivities) {
            self.activites = decoded
            return
        }
    }

    self.activites = []
}
}

struct ContentView: View {
@ObservedObject var appData = AppData()
@State private var showingAddActivity = false
@State private var showingMoreInfo = false

var body: some View {
    NavigationView {
        ZStack {
            Rectangle()
            .fill(Color(.gray))
            .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)

            ScrollView {
                VStack(spacing: 50) {
                    ForEach(appData.activites.indices, id: \.self) { i in
                        CardView(item: $appData.activites[i])  // binding here
                    }
                }
            }
        }
    }
}
}

// Below held in separate file
struct CardView: View {
@Binding var item: ActivityItem             // binding here
@State private var showingMoreInfo = false

var body: some View {
    ZStack {
        Rectangle()
            .fill(Color(.gray))
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .edgesIgnoringSafeArea(.all)
        RoundedRectangle(cornerRadius: 20)
            .fill(Color(.black))
            .frame(width: 325, height: 180)
        VStack {
            TextField("Name", text: $item.name)    // edit here
                .font(.title)

            Text("Description")

            Text("Type")

            Text("Amount")
        }
        .sheet(isPresented: $showingMoreInfo) {
            Text("View")
        }
    }
}
}

A: Swift 5.5 offers bindable collections, which allow the following implementation.
struct ActivityItem: Identifiable, Codable {
    var id = UUID()
    var name: String
    var description: String
    var type: String
    var amount: Int
}

class AppData: ObservableObject {
    @Published var activites: [ActivityItem] {
        didSet {
            let encoder = JSONEncoder()
            if let encoded = try? encoder.encode(activites) {
                UserDefaults.standard.set(encoded, forKey: "Activites")
            }
        }
    }

    init() {
        if let foundActivities = UserDefaults.standard.data(forKey: "Activites") {
            let decoder = JSONDecoder()
            if let decoded = try? decoder.decode([ActivityItem].self, from: foundActivities) {
                self.activites = decoded
                return
            }
        }
        // sample data
        self.activites = [ActivityItem(name: "Name1", description: "desc1", type: "type1", amount: 1),
                          ActivityItem(name: "Name2", description: "desc2", type: "type2", amount: 1)
        ]
    }
}

struct ContentView: View {
    @ObservedObject var appData = AppData()
    @State private var showingAddActivity = false
    @State private var showingMoreInfo = false

    var body: some View {
        NavigationView {
            ZStack {
                Rectangle()
                    .fill(Color(.gray))
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .edgesIgnoringSafeArea(.all)

                ScrollView {
                    VStack(spacing: 50) {
                        ForEach($appData.activites) { $activity in
                            CardView(item: $activity)
                        }
                    }
                }
            }

        }
    }
}

// Below held in separate file
struct CardView: View {
    @Binding var item: ActivityItem
    @State private var showingMoreInfo = false

    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color(.gray))
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.yellow)
                .frame(width: 325, height: 180)
            VStack {
                TextField("Name", text: $item.name)    // edit here
                    .font(.title)
                    .multilineTextAlignment(.center)
                    .textFieldStyle(.roundedBorder)
                Text("Description \(item.description)")
                Text("Type \(item.type)")
                Text("Amount \(item.amount)")
            }
            .sheet(isPresented: $showingMoreInfo) {
                Text("View")
            }
        }
    }
}


text:
Q: How to set a variable for test-connection to pull the ipv4address? I apologize for the terrible title, i had no clue how to word this.
I want to setup a script that when ran, it does a if-then command that outputs the computer name, if it failed or succeeded to connect, and what the IP is if connected.
So far what I have is:
    $computer1 = 'google.com'
    $computer2 = 'netflix.com'
if (Test-Connection "$computer1" -count 1 -Quiet) {"$computer1 connected"} else {"$computer1 failed"}
if (Test-Connection "$computer2" -Count 1 -Quiet) {"$computer2 connected"} else {"$computer2 failed"}

So that outputs:

Google.com connected
Netflix.com failed

How can I take it a step further so that when it returns it says something like:

Google.com connected "IPv4address"

where it shows the IPv4 address as well as connected and the computername?
almost like how when you originally do test-connection:
test-connection google.com

and that returns:
Source        Destination     IPV4Address

------        -----------     -----------
DOMINATOR     google.com      172.217.9.206
DOMINATOR     google.com      172.217.9.206
DOMINATOR     google.com      172.217.9.206
DOMINATOR     google.com      172.217.9.206

Reason im asking is because when a connection fails, it throws an annoying:
PS C:\Users\Andrew> Test-Connection netflix.com, google.com
Test-Connection : Testing connection to computer 'netflix.com' failed: Error due to lack of resources
At line:1 char:1
+ Test-Connection netflix.com, google.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (netflix.com:String) [Test-Connection], PingException
    + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

Test-Connection : Testing connection to computer 'netflix.com' failed: Error due to lack of resources
At line:1 char:1
+ Test-Connection netflix.com, google.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (netflix.com:String) [Test-Connection], PingException
    + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

Test-Connection : Testing connection to computer 'netflix.com' failed: Error due to lack of resources
At line:1 char:1
+ Test-Connection netflix.com, google.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (netflix.com:String) [Test-Connection], PingException
    + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

Test-Connection : Testing connection to computer 'netflix.com' failed: Error due to lack of resources
At line:1 char:1
+ Test-Connection netflix.com, google.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (netflix.com:String) [Test-Connection], PingException
    + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
DOMINATOR     google.com      172.217.13.78                                             32       14
DOMINATOR     google.com      172.217.13.78                                             32       14
DOMINATOR     google.com      172.217.13.78                                             32       15
DOMINATOR     google.com      172.217.13.78                                             32       17

and sure you can add "-quiet"
but then it just says:
False
True

Any help would be great cause im stumped

A: Here's one way to handle failures gracefully.
$targets = 'server1', 'server2', 'server3', 'dontexist'

$success = Test-Connection -ComputerName $targets -Count 1 -ErrorAction SilentlyContinue -ErrorVariable errors |
               Select-Object @{n='Server';e={$_.address}},IPv4Address,@{n='Result';e={'Successful'}}

$failed = $errors.exception.message |
              Where-Object {$_ -match "computer '(.+?)'"} |
                  Select-Object @{n='Server';e={$matches.1}},
                                @{n='IPv4Address';e={"N/A"}},
                                @{n='Result';e={'Failed'}}

$success + $failed


text:
Q: Nginx `location /` does not match `/some_path` Help me pls to configure nginx: I want nginx return index.html for all URLs like 10.10.256.142/, 10.10.256.142/some_path and 10.10.256.142/other_path/lala. Problem: currently it returns index.htmlonly for 10.10.256.142/ URL.
My current settings
listen 80;
server_name  10.10.256.142;
server_name_in_redirect  off;
resolver  127.0.0.1;

location / {
    error_page 405 =200 $uri;
    root   /some_path/project_dir;
    index  index.html index.htm;
}

location /websocket {
    # ....

A: For me, simplest solution would be:
root /some_path/project_dir;

location / {
    rewrite ^ /index.html break;
}

location /websocket/ {
    # ...
}

A: Just to complete the answer above and return static assets I had to write
root  /srv/www/betbull;
location / {
    if ($uri !~ (/assets/.*)) { # do not return index.html instead of static assets
        rewrite ^ /index.html break;
    }
}

UPDATE:
Better solution:
location / {
    try_files $uri $uri/ index.html$query_string
}


text:
Q: Been having issue with "Error: 'MenuController' is imported" I keep having this issue while I try to compile my flutter application
lib/view/screens/dashboard/dashboard_screen.dart:7:1: Error: 'MenuController' is imported from both 'package:flutter/src/material/menu_anchor.dart' and 'package:vale_ace_boy/controller/menu_controller.dart'. import 'package:vale_ace_boy/controller/menu_controller.dart';
How can I get this solved please
I've tried flutter clean and flutter pub get but nothing seems to be working

A: You probably created a class/widget called MenuController, which already exists in Flutter, so there is ambiguity between the two of them.
Rename your MenuController as something else, for example CustomMenuController.


text:
Q: Spying a method which is in the tested module To make it clear I'll 'draw' you a situation.
Module A(the same javascript file, at my case its reducer in ReactJS/Redux app) contains methods: First, Second
Im testing method First (inside which Second is called - and I want to check whether it has been called or not). So in pseudo code it looks like this:
creating a spy with sinon.spy(module1, 'Second')
invoking First()
checking whether its been called or not _createdSpy.should.have.calledOnce

The problem Ive encountered is that if the method Second is placed at the same module (file) as the First, it doesnt work (library doesnt detect if spy has been called). If I move it to the another file/module, it works just fine.
its by design or Im doing something wrong?
Im using sinon + chai + enzyme stack.


text:
Q: How to display Story in Storybook Summery
I"ve tried to implement Storybook in Nuxt.js application.
I successed to run Storybook. And I wrote index.vue and index.stories.ts.
But Storybook does not show any Story.

So I want to know how to actually display Story.
Show some code
index.vue
<template>
  <nuxt-link to="https://nuxtjs.org">
    NuxtJs
  </nuxt-link>
</template>

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'

@Component({})
export default class TestComponent extends Vue {}
</script>

index.stories.ts
import Test from './index.vue'

export default {
  component: Test,
  title: 'Components/Test'
}

export const Component = () => ({
  components: { Test },
  template: '<Test />'
})

Also I wrote ./storybook/config.js for settings.
import { configure } from '@storybook/vue';

const req = require.context('../components', true, /.stories.ts$/);
function loadStories() {
  req.keys().forEach(filename => {
    return req(filename)
  });
}

configure(loadStories, module);

Here is the actual repository. Please check.
https://github.com/jpskgc/nuxt-sample/tree/storybook-error

A: I resolved this problem by adding .storybook/main.js instead of .storybook/config.js.
module.exports = {
  stories: ['../components/**/*.stories.ts'],
};

https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-configure


text:
Q: Problems extending a circular array deque Greetings,
I'm trying to implement a Deque using a circular array that extends when the array gets full.  My problem seems to be that the array refuses to extend.  Either I am computing size() incorrectly or there is a problem with how I update my front and rear indices.  I've looked over it many times and I seem to figure this out.  Can anyone help?
public class ArrayDeque
    {
       public static final int INIT_CAPACITY = 8;   // initial array capacity
       protected int capacity;  // current capacity of the array
       protected int front;     // index of the front element
       protected int rear;      // index of the rear element
       protected int[] A;       // array deque

       public ArrayDeque( )      // constructor method
       {
          A = new int[ INIT_CAPACITY ];
          capacity = INIT_CAPACITY;
          front = rear = 0;
       }

        /**
         * Display the content of the deque
         */
        public void printDeque( )
        {
          for ( int i = front; i != rear; i = (i+1) % capacity )
              System.out.print( A[i] + " " );
              System.out.println();
        }
       /**
         * Returns the number of items in this collection.
         */
        public int size()
        {
            return (capacity - front + rear) % capacity;
        }
        /**
         * Returns true if this collection is empty.
         */
        public boolean isEmpty()
        {
            return front == rear;
        }
        /**
         * Returns the first element of the deque
         */
        public int getFirst() throws EmptyDequeException
        {
            if(isEmpty()){
                throw new EmptyDequeException("Deque is empty.");
            }
            return A[front % capacity];
        }
        /**
         * Returns the last element of the deque
         */
        public int getLast() throws EmptyDequeException
        {
            if(isEmpty()){
                throw new EmptyDequeException("Deque is empty.");
            }
            return A[(rear - 1) % capacity];
        }
        /**
         * Inserts e at the beginning (as the first element) of the deque
         * If array is full, extend array by doubling its capacity and insert element in new array
         */
        public void insertFirst(int e)
        {
            if(size() == capacity){
                int[] B = new int[2*capacity];
                for(int i = 0; i < size(); i++){
                    B[i] = A[i];
                }
                A = B;
            }
            int[] B = new int[capacity];
            for(int i = 0; i < size(); i++){
                B[i] = A[i];
            }
            A = B;
            for(int i = size(); i >= front; i--){
                A[i+1] = A[i];
            }
            A[front] = e;
            rear = (rear + 1) % capacity;
        }
        /**
         * Inserts e at the end (as the last element) of the deque
         * If array is full, extend array by doubling its capacity and insert element in new array
         */
        public void insertLast(int e)
        {
            if(size() == capacity){
                capacity *= 2;
                int[] B = new int[capacity];
                for(int i = 0; i < size(); i++){
                    B[i] = A[i];
                }
                A = B;
            }
            A[rear] = e;
            rear = (rear + 1) % capacity;
        }
        /**
         * Removes and returns the first element of the deque
         * Shrink array by half of current size N when number of elements in the deque falls below N/4
         * minimum capacity should always be 8
         */
        public int removeFirst() throws EmptyDequeException
        {
            if(isEmpty()){
                throw new EmptyDequeException("Deque is empty.");
            }
            else if(capacity >= 8){
                if(size() < capacity/4){
                    capacity /= 2;
                    int[] B = new int[capacity];
                    for(int i = 0; i < size(); i++){
                        B[i] = A[i];
                    }
                    A = B;
                }
            }
            int temp = A[front];
            A[front] = 0;
            front = (front + 1) % capacity;
            return temp;
        }
        /**
         * Removes and returns the last element of the deque
         * Shrink array by half of current size N when number of elements in the deque falls below N/4
         * minimum capacity should always be 8
         */
        public int removeLast() throws EmptyDequeException
        {
            if(isEmpty()){
                throw new EmptyDequeException("Deque is empty.");
            }
            else if(capacity >= 8){
                if(size() < capacity/4){
                    int[] B = new int[capacity/2];
                    for(int i = 0; i < capacity; i++){
                        B[i] = A[i];
                    }
                    A = B;
                }
            }
            int temp = A[rear - 1];
            A[rear] = 0;
            rear = (rear - 1) % capacity;
            return temp;
        }
    }  // end class

Test Input:
for(i = 1; i <= 100; i++)
   q.insertLast(i);
   q.printDeque();

for(i = 1; i <= 99; i++)
   k = q.removeFirst();
   q.printDeque();

Test Output: I've set up several print statements and the size always remains at 7 for some reason...
Exception in thread "main" A3.EmptyDequeException: Deque is empty.
    at A3.ArrayDeque.removeFirst(ArrayDeque.java:133)
    at A3.ArrayMain.main(ArrayMain.java:37)

A: Well, consider this...
If your max capacity is 8, then your queue can have 9 total size states: 0 1 2 3 4 5 6 7 and 8.
ANY_NUMBER % 8 can only have 8 states: 0 1 2 3 4 5 6 and 7.
This is homework (thanks for being honest about it) so I don't want to spoil it all for you, but this should point you in the right direction. Good luck!

A: Look at your insertFirst method, and what does it do when the array is full. Read the whole method, not only the first if block. Are you ever changing your capacity?


text:
Q: How to make sure that WorkManager cancels my Worker? It's mentioned in WorkManager documentation that cancelling a Worker is best-effort

WorkManager makes its best effort to cancel the task, but this is
  inherently uncertain--the task may already be running or finished when
  you attempt to cancel it

What if i have a use case that it's mandatory that the Worker gets cancelled upon calling one of the cancelling methods?

A: As you wrote WorkManager can only try with a best-effort to cancel a work. In particular, if a task is scheduled to run, and you cancel it, WorkManager will remove it from the schedule.
However, if the tasks it's already running, WorkManager cannot safely interrupt it. The best option is that you write your Worker class taking care of an external cancellation. This has been covered in the Working with WorkManager talk (around minute 15) recorded at the Android Developer Summit 2018.
To be a good citizen you can pool WorkManager using the method: ListenableWorker.isStopped(). You can combine this with the onStopped callback to cleanup your code when you or the OS request to stop the task.


text:
Q: Android check whether app reached background when user pressed Home Button? I am new to android and I need to know whenever App resumes from background I need to display a pass code lock screen I followed this link and able to get it but whenever I use to invoke camera intent or gallery pick intent App is going to background and lock screen is appearing instead I need to know whether App reached background on user home button press

A: Whitelist the "good" actions
I suggest you try thinking about it the other way around.  For the actions you want the user to take (like launch the camera, or pick from the gallery) you can white-list that action.
This way, if any other reason causes the app to go into the background (like the user getting a phone call) you can show the lock screen when they return.
When you start the camera or gallery activities you can define a custom requestCode and check for this when they return to your app via onActivityResult
Something like this:
private static final String MIME_TYPE = "image/*";
private static final int MY_GALLERY_REQUEST_CODE = 90210;

private void launchGallery()
{
    Intent i= new Intent();
    i.setType(MIME_TYPE);
    i.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(i, MY_GALLERY_REQUEST_CODE);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == MY_GALLERY_REQUEST_CODE)
    {
        //user is returning from the gallery picker
    }
    else
    {
        showLockScreenIfNeeded();
    }
}

@Override
protected void onResume()
{
    showLockScreenIfNeeded();
}

Also from: This other SO answer: onActivityResult() & onResume()
onActivityResult() should be called before onResume()
From the docs:

protected void onActivityResult (int requestCode, int resultCode,
  Intent data)
Since: API Level 1 Called when an activity you launched exits, giving
  you the requestCode you started it with, the resultCode it returned,
  and any additional data from it. The resultCode will be
  RESULT_CANCELED if the activity explicitly returned that, didn't
  return any result, or crashed during its operation. You will receive
  this call immediately before onResume() when your activity is
  re-starting.

A: You can use following method to check it
@Override
protected void onUserLeaveHint()
{
   super.onUserLeaveHint();
   // Put your code here
}

A: onResume() (or onStart()) cannot be used for your purpose since the callback is invoked whenever the activity becomes visible.
Instead of it, you can override onNewIntent(Intent) and then check whether Intent.FLAG_BROUGHT_TO_FRONT is set on the flag inside the intent.
That flag is automatically set by the Android system when the task where your activity is  brought from background to front (usually by pressing the app icon of an already-running app). This is NOT set when your activity is returned from another activity such as camera or gallery for attaching pictures. Note that in order to use the flag, you should set the launch mode of the activity to 'singleTask'. For details please refer to http://developer.android.com/reference/android/R.styleable.html#AndroidManifestActivity_launchMode.

A: Check the below code continuously that means u can use Timer class.
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<RunningTaskInfo> runningTasks = null;
    try {
        runningTasks = activityManager.getRunningTasks(1);
    } catch (Exception e) {

    }
    RunningTaskInfo runningTaskInfo = runningTasks.get(0);
    ComponentName topActivity = runningTaskInfo.topActivity;
if(topActivity.getPackageName().equals(your packagename)){
       S.o.p("fine");}
else{
       S.o.p.("application sent to background");}

A: I've found the way to overcome the issue I described with the @pjco solution.
To make it possible to show lock screen even when brought to background from third-party Activities, simply use FLAG_ACTIVITY_NO_HISTORY when starting these Activities:
Intent intent = new Intent(Intent.ACTION_PICK, Images.Media.INTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, REQCODE_PICK_GALLERY);


text:
Q: Is it possible to get a volatile field using reflection? Class<? extends Class> clazz = MyClass.class.getClass();
try {
    Field field = clazz.getDeclaredField("mInstance");
    field.setAccessible(true);
    looper = (Looper) field.get(this);
} catch (NoSuchFieldException e1) {
    e1.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
}

The field is declared like this:
private volatile Object mInstance;
I'm receiving a NoSuchFieldException.

A: This
Class<? extends Class> clazz = MyClass.class.getClass();

should be
Class<?> clazz = MyClass.class; // or Class<MyClass>

That is known as a class literal. The expression results in a Class object for the given type. Calling getClass() on a Class instance will return the Class instance for Class, not for MyClass.
(All this assumes that the field mInstance is declared in MyClass.)

A: You should use MyClass.class
Simple test would be run following code:
class A {
    public static void main(String[] args) {
        System.out.println(A.class.getClass());
        System.out.println(A.class);
    }
}

Output is:
class java.lang.Class
class A

Also see Retrieving Class Objects
Cheers !!


text:
Q: How to select all column in tables with count of certain column in SQL? Assuming that I have these column :

*

*Form_ID

*Product_ID

*Date

P.S : Each Form_ID can have more than 1 Product_ID , and I want to get all data sorted by number of occurence of Product_ID. I've tried some query like,
SELECT * , COUNT(Product_ID) AS indicator
from my_database.inv_table
GROUP BY (Product_ID)
ORDER BY indicator DESC

Any thoughts and help ? Thank you.

A: You could use Count(*) Over (Partition by Product_ID):
SELECT Form_ID, Product_ID, Date,
       Indicator = Count(*) Over (Partition by Product_ID)
FROM my_database.inv_table
ORDER BY Indicator DESC

You don't need to select the Indicator-column if you don't want, you can use Count(*) Over (Partition by Product_ID) also in the ORDER BY.
MSDN: https://msdn.microsoft.com/en-us/library/ms189461.aspx

A: Use a correlated sub-query to do the counting:
SELECT t1.*, (select COUNT(*) from my_database.inv_table t2
              where t1.Form_ID = t2.Form_ID) AS indicator
from my_database.inv_table t1
ORDER BY indicator DESC


text:
Q: What do the various journals and publications bodies offer for their subscriptions? I would like to abide by the site policies on not asking open-ended/chatty questions so if someone feels there is a better location or wording for this question, please feel free to modify it as appropriate.
I am normally a big fan of open source/open access work and I believe I have learned a great deal from such sources.  There is an open-access journal question here.  Nonetheless, there are times where I really do want a specific article that is not available through non-commercial means.  I am currently studying to return to school (in other words I don't have access to an institutional subscription) for a physics PhD and reading published work is becoming increasingly important to me.  As a result I am considering subscribing to one of the big publishing houses (Elsavier, ScienceDirect, Science, Nature, etc.).
Before I spend that kind of money, I would like to know what other physicists think of these organizations and who offers the best value.  If I decided to opt for a subscription, which would be the best?  Is a subscription even the best idea, or should I perhaps buy individual articles as needed?
PS - I know the answer to these questions depends on the area of interest, my interests lie in quantum field theories and the like, but feel free to answer for your particular area of expertise.

A: As you have mentioned already, I am all for the open culture when it comes to publishing. Most of the research is funded by the public and therefore should be accessible by the public! I am a researcher in Physics, so I read several papers everyday. My primary source of papers is arXiv. Even though I have access via a University network to various subscriptions, I am not a fan of subscription only journals. More to the point, I don't like it when authors don't make their papers freely available on places like arXiv; we are lucky to have such an open resource, making us the envy of many other disciplines. So my advice would be not to waste your money on any expensive subscriptions. You are not going to get too much for it. There are too many journals out there and you can't possibly subscribe to all of them. You can get 95% of the material you need from open sources. The rest you can perhaps buy on individual basis.
p.s. I don't mean this to be a rant. I just feel passionate about open source :-)

A: I fully agree with Omar's answer. But for the other 5% of the papers, you have other options beside buying them. You can ask the authors to send you a copy, and most do, even if it takes a few days for them to reply to you. Also, if you know anyone in a university, you could send them an email with the links you need and ask them to download them for you.

A: Indeed, without access to journal site licenses you tend to think twice about ordering an article that may not contain what you are looking

*

*Try to look first at Google Scholar. It often finds preprints or reprints on researchers' web site

*You may be better off buying individual articles instead of subscribing for a specific journal or publisher. Try to estimate how many articles you will order and from which journal and estimate the costs. Remember that each subscription provides access only to a single journal or publisher.

*Look for discounts and promotions. Note also that digital subscriptions are much cheaper than print subscrpitions.

*Some journals are subscribed to via society memberships, e.g., APS Publications, AAAS memberships (Science).


text:
Q: While using boost to generate a random int, faced with 'std::_Fill_in' called with unsafe parameters? I want to learn how to use boost library,and I install boost successfully.So I write a program like this.
#include "stdafx.h"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
int main(){
    boost::mt19937 gen;
    boost::uniform_int<>distribut(1, 10);
    boost::variate_generator<boost::mt19937 &, boost::uniform_int<>> die(gen, distribut);
    int x = die();
    return 0;
}

But it shows that 1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(2715): error C4996: 'std::_Fill_n': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
And it only happens when I include the file boost/random/mersenne_twister.hpp.
So I want to know how to handle this problem? If I need to use D_SCL_SECURE_NO_WARNINGS,how do I use it?
Thanks.


text:
Q: Python doesn't set Environment variables I've written a python application which can be set in development or production mode by using an environment variable. This variable can be passed as a CLI argument:
    if len(argv) >= 2:
        environ['DISCOVERY_ENV'] = argv[1]
    else:
        environ['DISCOVERY_ENV'] = 'development'

The problem now is that this environment is not being set. Which means if I've following code, it doesn't work:
if environ.get('DISCOVERY_ENV') == 'production':
    import adafruit_ads1x15.ads1015 as ADS
    from adafruit_ads1x15.analog_in import AnalogIn
    import busio
    import board

In this example the libraries will not being imported.
EDIT:
This does work on Windows but not on linux, my case: Rasbian OS.
Does anyone know why this doesn't work?
Thanks in advance!

A: By looking at your code, I think you are on micropython. If this is the case, according to the doc, environ is not implemented yet.
By quoting the doc, the suggestion seems to be the following:

Workaround: Use getenv, putenv and unsetenv


text:
Q: vagrant provisionning in packer build I would like to create a Vagrant box with Packer. For that I use a packer project on github : Packer ubuntu 14.04 LTS
As they are, the 'packer build' command run correctly and I can use my vagrant box normally. But I want to build a Vagrant box with my configuration and tools pre-install.
For that I create a new script sh file which is run in a provisioners scripts packer template.
  "provisioners": [
    {
        "execute_command": "echo 'vagrant'|sudo -S sh '{{.Path}}'",
        "override": {
            "virtualbox-iso": {
                "scripts": [
                    "scripts/base.sh",
                    "scripts/system.sh",
                    "scripts/vagrant.sh",
                    "scripts/python.sh",
                    "scripts/virtualbox.sh",
                    "scripts/docker.sh",
                    "scripts/test-perso.sh",
                    "scripts/cleanup.sh"
                ]
            }
        },
        "type": "shell"
    }
]

and the contain of this file :
#!/bin/bash -x

apt-get -y install aptitude
apt-get -y install nano
apt-get -y install apache2
apt-get -y install php5
apt-get -y install libapache2-mod-php5

All the packer build run correctly without errors. But when a create my Vagrant with this box and launch a cd /etc/apache2 it can't find this. No install of apache2 present.
Because when a run manually this command 'apt-get -y install apache2' on my vagrant, it return me

Impossible to open the file lock /var/lib/dpkg/lock - open (13: Permission not allowed)
  Impossible to lock the directory of administration (/var/lib/dpkg/). Have you the super-user privilege ?

I think have this problem because vagrant user that use for provisionning my vagrant don't have this right privilege. But I can't understand why because I have already this :
base.sh script :
# Set up sudo
echo 'vagrant ALL=NOPASSWD:ALL' > /etc/sudoers.d/vagrant

vagrant.sh script :
# Create the user vagrant with password vagrant
useradd -G sudo -p $(perl -e'print crypt("vagrant", "vagrant")') -m -s /bin/bash -N vagrant

# Install vagrant keys
mkdir -pm 700 /home/vagrant/.ssh
curl -Lo /home/vagrant/.ssh/authorized_keys \
  'https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub'
chmod 0600 /home/vagrant/.ssh/authorized_keys
chown -R vagrant:vagrant /home/vagrant/.ssh

builder in template.json packer :
  "builders": [
    {
      "boot_command": [
        "<esc><wait>",
        "<esc><wait>",
        "<enter><wait>",
        "/install/vmlinuz<wait>",
        " auto<wait>",
        " console-setup/ask_detect=false<wait>",
        " console-setup/layoutcode=fr<wait>",
        " console-setup/modelcode=pc105<wait>",
        " debconf/frontend=noninteractive<wait>",
        " debian-installer=fr_FR<wait>",
        " fb=false<wait>",
        " initrd=/install/initrd.gz<wait>",
        " kbd-chooser/method=fr<wait>",
        " keyboard-configuration/layout=fr<wait>",
        " keyboard-configuration/variant=fr<wait>",
        " locale=fr_FR<wait>",
        " netcfg/get_domain=vm<wait>",
        " netcfg/get_hostname=vagrant<wait>",
        " noapic<wait>",
        " preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg<wait>",
        " -- <wait>",
        "<enter><wait>"
      ],
      "boot_wait": "10s",
      "disk_size": 20480,
      "guest_additions_path": "VBoxGuestAdditions_{{.Version}}.iso",
      "guest_os_type": "Ubuntu_64",
      "http_directory": "http",
      "headless": true,
      "iso_checksum": "0501c446929f713eb162ae2088d8dc8b6426224a",
      "iso_checksum_type": "sha1",
      "iso_url": "http://mirrors.mit.edu/ubuntu-releases/trusty/ubuntu-14.04.3-server-amd64.iso",
      "output_directory": "packer-ubuntu-14.04-amd64-virtualbox",
      "shutdown_command": "echo 'vagrant'|sudo -S shutdown -P now",
      "ssh_username": "vagrant",
      "ssh_password": "vagrant",
      "ssh_port": 22,
      "ssh_wait_timeout": "10000s",
      "type": "virtualbox-iso",
      "vboxmanage": [
        [
          "modifyvm",
          "{{.Name}}",
          "--memory",
          "1024"
        ],
        [
          "modifyvm",
          "{{.Name}}",
          "--cpus",
          "1"
        ]
      ],
      "virtualbox_version_file": ".vbox_version",
      "vm_name": "packer-ubuntu-14.04-amd64"
    }
  ]

and my preseed.cfg ubuntu :
choose-mirror-bin mirror/http/proxy string
d-i base-installer/kernel/override-image string linux-server
d-i clock-setup/utc boolean true
d-i clock-setup/utc-auto boolean true
d-i finish-install/reboot_in_progress note
d-i grub-installer/only_debian boolean true
d-i grub-installer/with_other_os boolean true
d-i partman-auto-lvm/guided_size string max
d-i partman-auto/choose_recipe select atomic
d-i partman-auto/method string lvm
d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm_nooverwrite boolean true
d-i partman-lvm/device_remove_lvm boolean true
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
d-i partman/confirm_write_new_label boolean true
d-i passwd/user-fullname string vagrant
d-i passwd/user-uid string 900
d-i passwd/user-password password vagrant
d-i passwd/user-password-again password vagrant
d-i passwd/username string vagrant
d-i pkgsel/include string openssh-server cryptsetup build-essential libssl-dev libreadline-dev zlib1g-dev linux-source dkms nfs-common
d-i pkgsel/install-language-support boolean false
d-i pkgsel/update-policy select unattended-upgrades
d-i pkgsel/upgrade select full-upgrade
d-i time/zone string UTC
d-i user-setup/allow-password-weak boolean true
d-i user-setup/encrypt-home boolean false
tasksel tasksel/first multiselect standard, ubuntu-server

Can you tell me how can use a user with sudo access or root user in my provisionning vagrant in packer build ? I would like administrate my vagrant box before launch it all-out.
OS Host : windows 7 pro
OS Guest : Ubuntu 14.04 LTS
VM technology : VirtualBox 5.0.10 + Vagrant 1.7.4
VM tools builder : Packer 0.8.6
edit :
My debugging log tell me that apache correctly installed and also restarted...
But when a vagrant up I think that parameter

config.vm.box_url

not run correctly because when a locate a non-exist file, it up correctly a virtualbox.
in this case I think that vagrant up don't up the good box and I don't have my apache installation in my vagrant

A: do the following:
#vagrant box list

remove all or uneeded boxes:
#vagrant box remove <box>

run vagrant with the new box:
#vagrant up --provision

or just start the box without provisioning:
#vagrant up --no-provision

and finally:
#vagrant ssh


text:
Q: Changing the blue onClick indicator of a ListView In my app I have a list view. I dont get how to custom the native onClick indicator. When I press on a view every thing with alpha component is showing a blue onPress mark.
If the view don't have an alpha component, then nothing will be shown.
So, How do you "play" with what happens, when you press on a view in a ListView?
For example, in the Play Store you have a blue cover on top of every view that you press on? How can I do that?
And another question please, how can I disable this onClick indicator if I want?
Thanks!

A: List selector  this is what you are looking for
you can add any drawable resource as list selector


text:
Q: Ploting a spectrogram of a pure sinus with matplotlib I'm trying to get a spectogram plot of a pure sine function. Together with that i want to show a plot of the fft of that whole signal. I'm expecting the peaks to be on the same frequency since were dealing with the same signal which is stationary in time.
code
samplingFrequency = 32.
frequency = 4                           #frequency of the sinus wave
t = arange(0,20,1/samplingFrequency)    #time intervals with period 1/sampling frequency
y = cos(2*pi*frequency*t)

Y = fft.fft(y)                          #standard fft on the whole signal
frequencyAxis = fft.fftfreq(len(Y),1/samplingFrequency )          #adjusting the x axis

#PLOTTING
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1)
ax1.specgram(y, Fs = samplingFrequency)
ax2.stem(frequencyAxis,Y,linefmt='r--', markerfmt='ro')

plot

The fft of the whole signal is as expected with the peak on 4. However the spectogram plots a line on 12. Ideas on where the error is?
Update
Was using the following versions:

*

*matplotlib '1.1.1'

*numpy '1.6.2'

*python 2.7.3

A: On Python 2.7.5 with numpy 1.7.1 and matplotlib 1.2.1 your code works exactly as expected. Try updating both your numpy and matplotlib installations to the most recent versions.


text:
Q: probabilityproblem A and B play a game of chess. They play 20 games of which A wins 12 and B wins 4.The remaining 4 games are drawn.If 3 games are played between them, find the probability that
i)B wins at least 1 game?ii) the probability that 2 games are drawn?

A: Hints:

*

*If a game is played then what is the probability that $B$ will loose the game?

*If $3$ games are played then what is the probability that $B$ looses all games?

*If $3$ games are played then what is the probability that $B$ does not loose all games?

A: 20 games are not enough to establish the relative chess playing abilites of A and B but If we assume that they are representative; That is if they played 20 million games we get wins, losses and draws in the same proportion then B fails to win $\dfrac{16}{20} = \dfrac{4}{5}$ of the time.
The probability of B not winning any game is thus $\left(\dfrac{4}{5}\right)^3=\dfrac{64}{125}$ and the probability of winning at least one game is $1 - \dfrac{64}{125} = \dfrac{61}{125} = 0.488$


text:
Q: Is it possible that accuracy get reduced while increasing the no of epochs? I am training a DNN in MATLAB , while optimizing my network, I am observing a decrement in accuracy while increasing the epochs. Is it possible?
The loss values in on the other hand decreases during training while increasing epochs. Please guide.

A: It is absolutely possible:

*

*Especially when you are training in batches

*When your learning rate is too high

A: tldr; absolutely.
When entire training dataset is seen once by the model (feed forwarded once), it's termed as 1 epoch.
The below graph shows the general behaviour of accuracy with the number of epochs. Training on more number of epochs can result in low accuracy on validation, even though loss will continue to reduce (training accuracy will be high). This is termed as overfitting.
No. of epochs to train also a hyperparameter that needs fine tuning.


text:
Q: Query a Subquery I have to display the Rank of a user for which I plan to use the Rank() function in SQL Server. The Sql query to get the rank is as follows
select a.user_id, RANK() OVER (ORDER BY (a.quant_points) DESC) AS QRANK,
    RANK() OVER (ORDER BY (a.verbal_points) DESC) AS VRANK,
    RANK() OVER (ORDER BY (a.dilr_points) DESC) AS DRANK,
    RANK() OVER (ORDER BY (a.quant_points+a.verbal_points+a.dilr_points) DESC) AS ORANK
 from users a

However, I only want to get the rank of a particular user. If I add a where clause (where user_id = @user_id) to the above then all the Ranks are shown as 1.
So essentially, I have to query the above resultset treating it as a table. I was thinking of creating a temporary table but felt there might be better ways to achieve this.

A: How about creating a CTE, and pulling your single user out?
;with  UserRank AS
(
    SELECT a.user_id, RANK() OVER (ORDER BY (a.quant_points) DESC) AS QRANK,
           RANK() OVER (ORDER BY (a.verbal_points) DESC) AS VRANK,
           RANK() OVER (ORDER BY (a.dilr_points) DESC) AS DRANK,
           RANK() OVER (ORDER BY (a.quant_points+a.verbal_points+a.dilr_points) DESC) AS ORANK
   FROM Users a
 )

 SELECT QRANK, VRANK, DRANK, ORANK, user_id
 FROM UserRank WHERE user_id = @foo


text:
Q: Calculating the probability of a specific number of successful results out of a number of attempts, each with independent odds I'm attempting to calculate the probability of an exact number of successful outcomes in a set of unique scenarios that have independent odds. For example, I have 12 columns, each representing  scenario. There are 2 rows, 1 with the odds of a success, 1 with the odds of a failure for each attempt. What can I do to find the odds of any combination of 6 successes and 6 failures? Or the odds of 7 successes and 5 failures with 1 attempt of each scenario?

scenario 1
scenario 2
scenario 3
scenario 4
scenario 5
scenario 6
scenario 7
scenario 8
scenario 9
scenario 10
scenario 11
scenario 12

Success
.45
.65
.50
.40
.30
.45
.70
.75
.50
.90
.50
.25

Failure
.55
.35
.50
.60
.70
.55
.30
.25
.50
.10
.50
.75

Ultimately, my goal here is to make a bar graph that shows the probability of a specific number of successes after going through each scenario once. The x-axis of this graph would begin by showing the odds of 0 successful attempts all the way through the odds of all 12 being successful attempts.
For example, I know my odds of 0 successful attempts after going through all 12 scenarios is calculated by multiplying the odds of failure for each scenario: =Product(.55, .35, .50, .60, .70, .55, .30, .25, .50, .10, .50, .75)= .003%
Once you throw in a few successes, it adds a lot more combinations of outcomes and I need to sum the products of each of the possible outcomes that would lead to exactly 3 successes.
I started by attempting to sum the product of the results of every combination of successes and failures manually but soon realized there would be 924 combinations for 6 successes and I unfortunately don't have that much time on my hands. Are there any tools or functions that I could use in Excel to make this a bit more feasible?

A: As you correctly identify there are 924 possibilities that result in 6 successes and 6 failures. Had the probabilities of success for each scenario been identical then you could have used the Binomial distribution (function BINOM.DIST) to calculate your required probability values. (Incidentally, your use of the term "odds" is incorrect. Technically, the odds of an event happening is the ratio of the probability that the event happens to the probability that it does not happen.)
Unfortunately, the fact that each of your scenarios has a different probability of success means that there is no easy way to calculate your probabilities using a built-in function. However, it is not too difficult to calculate your required values using Excel.
Possibly the simplest way is to recognise that there are 4096 distinct possibilities, ranging all 12 scenarios being failures to all 12 being successes. The 4096 arises because each of the 12 scenarios can be a success or a failure meaning that there are 2^12 = 4096 distinct outcomes possible. These 4096 possibilities can be represented by the integers from 0 to 4095 and each integer can be represented as a 12 digit binary number, with the 12 0's and 1's representing failure and success respectively of the 12 scenarios. The first challenge, therefore, is to  find a way of converting each integer to a set of 12 values of 0's and 1's. Any integer (say I1) in the range 0 to 4095 can be converted to 12 0/1 values as follows

*

*Calculate the first 0/1 value as MOD(I1,2), call result B1

*Calculate a new integer (say I2) as (I1 - B1)/2

*Calculate the second 0/1 value as MOD(I2, 2) and call this result B2

*Calculate a new integer (say I3) as (I2-B2)/2
... (continue these pairs of calculation steps)

*Calculate a new integer (say I12) as (I11-B11)/2

*Calculate the twelfth 0/1 value as MOD(I12/2), call result B12

For each integer I1 (taking possible values between 0 and 4095), the 12 values B1, B2,...,B12 represent the binary digits of I1 in reverse order.
It is fairly straightforward to represent this as a rectangular array of numbers in Excel with 4096 rows and 24 columns. The rows represent the integers 0 to 4095, the first 12 columns represent the values I1 to I12 and the second 12 the 0/1 values of B1 to B12, with 1's representing success and 0's representing failure.
A 25th column can be added with the value in each row calculated as the sum of the 12 0/1 values B1,...,B12 in that row. This 25th column simply identifies the number of "successes" corresponding to the row.
A further 12 columns (columns 26 to 37) can now be added representing the probabilities of each scenarios outcome. If Pi and Qi are the probabilities of success and failure for the i'th scenario then the probability value (say Vi) is simply (Pi×Bi)+(Qi×(1-Bi)). A 38th column can now be calculated for each row as the product (function PRODUCT) of the 12 values V1, V2, ..., V12 in that row. This calculated value represents the probability of the particular pattern of successes and failures arising.
The final part is simply to calculate the required probabilities of n successes (and 12-n failures) where n=0,1,2,...,12. This is simply the sum  of the values in column 38 for those rows where column 25 has a value of n (function SUMIF or SUMIFS).
If I have entered the probability data correctly into my workbook, I calculate that to 5 significant figures the probability of 6 successes (the original question) is 0.23788.


text: Q: Frechet topology finer than a given locally convex topology Under what conditions given a locally convex space $(X,\tau)$ there exists a Frechet topology $\mu$, that is, $\mu$  is locally convex metrizable and complete such that $\mu$  is finer than $\tau$?


text:
Q: Problema con símbolos extraños en tildes, ñ y ¿ sólo en algunas páginas En una web realizada en wordpress me han aparecido sólo en algunas entradas o páginas el famoso problema de los acentos, ñ, etc...
Las soluciones que he leído en algún sitio de cambiar
define('DB_CHARSET', 'utf8');

por
define('DB_CHARSET', 'utf-8');

dentro del wp-config.php no funcionan, ya que al hacerlo las entradas que se ven mal pasan a verse bien, pero entonces todo el resto de la web (títulos, menús, páginas, entradas...) que estaban bien pasan a verse mal.
¿Alguna idea de cómo solucionar esto?
Edito la pregunta para aclarar que en el editor de wordpress se ve perfectamente y sin problemas, pero en el frontend aparece este problema. Comprobado con firefox y chrome, tanto en pc como en móvil.

A: Prueba a añadir también la colación. En este enlace se explica bien:
https://codex.wordpress.org/Editing_wp-config.php
Básicamente:
define( 'DB_COLLATE', 'utf8_spanish2_ci' );

A ver si así... lo que está claro es que en algún lugar de la base de datos de donde coge esos datos no tiene UTF-8 asignado, por eso tendrás esos problemas. Revísalo también :)

A: En PHPMyAdmin cambia el cotejamiento de las tablas a utf8_general_ci:
1.- Seleccionas y abres la BBDD
2.- Vas a la pestaña "Operaciones"
3.- En cotejamiento elijes "utf8_general_ci" y le das a continuar


text:
Q: Como reiniciar un objeto JavaScript Tengo una variable que guarda un objeto
var gData = {};

clase para crear el objeto
class Automate{
  constructor(){
    this.nodes = [];
    this.links = [];
    }
}

instancio y creo un nuevo objeto
var automateObject = new Automate();

y finalmente asigno el objeto a la variable
gData = automateObject;

Como puedo hacer posible que en algun punto eliminar toda la informacion que contiene el objeto gData e insertarle nuevos datos
He intentado utilizar la funcion "Delete" de javascript, por ejemplo
delete gData.nodes
delete gData.links

Pero al final no elimina las propiedad, sino que sigue agregando al momento de agregarle nuevo datos
   function parseContent(content) {
delete gData.nodes;
delete gData.links;
        var lines = content.split("\n");
        //Creation de l'automate
        var automateObject;
        //Parcourir tout le fichier
        for (var i = 0; i < lines.length; i++) {
          //Pour creer l'onbjet automate
            if(lines[i].length > 1){
              if(i == 0){
                var currentline = lines[i].split("\n");
                currentline = lines[i].replace(/[\(\)]/g, '');
                currentline = currentline.replace(/,/g, '');
                currentline = currentline.split(" ");
                automateObject = new Automate();
                const eta1 = new Etat(parseInt(currentline[1]),'RED');
                ets.push(eta1);
              } else {
                //variable pour stocker le titre et la couleur
                var label;
                //variable pour couper chaque ligne du fichier
                var currentline = lines[i].split("\n");
                  //Enlever les parenthese de la chaine de characters
                  currentline = lines[i].replace(/[\(\)]/g, '');
                  //Enlever les citations de la chaine
                  currentline = currentline.replace(/['"]+/g, '');
                  //Couper la chaine en 3 morceaux
                  currentline = currentline.split(",",3);
                  //Couper le deuxieme atribut pour obtenir le nom de lien et la couleur
                  label = currentline[1].split(":");
                  //Creation d'un object de type automate
                  const tran = new Transition(parseInt(currentline[0]),label[0],label[1],parseInt(currentline[2]));
                  //Ajouter l'object dans l'array
                  trans.push(tran);
                  validateEtat(parseInt(currentline[0]));
                  validateEtat(parseInt(currentline[2]));
              }
            }
        }
    automateObject.nodes = ets;
    automateObject.links = trans;
    gData = automateObject;
    console.log(gData);
    }

A: Te resumo tu código para que veas el problema:
function parseContent(content) {
    delete gData.nodes; //Borras el atributo
    delete gData.links; //Borras el atributo
    ...
    var automateObject; //declaras variable
    //Parcourir tout le fichier
    for (var i = 0; i < lines.length; i++) {
        ...
               //asignas un objeto a la variable
                automateObject = new Automate();

        ...
            }
        }
    }
    //rellenas los datos en la variable
    automateObject.nodes = ets;
    automateObject.links = trans;
    //gData borra su antiguo objeto y se le asigna uno nuevo
    gData = automateObject;
    console.log(gData); //muestras el valor de automateObject, que es lo guardado
}

La penúltima línea hace que las dos primeras de la función sean totalmente irrelevantes.


text:
Q: Apns notifications is not Working with Developement Certificate Please suggest me, As iam having developement p12 file and dependencies But iam getting Exceptiopn when sending notification through Developement Certificate.p12 file. the Exception is (javax.net.ssl.SSLException) javax.net.ssl.SSLException: Received fatal alert: internal_error
package com.push.notification.server;

import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;
import com.notnoop.apns.EnhancedApnsNotification;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

public class ApnsTest {

    private ApnsService service;

    public ApnsTest() {
    try {

        String path = "p12 file name";

        File certFile = new File(path);
        InputStream fis = new FileInputStream(certFile);
        service = APNS.newService().withCert(fis, "pwd")
            .withSandboxDestination()
            .build();
        sendMessage();
    } catch (Exception e) {
        e.printStackTrace();
    }
    }

    public static void main(String[] args) {
    new ApnsTest();
    }

    public void sendMessage() {
    String payload = APNS.newPayload().alertBody("nnnnn").sound("default").build();
    String deviceToken = "267fe9f23984cc6d8ca7b35db3c4b829cdbe2f9f1dbd3258cbbfa8f94e3fd986";
    int now = (int) (new Date().getTime() / 1000);
    EnhancedApnsNotification notification = new EnhancedApnsNotification(EnhancedApnsNotification.INCREMENT_ID(),
        now + 60 * 60, deviceToken, payload);

    System.out.println("Sending push notification");
    try {
        service.push(deviceToken, payload);
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

A: Yes, above problem solved by Creating Development certificate once again.
This is procedure enter image description here first in
On your Mac, open Keychain Access
From the top menu, select
Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority…
Fill out your email address, common name
Check Save to disk
Press Continue and save the .certSigningRequest file somewhere
enter image description here
Configuring Push Notifications for the App ID
Once the APP ID registration is completed, you need to configure it to make to work with push notification.
[enter image description here][3]
Select the App ID you just created, and click Edit
At Push Notifications, click Create Certificate then **Continue
Click Choose File… and upload the .certSigningRequest file you have generated and saved on your Mac earlier. Click Generate.
Once the certificate was generated, download it onto your Mac
[enter image description here][4]
1.4 Creating a Private Key
Now you are going to create a private key from the downloaded certificate.
[enter image description here][5]
Double-click the downloaded file. It should open in Keychain Access
Select My Certificates at left. You should find the certificate you just added.
Control-click the certificate, and select Export "Apple Development IOS Push Services:…"…
Save it as ..p12 file, by selecting File Format as Personal Information Exchange (.p12) in the Save As dialog
1.5 Creating a Provisioning Profile on Apple Developer portal,
Go to Provisioning Profiles
Click + to create a new provisioning file
Select iOS App Development, then Continue
Select a correct App ID from the drop-down list, then Continue
Select a correct certificate from the list, then Continue
Select devices you are going to develop with, the Continue
Enter a name for the provisioning profile, then Generate
Download the file
Double-click open the file in Xcode. The profile now should be added to Xcode.


text:
Q: How to debug pyqt signal/slot connections, probably threading issue I have the following piece of example code of my problem. Running this, I would expect that (if you type something in the lineedit) the A.updateValue slot would be called twice and thus show 'a.updatevalue called' and 'a2.updatevalue called'
However, it is only called once, namely for the self.a2 object and not for the self.a object, the latter which is sent from a worker thread to the GUI thread. How can I fix this so that this piece of code also triggers the slot for the self.a object?
Thank you,
David
import os, sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class A(QObject):
    def __init__(self, name):
        QObject.__init__(self)
        self.name = name
    def updateValue(self, value):
        print(self.name + ".updatevalue called")

class workerthread(QThread):
    def __init__(self, parent=None):
        QThread.__init__(self, parent)
    def run(self):
        a = A('a')
        QObject.emit(self, SIGNAL("mySignal"), a)

class Main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.centralwidget = QWidget(self)
        self.hbox = QHBoxLayout()
        self.centralwidget.setLayout(self.hbox)

    def update(self, a):
        self.a = a
        edit = QLineEdit("", self)
        self.hbox.addWidget(edit)
        edit.textChanged.connect(self.a.updateValue)
        self.a2 = A('a2')
        edit.textChanged.connect(self.a2.updateValue)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    gui = Main()
    worker = workerthread()
    worker.connect(worker, SIGNAL('mySignal'), gui.update)
    worker.start()
    gui.show()
    sys.exit(app.exec_())

A: Define a when you initialize workerThread
class workerthread(QThread):
    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        self.a = A('a')
    def run(self):
        QObject.emit(self, SIGNAL("mySignal"), self.a)


text:
Q: Constructing matrices in MATLAB I am trying to construct few matrices in MATLAB. Programming is not my forte and I cannot go into this. I know I should nest with for loops, but can't figure out how.I have an array of data y with T values. I need to set a lag m and then find Tm=T-2m+1. The  matrices Ymin and Yplus have order m x Tm, but don't know how to set them. In parentheses the position of the data in the array. Sorry for the format. The matrices are:
      y(m)      y(m+1)   ...   y(T-m)
      y(m-1)    y(m)     ...   y(T-m-1)
        .
        .
        .
       y(1)      y(2)    ...   y(Tm)

and
      y(m+1)    y(m+2)     ...   y(T-m+1)
      y(m+2)    y(m+3)     ...   y(T-m-2)
        .
        .
        .
       y(2m)      y(2m+1)  ...   y(T)

A: One approach with bsxfun to get those two matrices -
T = numel(y) %// number of elements in y

idx1 = bsxfun(@plus,[m:-1:1]',0:Tm-1)
out1 = y(idx1)

idx2 = bsxfun(@plus,[m+1:2*m]',0:Tm-1)
out2 = y(idx2)

A: Hope the following matlab code can help you!
%by Mark 4/28/2015

clear all;
%%%%%%%%%%%%%%%%% take an example

m=4;
T=10;
y=zeros(1,T);

for i=1:(T)
    y(i)=i;
end

%%%%%%%%%%%%%%%%%%%%%% calculate Ymin

count_i=0;

for i=m:1:(T-m)

    count_i=count_i+1;

    count_j=0;

    for j=i:(-1):(i-m+1)
        count_j=count_j+1;
        Ymin(count_j,count_i)=y(j);
    end
end

Ymin

%%%%%%%%%%%%%%%%%%%%%% calculate Ymax

count_i=0;

for i=(m+1):1:(T-m+1)
    count_i=count_i+1;
    count_j=0;
    for j=i:1:(i+m-1)
        count_j=count_j+1;
        Ymax(count_j,count_i)=y(j);
    end
end

Ymax

A: You can use hankel or toeplitz functions.
For first matrix use
flipud(hankel(y(1:m), y(m:Tm))

or
toeplitz(y(m:-1:1), y(m:Tm))

And for the second matrix use
hankel(y(m+1:2*m), y(2*m:T))


text:
Q: Can you compare varchar field one of table and char field of another table Can you compare varchar field one of table  and char field of another table ?

A: yes you can it.
first table have;
VARCHAR_COLUMN varchar(10)

second table have;
CHAR_COLUMN char(10)

you can use;
CHAR_COLUMN = VARCHAR_COLUMN

or convert;
Convert(varchar(10), CHAR_COLUMN) = VARCHAR_COLUMN


text:
Q: How to await an async delegate correctly? While in sync world, I have a TryExecute function to wrap try/catch/log logic for reuse, like this:
TryExecute(() => SyncFunction());

private static void TryExecute(Action action)
{
    try
    {
        action();
    }
    catch (Exception ex)
    {
        Log(ex);
        throw;
    }
}

I don't understand how to rewrite it into async/await pattern.
As what I understand, I have five valid ways to rewrite it into async/await (ignore any other Visual Studio has warning).
Using original sync TryExecute() with async delegate:
(1) TryExecute(async () => await AsyncFunction());

It seems not waiting anymore, the TryExecute() passes without waiting AsyncFunction() to finished.
Rewrite to a new sync TryExecuteTask() returns Task, call it with or without async delegate:
(2) await TryExecuteTask(() => AsyncFunction());
(3) await TryExecuteTask(async () => await AsyncFunction());

private static Task TryExecuteTask(Func<Task> asyncAction)
{
    try
    {
        return asyncAction();
    }
    catch (Exception ex)
    {
        Log(ex);
        throw;
    }
}

Or rewrite to a new async TryExecuteAsync(), call it with or without async delegate:
(4) await TryExecuteAsync(() => AsyncFunction());
(5) await TryExecuteAsync(async () => await AsyncFunction());

private async static Task TryExecuteAsync(Func<Task> asyncAction)
{
    try
    {
        await asyncAction();
    }
    catch (Exception ex)
    {
        Log(ex);
        throw;
    }
}

But if I throw Exception from inside AsyncFunction(), then none of above five ways can catch Exception. All stopped with unhandled exception. Only catch without delegate works:
(0) try
    {
        await AsyncFunction();
    }
    catch (Exception ex)
    {
        Log(ex);
    }

That means I can't use any forms of TryExecute() from (1) to (5) to reuse the try/catch/log logic, I can only repeating try/catch/log everywhere like (0).
My whole Console code is following:
class Program
{
    async static Task Main(string[] args)
    {
        // Original sync way
        TryExecute(() => SyncFunction());

        Console.WriteLine("0");
        try
        {
            await AsyncFunction();
        }
        catch (Exception ex)
        {
            Log(ex);
        }

        ////Console.WriteLine("1");
        ////TryExecute(async () => await AsyncFunction());

        ////Console.WriteLine("2");
        ////await TryExecuteTask(() => AsyncFunction());
        ////Console.WriteLine("3");
        ////await TryExecuteTask(async () => await AsyncFunction());

        ////Console.WriteLine("4");
        ////await TryExecuteAsync(() => AsyncFunction());
        ////Console.WriteLine("5");
        ////await TryExecuteAsync(async () => await AsyncFunction());

        Console.WriteLine("Finished without unhandled exception.");
    }

    private static void SyncFunction()
    {
        Console.WriteLine("SyncFunction starting");
        Thread.Sleep(500);
        Console.WriteLine("SyncFunction starting");
        throw new Exception();
    }

    private async static Task AsyncFunction()
    {
        Console.WriteLine("AsyncFunction starting");
        await Task.Run(() =>
        {

            Console.WriteLine("Sleep starting");
            Thread.Sleep(500);
            Console.WriteLine("Sleep end");
            throw new Exception();
        });
        Console.WriteLine("AsyncFunction end");
    }

    private static void TryExecute(Action action)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            Log(ex);
        }
    }

    private static Task TryExecuteTask(Func<Task> asyncAction)
    {
        try
        {
            return asyncAction();
        }
        catch (Exception ex)
        {
            Log(ex);
            throw;
        }
    }

    private async static Task TryExecuteAsync(Func<Task> asyncAction)
    {
        try
        {
            await asyncAction();
        }
        catch (Exception ex)
        {
            Log(ex);
            throw;
        }
    }

    private static void Log(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Because of the unhandled exception, I can only comment out all pieces but one in Main() to test every case.

A: Calling await TryExecuteAsync(AsyncFunction) works like you would expect:
class Program
{
    async static Task Main(string[] args)
    {
        await TryExecuteAsync(AsyncFunction);
        Console.WriteLine("Finished without unhandled exception.");
    }

    private async static Task AsyncFunction()
    {
        Console.WriteLine("AsyncFunction starting");
        await Task.Run(() =>
        {

            Console.WriteLine("Sleep starting");
            Thread.Sleep(3000);
            Console.WriteLine("Sleep end");
            throw new Exception();
        });
        Console.WriteLine("AsyncFunction end");
    }

    private async static Task TryExecuteAsync(Func<Task> asyncAction)
    {
        try
        {
            await asyncAction();
        }
        catch (Exception ex)
        {
            Log(ex);
            throw;
        }
    }

    private static void Log(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

AsyncFunction() raises an exception that is logged and then rethrown in TryExecuteAsync. If you want to catch the rethrown exception, you should put a try/catch around the call to TryExecuteAsync:
async static Task Main(string[] args)
{
    try
    {
        await TryExecuteAsync(AsyncFunction);
        Console.WriteLine("Finished without unhandled exception.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed to execute: " + ex.Message);
    }
}

A:
I don't understand how to rewrite it into async/await pattern.

When converting to async, the first step is to convert what your method calls. In this case, the delegate should be converted to an async-compatible delegate first.
Action is a delegate that takes no parameters and has no return value, like void Method(). An asynchronous method that takes no parameters and has no return value looks like async Task Method(), so its delegate type would be Func<Task>.
Side note: it's especially important when dealing with delegates to remember that async void is unnatural and should be avoided.
Once you change your delegate type from Action to Func<Task>, you can await its return value, which causes your TryExecute method to be changed to async Task, as such:
private static async Task TryExecuteAsync(Func<Task> asyncAction)
{
  try
  {
    await asyncAction();
  }
  catch (Exception ex)
  {
    Log(ex);
    throw;
  }
}

none of above five ways can catch Exception. All stopped with unhandled exception.

That's actually just a side effect of running the code in the debugger. With asynchronous code, you do sometimes see "unhandled" exceptions that are not actually unhandled. This is because it's the compiler-generated code that is catching the exception and placing it on the task, where it will later be re-raised when your code awaits it and then your code will catch it. The debugger gets a bit freaked out when the original exception caught by something other than your code (it's caught by the compiler generated code), and it has no way of knowing that this is perfectly normal.
So if you just continue past the debugger's "unhandled" exception, you'll see it works just fine.


text:
Q: Is it possible to create a trigger which is triggered on any insert in any table? I would like to create a MySQL trigger which runs before any row insert in any table. Is that possible? The alternative is to create a trigger before insert for each table, but that is not good enough: it is messy and it doesn't handle new tables, so I would definitely like to write a MySQL trigger which is triggered on any insert into any row. Is that possible? If so, how? (I could not find any reference to that in the documentation)

A: Go for a instead of trigger
ex: in sql server
create trigger name
on table_name
instead of insert
as
begin
if exists9select count(*) from inserted as i
join table_name as t
on i.id-t.id
group by i.id
having count(*) >1)
begin
raiseerror "duplicate category names npt allowsed"
end
else
insert into table_name (col1,col2)
select col1,col2 from inserted

`create trigger name
on table_name
instead of insert
as
begin
if exists9select count(*) from inserted as i
join table_name as t
on i.id-t.id
group by i.id
having count(*) >1)
begin
raise error "duplicate category names not allowed"
end
else
insert into table_name (col1,col2)
select col1,col2 from inserted
end
go

`

A: No, it is not possible, I have asked the guys from MySQL and they assured me that MySQL does not support currently this feature and it is not even planned for anytime soon, so nope, no hope at all, that's the answer.