text:
Q: Adding check boxes to each row on MVCcontrib Grid How can I add a checkbox to each row of a MVCcontrib grid. then when the form is posted find out which records were selected? I Am not finding much when searching for this.
Thank you

A: Here's how you could proceed:
Model:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsInStock { get; set; }
}

Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var products = new[]
        {
            new Product { Id = 1, Name = "product 1", IsInStock = false },
            new Product { Id = 2, Name = "product 2", IsInStock = true },
            new Product { Id = 3, Name = "product 3", IsInStock = false },
            new Product { Id = 4, Name = "product 4", IsInStock = true },
        };
        return View(products);
    }

    [HttpPost]
    public ActionResult Index(int[] isInStock)
    {
        // The isInStock array will contain the ids of selected products
        // TODO: Process selected products
        return RedirectToAction("Index");
    }
}

View:
<% using (Html.BeginForm()) { %>
    <%= Html.Grid<Product>(Model)
            .Columns(column => {
                column.For(x => x.Id);
                column.For(x => x.Name);
                column.For(x => x.IsInStock)
                      .Partial("~/Views/Home/IsInStock.ascx");
            })
    %>
    <input type="submit" value="OK" />
<% } %>

Partial:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %>

<input type="checkbox" name="isInStock" value="<%= Model.Id %>" />

And finally here's a helper method you could use to generate this checkbox:
using System.Web.Mvc;
using Microsoft.Web.Mvc;

public static class HtmlExtensions
{
    public static MvcHtmlString EditorForIsInStock(this HtmlHelper<Product> htmlHelper)
    {
        var tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttribute("type", "checkbox");
        tagBuilder.MergeAttribute("name", htmlHelper.NameFor(x => x.IsInStock).ToHtmlString());
        if (htmlHelper.ViewData.Model.IsInStock)
        {
            tagBuilder.MergeAttribute("checked", "checked");
        }
        return MvcHtmlString.Create(tagBuilder.ToString());
    }
}

Which simplifies the partial:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %>
<%: Html.EditorForIsInStock() %>

A: Dont know if this helps but I did a similar thing using the code below:
@Html.Grid(Model.PagedModel).AutoGenerateColumns().Columns(column => {
column.For(a => Html.ActionLink("Edit", "Edit", new { a.ID })).InsertAt(0).Encode(false);
column.Custom(a => Html.Raw("<input type='checkbox' name='resubmit' value='" + a.ID + "'/>" ) );
})

My controller was then able to receive the selected checkboxlist items:
[HttpPost]
public ViewResult List(string[] resubmit)

A: For resolving this in every get request I'm appending checked boxes value as comma separated string. Then retrieve the values from query string.
$("#pageLayout a").click(function () {
        //Check for the click event insed area pageLayout
        //get the href of link
        var link = $(this).attr('href');
        var apps = '';

        //for all the checkbox get the checked status
        $("input:checkbox").each(
            function () {
                if ($(this).attr('name') != 'IsChecked') {
                    if (apps != '') {
                        apps = apps + ',' + $(this).attr('name') + '=' + $(this).is(':checked');

                    }
                    else {
                        apps = $(this).attr('name') + '=' + $(this).is(':checked');
                    }
                }

            }
            )

        //Used to check if request has came from the paging, filter or sorting. For the filter anchor href doesnt haave
        //any query string parameter. So for appending the parameter first ? mark is used followed by list of query string
        //parameters.
        var index = link.lastIndexOf('?');

        //If there is no question mark in the string value return is -1
        if (index == -1) {
            //url for the filter anchor tag
            //appList hold the comma sep pair of applicationcode=checked status
            link = link + '?appList=' + apps + '&profileName=' + $('#ProfileName').val();
        }
        else {
            //url for sorting and paging anchor tag
            link = link + '&appList=' + apps + '&profileName=' + $('#ProfileName').val();

        }

        //Alter the url of link
        $(this).attr('href', link);

    });

A: In your view (say ReportList.cshtml) include your grid in a form and define an action for the form

<form action="/SubmitReportList">
            @{Html.Grid((List<NetSheet.Models.Report>)ViewData["ReportList"])
       .Sort((GridSortOptions)ViewData["sort"])
       .Attributes(id => "grid", @class => "grid")

       .Columns(column =>
       {
            column.For(c => Html.CheckBox("chkSelected", new { @class = "gridCheck",   @value = c.ReportId }))
            .Named("").Encode(false)
            .Attributes(@class => "grid-column");

column.For(c => c.ReportName)
              .Named("Buyer Close Sheet Name")
              .SortColumnName("ReportName")
               .Attributes(@class => "grid-column");

       })
       .Render();}

<input type="submit" name=" DeleteReports" id=" DeleteReports" value="Delete" class="btnSubmit"/>

</form>

Then in your controller implement your action method
public ActionResult SubmitReportList (string ReportListSubmit, IList<string> chkSelected){
    // The IList chkSelected will give you a list of values which includes report ids for the selected reports and "false" for the non-selected reports. You can implement your logic accordingly.
    return View("ReportList");
    }


text:
Q: Can not read property length of null in titanium appcelerator I am retrieving the json data using titanium.But the problem is that whenever i calculate the length of json data it says can not read length of null Here is my code:
                  Ti.UI.setBackgroundColor('#000');

 var win1 = Ti.UI.createWindow({
backgroundColor : '#fff',
title : 'Tab 1'
 });
var tab1 = Ti.UI.createTab({
icon : 'KS_nav_views.png',
title : 'Tab 1',
window : win1
 });

var JsonTable = Ti.UI.createTableView({
height : Ti.UI.FILL,
width : Ti.UI.FILL
});
win1.add(JsonTable);

 function getData() {
var myfontsize = '14dp';
// I needed to add this to test
var tableData = [];
var Json, Story;
var xhr = Ti.Network.createHTTPClient({
    onload : function() {
        var json = JSON.parse(this.responseText);
        // declare your variables :-)
        //alert(JSON.stringify(Story));
    //  alert(Story.nombre);
        alert(json.length);
        // only one . between things
        for (var i = 0; i < json.length; i++) {
            Story = json[i];
            //Ti.API.info('Story', JSON.stringify(Story));
            //Ti.API.info('Story.nombre', Story.nombre);
            var row = Ti.UI.createTableViewRow({
                backgroundColor : 'yellow',
                height : '85dp',
                width : Ti.UI.FILL
            });
            var labTitle = Ti.UI.createLabel({
                backgroundColor : 'orange',
                color : 'black',
                font : {
                    fontSize : myfontsize,
                    fontWeight : 'bold'
                },
                height : Ti.UI.SIZE,
                left : '25%',
                text : Story.nombre,
                top : '2%',
                width : Ti.UI.FILL
            });

            row.add(labTitle);
            tableData.push(row);
        }
        JsonTable.setData(tableData);
    },
    onerror : function(e) {
        Ti.API.debug("STATUS: " + this.status);
        Ti.API.debug("TEXT: " + this.responseText);
        Ti.API.debug("ERROR: " + e.error);
        alert('There was an error retrieving the remote data. Try again.');
    },
    timeout : 5000
});
JsonTable.addEventListener('click', function(e) {
    var index = e.index;
});
xhr.open("GET", "http://aplicaciones4.sct.gob.mx/sibuac_internet/SerEscogeRuta?estados");
xhr.send();
  }

 var btnGo = Ti.UI.createButton({
title : 'Go'
 });
 btnGo.addEventListener('click', function(e) {
getData();
  });
  //win1.setRightNavButton(btnGo);
win1.add(btnGo);

var img = Ti.UI.createImageView({
height : 32,
image : 'activity_indicator.gif',
width : 32
});
//win1.add(img);

 var tabGroup = Ti.UI.createTabGroup();
 tabGroup.addTab(tab1);
 tabGroup.open();

Can you help me in this
Thanks in advance

A: Try naming the result something other than "json".
Also, there's sloppy var declarations...
"var Json,Story;" << "J"son upper-case, never used

redpajama_set_name: RedPajamaStackExchange


text: Q: On intersections of exceptional divisors Let $X$ be a smooth, projective variety of dimension $n \ge 2$, $L$ a very ample line bundle on $X$ and $\pi: \widetilde{X} \to X$ be the blow-up along a closed subvariety of codimension at least $2$. Denote by $E$ the associated exceptional divisor. Is it true that for all $1 \le i \le n-1$, we have $(\pi^*L)^{n-i} E^i=0$?


text:
Q: Example of linear functional from Rudin's book
Rudin states that $\Lambda(f)=\int \limits_{X}fg d\mu$ is linear functional. We know that $\exists M$ such that $|g|\leqslant M$. Hence $|fg|\leqslant M|f|$ $\Rightarrow$ $\int \limits_{X}|fg|d\mu<\infty$ and $fg$ is measurable $\Rightarrow$ $fg\in L^1(\mu)$. So $\Lambda(\alpha f_1+\beta f_2)=\alpha \Lambda(f_1)+\beta \Lambda(f_2)$ is obvious since $fg\in L^1(\mu)$. Am I right?


text:
Q: HttpApplication.Start event does not exist I looked for an answer to this for quite sometime now but didn't find any.
I will refer to Application start as a stage.
Most of the documentations out there talk about the Global.asax file and the Application_Start method which is invoked only once when the first request reaches the Application, even if this behaviour is similar to subscribing to an event it's technicaly not an event.
While lifecycle events such as BeginRequest, AuthenticateRequest and so on are accessible through the application instance as events, the Application.Start is not.
I can subscribe to BeginRequest event in an HttpModule.Init() method or Global.asax Init() method but not to the Application.Start stage like so:
Module
public class MyModule : IHttpModule
{
  public void Init(HttpApplication httpApplication)
  {
    httpApplication.BeginRequest += new EventHandler(ApplicationBeginRequest);
  }
}

Global
public class Global : HttpApplication
{
  public override void Init()
  {
    BeginRequest += new EventHandler(ApplicationBeginRequest);
  }
}

My question:
Since there is no HttpApplication.Start event accessible from the Application instance, is Global.asax and the "Application_Start" method the only hope to subscribe to the Application start stage ?

A: After jumping to the .NET source code i found that the HttpApplicationFactory class looks for a method named Application_OnStart or Application_Start in the Global.asax file and then invokes it using reflection => ReflectOnMethodInfoIfItLooksLikeEventHandler().
I don't have the answer why HttpApplication.Start is not event but it's clearly intended to be handled in an event like fashion using Application_OnStart or Application_Start methods.


text:
Q: I'm having problems with Compiz I'll give you an example situation-I have two windows open of Program 1, and I'm currently active in Program 2. If I click on Program 1's icon in the launcher (it doesn't have to be pinned), the last window I was in while I used Program 1 comes up. But if I click the icon again to switch windows, while still in the window that came up, all of windows freeze for a couple seconds, then they all show up, stacked over one another (not like when you do Super+W- which doesn't work either), without their window decorations, and then, after a couple seconds, the windows flicker,  disappear, and then they reappear, with their decorations.
Sometimes, if this happens too frequently (maybe two times in ten seconds), the second time, the windows do not regain their decorations, and it's stuck like that. If I have my terminal open, (sometimes this works) I can type in compiz and everything starts working again. If not, then I have to shut down my computer and lose all my work.
I tried sudo apt-get install --reinstall compiz, sudo apt-get purge compiz, and the same commands except with unity and ubuntu-desktop included in the reinstallation and purging.
I am literally afraid to use the launcher now because of this. Please help, I'll try anything but Ubuntu reinstallation by now.
I'm using Ubuntu 14.04 LTS and Compiz 0.9.11.


text:
Q: Error: Abort signal from abort(3) (SIGABRT) when using recursion Problem Statement:
To construct a binary tree from a given inorder and preorder list.
I was able to write the logic but I get the error Abort signal from abort(3) (SIGABRT) and I ain't able to find what's causing this error.
Code:
#include <iostream>
#include <vector>
#include<algorithm>
#include <map>
#include <cmath>

using namespace std;

struct Node{
    int key;
    Node *left, *right;
    Node(int key){
    {
        this->key=key;
        this->left=this->right=nullptr;
    }
    }
};

class Solution {
public:

Node *construct_bin(int pidx, int s, int e, map<int, int>  m, vector<int> pre){

    if (s>e){
        return nullptr;
    }
    Node * root = new Node(pre[pidx++]);

    int i = m[root->key];
    root->left = construct_bin(pidx, s, i-1, m, pre);
    root->right = construct_bin(pidx, i+1, e, m, pre);

    return root;

}
};

int main()
{
    Solution sol;
    /* Construct the following tree
               1
             /   \
            /     \
           2       3
          /       / \
         /       /   \
        4       5     6
               / \
              /   \
             7     8
    */

    vector<int> inorder = { 4, 2, 1, 7, 5, 8, 3, 6 };
    vector<int> preorder = { 1, 2, 4, 3, 5, 7, 8, 6 };
    map<int, int> m;
    int co=0;
    for (auto it: inorder){
        m[it] = co++;
    }
    int n = preorder.size();
    Node* x = sol.construct_bin(0,0,n-1,m, preorder);
}

Logic:

A: You increment pidx in construct_bin, but you don't do anything with that incremented value. As a result, you call construct_bin an infinite number of times and your code eventually runs out of memory or overflows the stack.


text:
Q: How to point a chef client to a different chef server I've set up a chef client on my computer in order to do practice using the labs offered by learnchef.com.
How do I now point my chef client to our internal chef servers( we have 2 non-production and production). Do you need to reconfigure knife.rb as well as recreate validator.pem and client.pem files?

A: You'll have to get the validator.pem from each server and register to each
Another option is to create a client on each server and save the private key.
For bootstraping other nodes you need the validator.pem file for each server.
I've the same use case and do the following:
1) create a directory per chef server containing a knife.rb, client.pem etc.
i.e:
c:\chef\confs\server1
c:\chef\confs\server2

2) set KNIFE_HOME environment variable to the directory matching the server you wish to target
set KNIFE_HOME=c:\chef\confs\server1

Now every knife command will target server1.
Another option is to set any environment variable you wish and use it in your knife.rb file like
    chef_server_url  ENV['CHEF_SERVER_I_USE']
But this last one involves having some other settings modified (like using server1.pem and server2.pem files and using the ENV[]  in the validator_key for exemple)
You can find an exemple of this method here (for users, but easy to adapt): http://docs.getchef.com/config_rb_knife.html

A: Your chef client does not need to talk to more than one chef server. If you want to switch chef servers, then just delete the chef client's existing configuration and do a fresh bootstrap:
ssh $VM rm -rf /etc/chef
knife bootstrap $VM ...

Your chef workstation (your development machine that administers the chef servers) might want to access more than one chef server. In that case I recommend installing the knife block plugin.

A: For single-time interaction you may use -s SERVER_URL option like:
chef-client -S 'http://my_chef_server.net'

In case you need to change Chef Server forever, you have to edit knife.rb file. In order to interact with a Chef Server, three configuration settings are required, and you must change them.
node_name
client_key
chef_server_url

You may do it using knife configure command or manually with text editor(by default it lies in ~/.chef/knife.rb).
I would advise to you get familiar with that gist. It's Commented knife.rb for all the things. I believe it will help you to find out everything about configuring knife.


text:
Q: Need help in using Regular Expressions in Validation Rules My requirement is NOT to have any combination of PO Box (P.O. Box, P. O. Box, etc) getting into any line of ShippingStreet of the Account record.
To achieve I have used the following Regex in Validation Rule which is working perfectly fine when ShippingStreet has any combination of PO Box (in any line). But if there is NO PO Box entered, then I'm seeing this error:

Validation Formula "PO_Box_check" Invalid (Regular expression runtime exceeded for: (?i)(?:(\r\n*.))\b(?:.p.?\so.?\s*|.post\s+office)\s+box.(\r\n*.)).*

REGEX( ShippingStreet , "(?i)(?:(\\r*\\n*.*)*)\\b(?:.*p\\.?\\s*o\\.?\\s*|.*post\\s+office)\\s*+box.*(\\r*\\n*.*)*")

Can anyone please help?

A: I recommend you do a couple things:

*

*Use the s flag to have . match newline characters. That will help you simplify your expressions.

*Remove non-capturing groups. You're not using any of the groups, so you don't care if they are captured or not.

I was able to produce your runtime exceeded error with your initial validation formula, and the following worked just fine.
REGEX(ShippingStreet, "(?si).*\\b(p\\.?\\s*o\\.?\\s*|.*post\\s+office)\\s+box.*")


text:
Q: SASS throws an error for BEM syntax I'm just trying to use the "modifier" and "element" BEM syntax in SASS.
.second-title{
   background-color:green;

  &--touched{
    background-color:black;
  }

  &__left{
   background-color:red;
  }
}

The CSS file compiles correctly but when I try to run "grunt serve" compass throws the following error:
Syntax error: Invalid CSS after \" &-\": expected number or function, was \"-touched{\"\A on line 71 of D:/webdev/angularjs/ang-snapscan/app/styles/mobilestyle.scss";

A: In order to use the parent selector this way, you need to use Sass 3.3:
http://thesassway.com/news/sass-3-3-released#parent-selector-suffixes
If you're stuck using an older version, you could try this:
$module: 'second-title';

.second-title {
   background-color:green;
}

.#{$module}--touched{
  background-color:black;
}

.#{$module}__left{
 background-color:red;
}


text:
Q: AWS Fargate delay We use AWS Fargate to serve about just 700 requests per day with our API, there is no database or any other external dependencies.
Most of the time it works well and responds adequately, but sometimes the response takes 10 seconds and we get a request time out. We've checked everything and we have just 1 assumption, which we want to check if it can take place.
Our assumption is that Fargate de-allocates all resources when there are no requests and sometimes it can take a while till containers resume running. Can that be the cause?

A: When you start a task with Fargate we allocate capacity and never release it until the task stops. So your assumption is not the root cause. Consider that a Fargate task may take around 30/40 seconds to start (possibly more depending on the image size) so it doesn't look like what you are seeing (10 seconds delay) is a symptom of a task starting either. If you have enabled CloudWatch Container Insights for the cluster, you could try to see if there is any particular activity (peaks, tasks being deployed etc) at the time you see your delay/timeout. Assuming this is an ECS service that scales in and out I am wondering if there is any specific activity being carried out when you experience the issue. It's hard to suggest anything without further elements but definitely your theory isn't what's happening.


text:
Q: Replicate Protovis N-body simulation in D3 I would like to replicate the N-Body example from Protovis in the new library D3. D3 is supposed to be an evolution of Protovis but I am having a lot of trouble getting any simulation to even come close.
Target: http://mbostock.github.com/protovis/ex/nbody.html
So far I have the following problems:

*

*D3 has no built in collision detection.

*When adding collision detection of my own in each tick, it's very jittery.

*The N-body example moves slowly and smoothly, this is not the case for me in D3. Trying to replicate the settings in the Force layout doesn't seem to match.

*The color ramp I can't replicate with any accuracy. Mine jitters badly when trying to base it on node velocity.

*I can't get the simulation to stay running in any reasonable way. The cooling facter I have tried setting manually and via a resume().

Here is my current attempt: https://gist.github.com/1917001


text:
Q: "Run | Debug" option showing above each test in Eclipse using TestNG and Selenium I recently had to install fresh Eclipse and TestNG, and now this new option is showing above each test. I'd like to remove it but I can't find a configuration for it. Any ideas?
"Run | Debug" option showing
Edit: It seems to always display under the @Test. When I remove that, the option goes away.

A: These decorations in the Java text editor are called "Code Minings".
You can disable them by visiting: Preferences > Java > Editor > Code Minings.
While you can easily disable the decorations altogether, unfortunately I haven't found a way to disable just the ones related to TestNG.

A: These are simple Run or debug options.
If you click on Run-> It will run the respective scenario.
If you click on Debug-> It will run the respective scenario on Debug mode.


text:
Q: Python 3 filter - Bug or Feature? Okay, I am a complete newbie to Python - and stackoverflow.  I am coming from a ksh and Perl background.
The following in an interactive session with Python 2.7:

    Python 2.7.3 (default, Jan  2 2013, 16:53:07)
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import re
    >>> KEY="REC_PAPER"
    >>> VALIDVALUES=filter(lambda x:re.search(r'^' + KEY + '\=', x), [
    ... "REC_METAL=|YES|NO|",
    ... "REC_PAPER=|YES|NO|",
    ... "REC_GLASS=|YES|NO|",
    ... "REC_PLAST=|YES|NO|",
    ... "DEBUG_FLAG=|0|1|"
    ... ])  #End general list.
    >>> print(VALIDVALUES)
    ['REC_PAPER=|YES|NO|']
    >>>

Which is what I would expect VALIDVALUES to return.  However, Python 3.2's interactive session yields completely different results:

    Python 3.2.3 (default, Feb 20 2013, 17:02:41)
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import re
    >>> KEY="REC_PAPER"
    >>> VALIDVALUES=filter(lambda x:re.search(r'^' + KEY + '\=', x), [
        ... "REC_METAL=|YES|NO|",
        ... "REC_PAPER=|YES|NO|",
        ... "REC_GLASS=|YES|NO|",
        ... "REC_PLAST=|YES|NO|",
        ... "DEBUG_FLAG=|0|1|"
        ... ])  #End general list.
    >>> print(VALIDVALUES)
    &ltfilter object at 0xb734268c>
    >>>

I have seen in several places (including stackoverflow) where Python's equivalent of Perl's grep against a list is to filter the list.  That appeared to work in Python 2.  However, assuming the above behaviour in Python 3 is "correct," that no longer seems to be the case.
First question:  Is the above beahviour a bug or feature in Python 3?
Second question:  Assuming it is a feature, how do I get the output that Python 2 was giving?  For reasons I won't go into, I want to stay away from defining a function or subroutine, and do it "inline" like the current code.
Am I missing something obvious (quite possible for a newbie)?  Thanks in advance.

A: As per the documentation, filter in Python 3.x returns an iterator, rather than a list as in version 2.x. This is more memory-efficient than generating the whole list up-front. If you want the list back, you can wrap the iterator in a list() call:
VALIDVALUES = list(filter(...))

Alternatively, and as recommended by What's New In Python 3.0, you could rewrite it as a list comprehension without a lambda:
VALIDVALUES = [x for x in [...] if re.search(r'^' + KEY + '\=', x)]

A: Note that you don't usually need a list of values. You can directly loop the output like below
for value in VALIDVALUES:
  do_some_thing(value)

or
for value in filter(...):
  do_some_thing(value)

Sometimes you may need unique values or non mutable values. Use set or tuple or frozenset instead of list as shown in the other answer.


text:
Q: How to save programmatically created TextView in Android I have programmatically created an Android TextView on a Click event.
public class FireMissilesDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();

        builder.setView(inflater.inflate(R.layout.dialog_addvehicles, null))
        // Add action buttons
               .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int id) {

                        Dialog dialogAddVehicles = (Dialog) dialog;
                        etVehicleModel = (EditText) dialogAddVehicles.findViewById(R.id.etModel);
                        String vehicleModel = etVehicleModel.getText().toString();
                        SharedPreferences.Editor editor = myVehicleData.edit();
                        editor.putString("VehicleModel", vehicleModel);
                        editor.commit();

                        vehicleModelReturned = myVehicleData.getString("VehicleModel", "");

                        TextView valueTV = new TextView(AddMyVehicle.this);
                        linearLayout.addView(valueTV);

                        valueTV.setText(vehicleModelReturned);
                        valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
                        valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
                        valueTV.setTextColor(Color.parseColor("#333333"));
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       FireMissilesDialogFragment.this.getDialog().cancel();
                   }
               });
        return builder.create();
    }
}

The above code works perfectly and creates a new TextView, But when I close the application and re-run it the TextView would not display.
Is there any method that I could use to save the TextView so that even if I close the Application the TextView would remain.
You can find the whole code Here -> http://pastebin.com/0MZRmNAA

A: You can create a boolean variable on the activity class and set it to true when the button is clicked. That would mean that the textview has been created.
You should put the code to create the textview also into onResume method and check the boolean variable to see if you need to re-create the textview.
You can also save the information whether the button has been added in state so that the text view is re-created when the activity is re-created (e.g. after orientation change).
All that will work if you do not need to persist the information after the app killed. If you need to, use shared preferences (see other answers).
UPDATE:
Here is a sample activity that shows the code what needs to be done:
public class MainActivity extends Activity {

    private boolean textViewAdded; // whether the textview has been added
    private final String STATE_TEXTVIEWADDED = "STATE_TEXTVIEWADDED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) // restore state
            textViewAdded = savedInstanceState.getBoolean(STATE_TEXTVIEWADDED);
    }

    @Override
    protected void onResume() {
        if (textViewAdded) addTextView();
        super.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(STATE_TEXTVIEWADDED, textViewAdded); // save state
        super.onSaveInstanceState(outState);
    }

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

    public void buttonClick(View view) { // method called when a button is clicked.
        if (!textViewAdded) addTextView();
    }

    private void addTextView() {
        LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
        TextView valueTV = new TextView(MainActivity.this);
        valueTV.setText("Sample");

        main.addView(valueTV);
        textViewAdded = true;
    }

}

A: You can use SharedPreferences.
Initially, do the following:
SharedPreferences SP = getSharedPreferences("preferences name", MODE_PRIVATE);
Editor edit = SP.edit();

When you do the setText() call the following:
edit.putString("text", your_value);
edit.commit();

and before your activity loads, you could call to check if you have the following "text":
SP.getString("text", "");

I would recommend you creating a separate class for the SharedPreferences operations. And also do override the onResume() and onPause(). For reference, see this, the example implements the SharedPreference as a separate class.
Update: I think in your case, you are always creating a new SharedPreference, rather than using the existing one, create a separate class and I think all will go well.

A: If you need to persist your text view only during the lifetime of your application you can just write the code for creating the text view in onResume() method based on a flag, refer the answer by Szymon.
But if you are looking to keep it beyond the normal life cycle of your app, i.e even after you have forcefully stopped your app, you can write the details of the textview created(textview with its parameters ) in a file in onDestroy() of your activity. Later when restarting your activity, you can check this file and recreate the textviews into your layout as per the file.
Hope this helps.

A: try This
=====
LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
TextView valueTV = new TextView(this);
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
valueTV.setTextColor(Color.parseColor("#333"));
valueTV .setLayoutParams(lpView);
linLayout.addView(valueTV );

A: I think you are in need of persistent storage. You can do it in two ways:

*

*Preferences

*Database

In your case, you need to use Preferences (you can use database, too, but that would be cost effective in terms performance).
Check this link: http://developer.android.com/training/basics/data-storage/shared-preferences.html
Clearly explains how to use preferences for saving and retrieving data.
For tutorial, you can go here:
How to use SharedPreferences in Android to store, fetch and edit values


text:
Q: Is there a way to combine a pydantic and SQLite model into one class? I'm using fastapi and SQLite to make a simple API that can write to a database.
The pydantic model (Component class in main.py) is almost identical to the SQLite one (Component class in models.py). These two models could end up having many more properties. Each added property adds a line of duplicated code to the create and update methods that exists only to copy data from one model to the other. It seems like there must be a more elegant way to do this (sharing a model, multiple inheritance?) rather than defining two nearly identical classes and copying individual properties line by line multiple times.
models.py
A simple SQLite model:
from sqlalchemy import Column, Integer, String
from database import Base

class Component(Base):
    __tablename__ = "components"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    author = Column(String)
    description = Column(String)

main.py
I use fastapi and pydantic to define a basic CRUD API in a main.py. I've included only two of the operations:
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from database import engine, SessionLocal
import models

app = FastAPI()

models.Base.metadata.create_all(bind=engine)

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

class Component(BaseModel):
    name: str = Field(min_length=1)
    author: str = Field(min_length=1, max_length=100)
    description: str = Field(min_length=1, max_length=100)

@app.post("/")
def create_component(component: Component, db: Session = Depends(get_db)):
    c = models.Component()
    c.name = component.name
    c.author = component.author
    c.description = component.description
    db.add(c)
    db.commit()
    return component

@app.put("/{component_id}")
def update_component(component_id: int, component: Component, db: Session = Depends(get_db)):
    c.name = component.name
    c.author = component.author
    c.description = component.description

    db.add(c)
    db.commit()
    return component


text:
Q: Feature stroke is not updated I'm changing the stroke color of my features when they are selected like follows:
  var select = new Select({
    condition: click
  });
  select.on('select', function (e) {
    e.selected.forEach(function (feature) {
      feature.getStyle().getStroke().setColor([r, g, b, 1]);
    });
  });

It is working but when the map is translated, the deselected feature doesn't change its stroke.
I tried to use also the e.deselected property to set the default stroke color but it didn't work

A: As @Mike suggested you should be using select interaction's style option unless you have some reason not to.
var select = new Select({
    condition: click,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: [255,0,0,1],
        })
    })
});


text:
Q: Error When Calculating Standard Deviation in PowerShell I'm attempting to calculate some statistics for the values in each column of a CSV file using PowerShell. The Measure-Object cmdlet seems like it will do the trick for everything I need other than the Standard Deviation. I tracked down a description online where the Standard Deviation is calculated using [MATH], but when I run the code, I get the following error on the lines containing Pow():

Method invocation failed because system.management.automation.psobject doesn't contain a method named 'op_Subtraction'.

Here's my code, any help would be appreciated:
$i = 1

While ($i -le 211) {

#Set the variable to the filename with the iteration number
$filename = "c:\zMFM\z550Output\20dSummer\fixed20dSum550Output$i.csv"

#Check to see if that a file with $filename exists. If not, skip to the next iteration of $i. If so, run the code to collect the statistics for each variable and output them each to a different file
If (Test-Path $filename) {

#Calculate the Standard Deviation
#First get the average of the values in the column
$STDEVInputFile = Import-CSV $filename

#Find the average and count for column 'td'
$STDEVAVG = $STDEVInputFile | Measure-Object td -Average | Select Count, Average
$DevMath = 0

# Sum the squares of the differences between the mean and each value in the array
Foreach ($Y in $STDEVInputFile) {
$DevMath += [math]::pow(($Y - $STDEVAVG.Average), 2)

#Divide by the number of samples minus one
$STDEV = [Math]::sqrt($DevMath / ($STDEVAVG.Count-1))

}

#Calculate the basic statistics for column 'td' with the MEASURE-OBJECT cmdlet
$STATS = Import-CSV $Filename |
Measure-Object td -ave -max -min

#Append the standard deviation variable to the statistics array and add the value

$colSTDDEV = New-Object System.Data.DataColumn StdDev,([double])
$colVZA = New-Object System.Data.DataColumn VZA,([double])
$colVAZ = New-Object System.Data.DataColumn VAZ,([double])

$VZA = $Stats.VZA
$VAZ = $Stats.VAZ

$STATS.Columns.Add($colSTDDEV)
$STATS[0].StandardDev = $STDEV

$STATS.Columns.Add($colVZA)
$STATS[0].StandardDev = $VZA

$STATS.Columns.Add($colVAZ)
$STATS[0].StandardDev = $VAZ

#Export the $STATS file containing everything you need in the correct folder

Export-CSV -notype "c:\zMFM\z550Output\20dSummer\20dSum550Statistics.csv"

}
$i++
}

A: $DevMath += [math]::pow(($Y - $STDEVAVG.Average), 2)

You may have to replace this with:
$DevMath += [math]::pow(($Y.Average - $STDEVAVG.Average), 2)

since $Y seems to be an object, not a numeric value.


text:
Q: Build:Cannot find module OurFirstAppWithFVisualStudio.module.scss I am using NodeJS tools for visual studio for building a SPF App like shown here:
https://github.com/SharePoint/sp-dev-docs/wiki/Working-with-visual-studio
However after doing all steps, I have this error

Severity  Code    Description Project File    Line    Suppression State
  Error     Build:Cannot find module
  './OurFirstAppWithFVisualStudio.module.scss'. NodejsApp1  E:\GoogleDrive\Labs\SPF\OurFirstSPFAppWithVisualStudio\src\webparts\ourFirstAppWithFVisualStudio\OurFirstAppWithFVisualStudioWebPart.ts 8

When I checked the solution, I noticed the .scss file was excluded from the solution, so my first action was to include it in the project.
However that didnt have any effect.

A: The problem is perhaps that typescript cannot find the typings for for your module OurFirstAppWithFVisualStudio.module.css which it is being unable to resolve your module. Try requireing the styles. If typescript is unable to resolve the require function add the following in a .d.ts file
declare interface IRequire {
<T>(path: string): T;
(paths: string[], callback: (...modules: any[]) => void): void;
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
}

declare var require: IRequire;

In your project. You don't need to do import styles from './...scss'. Simply importing or requiring the file should do the trick. Although make sure you have configured the style loaders in your webpack.config.js or any other bundler if you're not using webpack. You can follow this article to configure the loaders in webpack. If neither of these work for perhaps you can create declaration files for your css modules using typed-css-modules


text:
Q: Grouping and Dividing Netezza I have the following query that divides each row in the sum(rev) column by the sum of the column.
For the following example the sum of sum(rev) column is 23193.The Divide column is derived by : row in sum(rev)/sum(rev)
select date,id,sum(rev),
NULLIF(rev,0) / sum(rev) over() as Divide
from test
where month(date) = 11
and year(date) = 2012
and day(date) = 02
and id = 'Client1'
group by date,id,rev
having sum(rev) <> 0
order by date

date                  id      sum(rev)      Divide

2012-11-02 00:00:00 Client1     1562.00     0.067348
2012-11-02 00:00:00 Client1     1.00        0.000043
2012-11-02 00:00:00 Client1     4689.00     0.202173
2012-11-02 00:00:00 Client1     267.00      0.011512
2012-11-02 00:00:00 Client1     16674.00    0.718924

There are 2 problems
1.) When the day(date) condition is commented the values retrieved are wrong.It does not give the correct value in the Divide Computation
    date               sum(rev)         Divide
    2012-11-02 00:00:00 1.00            0.000002
    2012-11-02 00:00:00 267.00          0.000412
    2012-11-02 00:00:00 1562.00         0.002412
    2012-11-02 00:00:00 4689.00         0.007241
    2012-11-02 00:00:00 16674.00        0.025749

2.) I want to group by date.So since we have records only for 2-11-2012 there must be only one line of record for each day
Please help fix these two errors
Ref: Find column Value by dividing with sum of a column

A: If you want to group by date and divide the daily totals by the grand total, you could do it like this:
SELECT
  date,
  SUM(rev) AS total,
  SUM(rev) / SUM(SUM(rev)) OVER () AS portion
FROM test
GROUP BY
  date
;

That is, the argument of SUM() OVER () should be a valid expression, and rev isn't a valid expression in this GROUP BY query, because rev isn't included in GROUP BY. But you can (and should) use SUM(rev) as an argument, and it will work as expected.
If you want separate results for separate clients, add id to the GROUP BY clause and add PARTITION BY id to the OVER clause of the window SUM(), like this:
SELECT
  date,
  id,
  SUM(rev) AS total,
  SUM(rev) / SUM(SUM(rev)) OVER (PARTITION BY id) AS portion
FROM test
GROUP BY
  date,
  id
;

Read more about the OVER clause in the manual.


text:
Q: prettyPhoto integration with Sitecore 6.5 I am trying to load a page on my site into a prettyPhoto lightbox via a click on an anchor tag.  What happens is that it looks like the lightbox begins to load, and it fetches the correct content, but instead of it loading the content in the lightbox, it over writes the whole page.
I tried to load external content in an iframe as well by trying the following:
TEST

It brings me to google, moving me away from my site and not loading it into an iframe.
Has anyone had similar problems with this? I am using sitecore 6.5.


text:
Q: Angular - No overload matches this call. The last overload gave the following error Below is the code for token.get() in my Angular-12 application:
get(){
  return localStorage.getItem('token');
}

Then I have the below mentioned code in my Service:
//GET Method
public getAllTerms(): Observable<any> {
   const headers = {     //Token for API Authorization
    'Authorization' : this.token.get(),
    'X-Requested-With' : 'XMLHttpRequest'
  }
  return this.http.get(`${this.api.baseURL}core/students`, headers);
}

My POST gave me a response without any. But in Angular, I got this error:

No overload matches this call.
The last overload gave the following error.
Type '{ Authorization: string | null; '
X - Requested - With ': string; }'
has no properties in common with type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; context?: HttpContext | undefined; observe?: "body" | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.ts(2769)
http.d.ts(1149, 5): The last overload is declared here.
const headers: {
    Authorization: string | null;
    'X-Requested-With': string;

headers is highlighted
If I change it to:
 public getAllTerms(): Observable<any> {
   const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
   return this.http.get(`${this.api.baseURL}core/students`, { headers, responseType: 'json' });
 }

The error change to:

401 (Unauthorized)

How do I resolve this?

A: get(){
  return localStorage.getItem('token');
}

Could return null if the token is not present, hence its definition is implicitly the following :
get(): string | null.
Since Angular use typescript, it is strictly typed, so string | null != string.
I guess this will solve your problem :
get(): string {
  return localStorage.getItem('token') ?? 'unauthenticated';
  // ?? operator is explained here https://indepth.dev/posts/1300/double-question-marks-typescript-3-7-nullish-coalescing
}


text:
Q: Why are some common-mode chokes rated in ohms instead of henries? Some common-mode chokes, including this one, are rated in ohms instead of in henries. Why? Isn't the impedance injected by the common-mode choke entirely frequency dependent? Is there an assumed frequency at which the specified ohm-age is calculated?

A: It is measured in ohms because it doesn't behave like an inductor. It's inductive at low frequencies, lossy/resistive in between, and capacitive at very high frequencies.
The resistance is usually measured at 100MHz, but check the datasheet to be sure.

A: That particular part there is a ferrite bead, not an inductor, so it has no inductance.


text:
Q: Getting concrete type in extension function I'd like to get the concrete type in an extension function:
extension ObjectExt on Object {
  T applyTo<T>(T Function(typeof this o) op) => op(this);
}

How to do that?

A: extension ObjectExt<T> on T {
  R applyTo<R>(R Function(T) op) => op(this as T);
}

This will allow to write x.applyTo(f) instead of f(x).


text:
Q: Are synthesized copy control members always public? When we don't define any constructors, the compiler synthesizes a default constructor for us. And the compiler will always synthesize the copy constructor, copy assignment and destructor if we don't define them ourselves. I want to know if the synthesized copy control members are always public? Or is there any way to control the access of these synthesized members?
Edit: To clarify, I want to know what the default access are for these members if I don't declare them at all.

A: Yes, you can get the synthesized special functions, but with different access controls:
class Foo {
  private:
     Foo() = default;
};

Since it's still declared private, it's not public, but you don't need to define it.

A: They should be public
http://en.cppreference.com/w/cpp/language/copy_constructor

If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class

A: The old way of blocking these member functions from being available for use was to declare them private yourself. Now you can just set the member functions equal to delete:
Example& operator = (const Example& rhs) = delete;


text:
Q: How can I assign a two dimensional array to a pointer? I want to assign an array to a pointer so I can use it
int arrayA[2][2] = {{1,2},{3,4}};
int arrayB[3][1] = {{1},{2},{3}};
int** arrayC;
if(case1)
   arrayC = arrayA;
if(case2)
   arrayC = arrayB;
//work with arrayC

What could I do?
Edit: Found another solution. See Answers

A: int ** is a fundamentally different and therefore incompatible data type than a 2D array int [][].
The only simple way to do the kind of thing you are attempting in your example above is to flatten your 2D arrays to 1D arrays:
int arrayA[2 * 2] = { 1, 2, 3, 4 };
int arrayB[3 * 1] = { 1, 2, 3 };
int* arrayC;
if (case1)
   arrayC = arrayA;
if (case2)
   arrayC = arrayB;

Obviously you'll then need to do explicit array index calculations yourself.

A: You can't assign (the correct term is convert) a 2D array to a pointer to pointer.   The reason is that the conversion of a 1D array to a pointer (to the first element) is not applicable in higher dimensions.
What you can do is declare a pointer to an array of two int.  The conversion in this case is valid.
int arrayA[2][2] = {{1,2},{3,4}};
int   (*arrayB)[2];
arrayB = arrayA;

The thing to realise, though, is that *arrayB is the address of the first element of arrayA.   In this example, that element is the array initialised using {1,2}.
Edited to add the following after the original question was edited to ask a different question.
The above does require consistency of dimensions though, so will not work in your (now edited example) where dimensions don't match.   It is the last (right-most) dimension that needs to match.
If you want mismatch of dimensions, there is no solution other than flattening the array to a single dimension.

A: I found a solution with dynamic initialisation of the array:
int arrayA[2][2] = { { 1, 2 }, { 3, 4 } };
int arrayB[3][1] = { { 1 }, { 2 }, { 3 } };
int** arrayC;
int dimension1, dimension2;
if (case1)
{
    dimension1=2;
    dimension2=2;
    arrayC = new int*[dimension1];
    for (int i = 0; i < dimension1; i++)
        arrayC[i] = arrayA[i];
}
if (case2)
{
    dimension1=3;
    dimension2=1;
    arrayC = new int*[dimension1];
    for (int i = 0; i < dimension1; i++)
        arrayC[i] = arrayB[i];
}
//work with arrayC
for (int i=0; i<dimension1; i++)
   arrayC=null;
delete[] arrayC;


text:
Q: Difficulty selecting data from multiple tables with a sub-query Afternoon,
Below is a relational schema I have created to assist in answering my question.
JOBS (**jobClass**, Description, chargePerHour)

EMPLOYEES (**empNo**, *jobClass*, firstName, lastName)

Foreign Key jobClass references JOBS
PROJECTS (**projectNo**, projectName)

PROJECTS2EMPLOYEES (**projEmpKey**, *projectNo*, *empNo*, hoursBilled, projectLeader)

Foreign Key projectNo references PROJECTS
Foreign Key empNo references EMPLOYEES
Bold = PK (Primary Key)
Italic = FK (Foreign Key)

I am trying to select projectName from the Projects table and the full name of the project leader for each project from the Employees table.
Project leaders are differentiated by a 1 in the projectLeader field in the projects2employees tables.
My last attempt was
SELECT projectName, CONCAT_WS(" ", firstName, lastName) FROM Projects, Employees WHERE projectNo IN
(SELECT projectNo from projects2employees WHERE projectLeader = 1)

but it didn't work out very well.
Any help would be appreciated

A: Try this :
SELECT p.projectName, CONCAT(firstName, ' ', lastName)
  FROM Projects p
  JOIN projects2employees pe
    ON (p.projectNo = pe.projectNo and pe.projectLeader = 1)
  JOIN employees e
    ON (pe.empno= e.empno)


text:
Q: Mechanically compressing a biological cell using solid weight vs water weight Hope to get some fruitful information from people with physics background. I am doing some lab experiments in which i grow cancer cells on a circular surface, before placing solid weight on top of the cell. The total weight placed is 36g and this weight over surface diameter of 24mm would correspond to 5.8mmhg Or 0.7 kPa.
I then looked at cell shape and other biological phenomena From using my compression device.
However, my advisor is asking if i could replicate the result by submerging the cell in a very high water (water with cell nutrients) height. I calculated that to get 5.8 mmhg of pressure in theory by water, i need to submerge cell in 8cm height.
To my amazement i couldnt replicate the same results. Im a biologist by background, and i try to formulate reasons as to why the results differ. An analogy i can think of is that if you slapping or punch someone, it will have different effects. But this would be a lame reasoning. So i did some googling and came across a somewhat similar qn on this forum and i attach the screenshot. and thre link below,
What's the difference between compression by a gas/liquid or by a solid?
It involves some physics which states that compression weight by liquid or air is at equilibrium at all points. Whereas solid weight stacked on something is not in equilibrium?
Hope to get some understanding on this matter. Any opinion is much appreciated!
An update: i realised (guess could be wrong) that liquid pressure acting on the cell in theory would come in all directions - cell is compressed from its sides as well as being compressed from the top. While solid pressure weight is only downward. Is this a concrete evidence?

A: Good investigation. You're very close to the key difference, which is that force applied from just one side (e.g., a weight from above) produces deviatoric stress. (Indeed, any loading configuration that's not the same in all three directions produces deviatoric stress.) This type of stress involves shear. It contributes to material failure. If you imagine various configurations with right angles inside the material, deviatoric stress will cause some of these angles to change.
In contrast, pressure (or hydrostatic stress, or equitriaxial compressive stress) is a fundamentally different type of stress called dilatational stress, which is calculated as negative one-third the trace of the stress matrix. It is the mediator of volumetric changes. It does not contribute to material failure and does not change right angles in
continuous objects.
If some cellular mechanism were crucially triggered from deviatoric stress, than I would not expect hydrostatic pressure to produce the same results. Examples include changes in molecular affinity from molecules being sheared, from changes in angular configurations, and from stretching (which arises from Poisson effects with deviatoric loading but cannot arise from hydrostatic pressure). In cell mechanosensitivity, for example, stretching is a key part of the mechanosensory mechanism, sometimes attributed to the behavior of catch bonds.


text:
Q: How to append api key body in the interceptor on a post request using retrofit I'm trying to append an Api key into the body of my request using an interceptor. I've tried various ways, none of them works..
URL: https://someapi.com/api/stories/
METHOD: POST
HEADERS: Accept: application/json
INPUT: {"key": ""}
@Provides
    @Singleton
    public Interceptor interceptor(NetworkUtils networkUtils) {
        return chain -> {
            Request originalRequest = chain.request();
        RequestBody requestBody = networkUtils.createBody();
        String postBodyString = networkUtils.bodyToString(requestBody);
        Request.Builder builder = originalRequest.newBuilder();
        postBodyString += ((postBodyString.length() > 0) ? "&" : "") + networkUtils.bodyToString(requestBody);
        originalRequest = builder.
                post(RequestBody.create(MediaType.parse(Constants.NETWORKING_HEADER.CONTENT_TYPE), postBodyString)).build();
        return chain.proceed(originalRequest);
    };
}

public RequestBody createBody() {
    return new FormBody.Builder()
            .add(Constants.NETWORKING_HEADER.KEY, Constants.NETWORKING_HEADER.API_KEY).build();
}

public String bodyToString(final RequestBody request) {

    try {
        final RequestBody copy = request;
        final Buffer buffer = new Buffer();
        if (copy != null) {
            copy.writeTo(buffer);
        } else {
            return "";
        }
        return buffer.readUtf8();
    } catch (final IOException e) {
        String message = "Did not work";
        Timber.d(message);
        return message;
    }
}

A: Possible duplicate of Retrofit2: Modifying request body in OkHttp Interceptor
The last answer by @Debanjan offers a good solution, covers both application/json as well as form data.


text:
Q: Magento getCollection with website filter My Magento installation has the price scope set to website. Therefore I can set different product prices for different websites.
I am trying to load a product model but the price attribute value retrieved is the default value and not the website specific value.
Following is the code I am using.
             $oProduct = Mage::getModel("catalog/product")
                        ->getCollection()
                        ->addAttributeToSelect("*")
                        ->addWebsiteFilter($websiteId)
                        ->addFieldToFilter("entity_id", $ruleData["product_id"])
                        ->getFirstItem();

Not sure what I am missing the addWebsiteFilter method doesn't seem to have the desired effect.
Thanks

A: I wanted to apply a website filter on the frontend and found that using addWebsiteFilter()  (no parameter) to filter products by the current website accomplished this.
Example:
Mage::getModel('catalog/product')->getCollection()->addWebsiteFilter()

A: I think you need to set the StoreId for the collection. So:
$oProduct = Mage::getModel("catalog/product")
                ->getCollection()
                ->setStoreId($correct_store_id_for_website)
                ->addAttributeToSelect("*")
                ->addFieldToFilter("entity_id", $ruleData["product_id"])
                ->getFirstItem();


text:
Q: Multiply two arrays with different dimensions using numpy I need a faster/optimised version of my current code:
import numpy as np

a = np.array((1, 2, 3))
b = np.array((10, 20, 30, 40, 50, 60, 70, 80))

print([i*b for i in a])

Is there any faster way to do this using numpy functions (maybe without reshaping and blowing up the whole thing)?

A: Looks like the outer product.
>>> np.outer(a, b)
array([[ 10,  20,  30,  40,  50,  60,  70,  80],
       [ 20,  40,  60,  80, 100, 120, 140, 160],
       [ 30,  60,  90, 120, 150, 180, 210, 240]])


text:
Q: Write data to excel or csv file using python First off, I am really new to Python. With that said, I am trying to scrape a webpage to see when and where the Shopkins Live shows are being performed so I can map it. Now, before you judge me on the Shopkins - just know it is a project I am doing with my oldest kid who is a huge Shopkins fan.
I originally tried putting the data into a csv file but when I did that it would print individual characters into a column - for instance it would say- d a t e across four columns rather than one column. I tried putting it into brackets writerows([data]) but that didn't work.
I have now tried moving onto writing into excel but am struggling with how to do it.  Any help would be greatly appreciated. When I run the python code it is outputting what I need in the Shell, but not sure how to transition this to write correctly in Excel.  The following is my code - any help is appreciated:
from bs4 import BeautifulSoup
import requests
import os, csv, sys, openpyxl
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
import contextlib
import re

url = 'http://www.shopkinslive.com/tour'
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
wb = load_workbook('Shopkins.xlsx')
ws = wb.get_sheet_by_name('Sheet1')

for div in soup.find_all('div', class_='row'):
    divtext = (div.text)
    ws['A1'].value = divtext  #I know this is what I need to fix but not sure how to do it

    print(divtext)   #This part works correctly

A: Your kid is really lucky and I bet he/ she knows it!
For the code:
from bs4 import BeautifulSoup
import requests
import pandas as pd

url = 'http://www.shopkinslive.com/tour'
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

tour_date = soup.find_all("div", {"class": "col date"})
tour_city = soup.find_all("div", {"class": "col city"})
tour_venue = soup.find_all("div", {"class": "col venue"})
tour_time = soup.find_all("div", {"class": "col time"})

t_date = [' '.join(td.text.split()[1:]) for td in tour_date]
t_city = [' '.join(td.text.split()[1:]) for td in tour_city]
t_venue = [' '.join(td.text.split()[1:]) for td in tour_venue]
t_time = [' '.join(td.text.split()[1:]) for td in tour_time]

df = pd.DataFrame({'Date' : t_date, 'City': t_city, 'Venue': t_venue, 'Time': t_time} )

df.to_excel('Shopkins.xlsx')

I tried to work around here as I didnot manage to append the dataframe row by row. But here's the idea:
I shall grab all necessary data using BS, put them into separate lists and then merge them into a data frame before exporting to excel file.
Please check out if it meets your needs.
P.s: the [1:] part should remove the text in  tags provided by the website. So yeah, it's the pattern.


text:
Q: How to build Meteor.js in an executable file? I need to build a meteor application under windows. How to do it right?
I found the meteor-electron package. If I understand correctly, it creates an executable file (exe).
I perform the following commands:
meteor create meteor-electron-build-test
cd meteor-electron-build-test
meteor add meson: electron
meteor

At this stage, everything is fine, the application of the electron inside the meteor is launched.
But if I stop the electron in the console and go to .meteor-electron \ win32-ia32 \ builds \ Electron-win32-ia32 \ Electron.exe - this application is empty.
I tried to add settings.
{
  "electron": {
    "name": "MyApp",
    "version": "0.1.0",
    "description": "A really cool app.",
    "rootUrl": "https://myapp.com",
    "launchPath": "/ app / landing",
    "sign": "Developer ID Application: ...",
    "height": 768,
    "width": 1024,
    "frame": true,
    "title-bar-style": "hidden",
    "resizable": true,
    "protocols": [{
      "name": "MyApp",
      "schemes": ["myapp"]
    }]
  }
}

And launched the team meteor --settings settings.json. The result is the same.
https://github.com/StekolschikovV/meteor-electron-build-test
If I add the "appSrcDir" parameter: "./" - starts an endless loop that all copies to the .meteor-electron folder.
How to correctly build an executable file meteor electron using windows?

A: meteor-electron doesn't deliver a meteor server process, only a thin web client. Therefore, your rootUrl setting must point to a valid web address hosting your app. This can be http://localhost:3000 for the purposes of testing.

A: Try Electrify.  I just tested it on the latest Meteor 1.7 and it works.  Bundles node and MongoDB.  Runs meteor client and server.
npm install -g electrify

https://github.com/arboleya/electrify


text:
Q: A data field that can have different kind of multimedia I am creating a database table, one of the columns can take the shape of all possible multimedia (text,video,audio,image). Without going into overkill of creating several different columns or multiple tables I decided that I should rather have a file pointer that points to where the data resides on the server and have an extra column that indicates the type of data present for the given row.
I want to know if this is a good design strategy or if there are better existing alternatives?
Thanks much,
Parijat

A: This is a fine strategy. In addition to the type of file, I would recommend adding a column that stores the length in bytes of the file, to save you retrieving it from the filesystem when you need to supply it in a Content-length header, for example.
If you expected all files to be of a relatively consistent size (none too large like video files), it might be preferable to store the data as binary blobs in the database, but given that you expect diverse media types and possibly very diverse file sizes, I think it makes more sense to keep the files in the filesystem and point to them from the database.


text:
Q: How do I import Encrypted ZMK.LMK into HSM for triple DES operations? I'm trying to import the ZMK that encrypted with LMK into HSM Thales 9000 for triple DES operations.
anyone had any idea for it ?
the ZMK is form by 3 clear component and encrypted under LMK. And i didnt have the 3 clear component.
thanks in advance.

A: your only way to import this key is either with the 3 components or use the same LMK.
if you have imported the 3 components on the same device or you are using the same LMK (on multiple devices) you can just use the encrypted ZMK whenever needed.
what are you trying to do?


text:
Q: How the mod() function works internally in languages like Java, Python, etc? in Java or Python this function is given by the % operator.
I would like to know the mathematical algorithm that uses this function.


text:
Q: Alphabetizing structured lists by last name in C I am attempting to sort a structure by last names alphabetically.  I have got most of my code to work correctly, but I have not been able to get it to sort alphabetically.  I attempted to use a swapper method, where you have a temp holder, swap the temp with the [s], and swap the [s] with the [s+1], but I could not get it to swap correctly.  I attempted to make a function and transfer the structure to the function, but I could not get that to function correctly either.  I am new to C and my syntax isn't that great.  I have gotten decent at sorting arrays full of numbers, but I haven't been able to find any examples of sorting structures to go by.  Any help would be greatly appreciated.  Here is my code so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student{
char f_name[20];
char l_name[20];
char temp[20];
int id_num;
float test1;
float test2;
float test3;
}s[10];

int main(void)
{
char grade;
float average;
int i, j, b;

for(i=0;i<10;i++)
{
printf("Enter first name(ZZ to quit): ");
scanf("%s", &s[i].f_name);
if(strcmp(s[i].f_name, "ZZ")==0)
    break;
else
{
printf("Enter students last name: ");
scanf("%s", &s[i].l_name);
printf("Enter Student ID: ");
scanf("%d", s[i].id_num);
printf("Enter 3 test scores: ");
scanf("%f %f %f", &s[i].test1, &s[i].test2, &s[i].test3);
    b++;
    }
}

i--;
printf("Student\t\tStudent Id\tFinal Grade\n");
for(i;i>=0;i--)
{
average = (s[i].test1 + s[i].test2 + s[i].test3) / 3;
if(average >= 90)
   grade = 'A';
else if(average >=80 || < 90)
   grade = 'B';
else if(average >= 70 || < 80)
   grade = 'C';
else if(average >= 60 || < 70)
   grade = 'D';
else
   grade = 'F';

printf("%s, %s\t%d\t\t%.2f \t%c\n", s[i].l_name, s[i].f_name, s[i].id_num, average, grade);
}
return 0;
}

A: Since you are new to C, I inserted sorting code into your own code and made a few minor, but necessary corrections.
Your code isn't too long, so I pasted the complete program below with comments explaining the added code.
This is not an optimal or efficient solution, but I wanted to get your own code working, without altering it much, so that you could understand the solution, and without introducing many new concepts that you might not understand.
As you learn more, and if you move on to C++, you'll find that there are much more elegant and efficient ways to solve this problem (especially with C++ and its sorting algorithms).
I also sorted by first name, if last names are the same, and included commented out hard code, so you can test it more quickly, as I hope that you will continue to refactor and improve your code on your own.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student{
    char f_name[20];
    char l_name[20];
    char temp[20];
    int id_num;
    float test1;
    float test2;
    float test3;
}s[10];

int main(void)
{
    char grade;
    float average;
    int i, j = 0, b = 0; //CORRECTION

    ////hard code for testing. UNCOMMENT, THEN COMMENT OUT INPUT 'FOR LOOP' FOR HARD CODE TESTING
    //strcpy(s[4].f_name, "Rob");
    //strcpy(s[4].l_name, "Zenf");
    //s[4].id_num = 5;
    //s[4].test1 = 60, s[4].test2 = 65, s[4].test3 = 70;

    //strcpy(s[3].f_name, "Red");
    //strcpy(s[3].l_name, "Zenf");
    //s[3].id_num = 4;
    //s[3].test1 = 80, s[3].test2 = 70, s[3].test3 = 75;

    //strcpy(s[2].f_name, "Adam");
    //strcpy(s[2].l_name, "Ant");
    //s[2].id_num = 3;
    //s[2].test1 = 100, s[2].test2 = 100, s[2].test3 = 100;

    //strcpy(s[1].f_name, "Zac");
    //strcpy(s[1].l_name, "Miller");
    //s[1].id_num = 2;
    //s[1].test1 = 60, s[1].test2 = 50, s[1].test3 = 40;

    //strcpy(s[0].f_name, "Ed");
    //strcpy(s[0].l_name, "George");
    //s[0].id_num = 1;
    //s[0].test1 = 90, s[0].test2 = 80, s[0].test3 = 70;

    //i = 5; // 1 more than index number of last hard-coded student

    ////end hard code

    //COMMENT OUT THIS 'FOR LOOP' FOR HARD CODE TESTING
    for (i = 0; i<10; i++)
    {
        printf("Enter first name(ZZ to quit): ");
        scanf("%s", &s[i].f_name);
        if (strcmp(s[i].f_name, "ZZ") == 0)
            break;
        else
        {
            printf("Enter students last name: ");
            scanf("%s", &s[i].l_name);
            printf("Enter Student ID: ");
            scanf("%d", &s[i].id_num); //CORRECTION
            printf("Enter 3 test scores: ");
            scanf("%f %f %f", &s[i].test1, &s[i].test2, &s[i].test3);
            b++;
        }
    }

    i--;

    //BEGINNING OF INSERTED SORT CODE. SHOULD BE REFACTORED INTO A FUNCTION

    int least;

    //Nested for loops. For every Student (except the first; this
    //algorithm sorts in reverse alphabetical order, because
    //your output 'for loop' prints in descending order), will
    //compare with every remaining student name in second (nested)
    //for loop, and swap with student name that comes first
    //alphabetically in the second for loop, if any.
    for (int counter = i; counter > 0; --counter) {

        least = counter;

        for (int k = counter - 1; k > -1; --k) {

            // Compare last names. If same, compare first name
            if (   (strcmp(s[k].l_name, s[least].l_name) < 0)   ||
                ( (strcmp(s[k].l_name, s[least].l_name) == 0) &&
                (strcmp(s[k].f_name, s[least].f_name) < 0) )   )

                least = k;
        }

        // Very manual swap of values.
        // Swaps take this format: temp = a; a = b; b = temp;
        char temp_f_name[20]; strcpy(temp_f_name, s[least].f_name);
        char temp_l_name[20]; strcpy(temp_l_name, s[least].l_name);
        char temp_temp[20]; strcpy(temp_temp, s[least].temp);
        int temp_id_num = s[least].id_num;
        float temp_test1 = s[least].test1;
        float temp_test2 = s[least].test2;
        float temp_test3 = s[least].test3;

        strcpy(s[least].f_name, s[counter].f_name);
        strcpy(s[least].l_name, s[counter].l_name);
        strcpy(s[least].temp, s[counter].temp);
        s[least].id_num = s[counter].id_num;
        s[least].test1 = s[counter].test1;
        s[least].test2 = s[counter].test2;
        s[least].test3 = s[counter].test3;

        strcpy(s[counter].f_name, temp_f_name);
        strcpy(s[counter].l_name, temp_l_name);
        strcpy(s[counter].temp, temp_temp);
        s[counter].id_num = temp_id_num;
        s[counter].test1 = temp_test1;
        s[counter].test2 = temp_test2;
        s[counter].test3 = temp_test3;

    } //END OF INSERTED SORT CODE

    printf("Student\t\tStudent Id\tFinal Grade\n");
    for (i; i >= 0; i--)
    {
        average = (s[i].test1 + s[i].test2 + s[i].test3) / 3;
        if (average >= 90)
            grade = 'A';
        else if (average >= 80 && average < 90) //CORRECTION. Use && not ||. Needed "average" again
            grade = 'B';
        else if (average >= 70 && average < 80) //CORRECTION
            grade = 'C';
        else if (average >= 60 && average < 70) //CORRECTION
            grade = 'D';
        else
            grade = 'F';

        printf("%s, %s\t%d\t\t%.2f \t%c\n", s[i].l_name, s[i].f_name, s[i].id_num, average, grade);
    }
    return 0;
}


text:
Q: Linux Ubuntu Files behind the mount root@host:~# mkdir -p /tmp/test
root@host:~# echo "test" >> /tmp/test/file.txt
root@host:~# mount /dev/xy /tmp/test/

How can I now access file.txt without unmount /dev/xy?

A: You may be able to see it by using a bind mount e.g.
mount --bind /tmp /mnt

then
cat /mnt/test/file.txt
test

You have to bind mount the filesystem that contains the original file. In this case /tmp. This may not work with some filesystems e.g. zfs.


text:
Q: Developing: Where to start? I'm interested in getting into the technicalities of the OS, perhaps by doing some developing but mainly just understanding how everything works on Ubuntu!
I've been using it for about 6 months and I absolutely love it and the whole community, I know some basic Python and Javascript (I've been taking the Codecademy courses) but I really don't know where to start.
Any ideas will be welcomed (books, websites or even just something that I should look into).
Thanks in advance!
Jo

A: Maybe the Ubuntu developers community could help you :
http://community.ubuntu.com/contribute/developers/
Emman


text:
Q: Data binding to a UserControl in a FormView I have a FormView that contains a custom UserControl, but I can't seem to databind my UserControl to the data item. Data binding to other built-in ASP.NET controls works fine.
Here's a quick example:
<asp:FormView runat="server">
    <ItemTemplate>
        <!-- Works: Binding a Label's 'Text' property -->
        <asp:Label runat="server" Text="<%# Item.ToString() %>" />

        <!-- Works: Setting my custom control's 'Text' property in markup -->
        <my:CustomControl runat="server" Text="plain text in markup" />

        <!-- DOESN'T WORK: Binding my custom control's 'Text' property -->
        <my:CustomControl runat="server" Text="<%# Item.ToString() %>" />
    </ItemTemplate>
</asp:FormView>

The first two controls display correctly; the last example is blank and setting a breakpoint in the Text property reveals it's never getting called.

A: I think if you use Eval instead it should work, try the below:
<my:CustomControl runat="server" Text="<%# Eval("Item") %>" />


text:
Q: How to format a locked SATA hard drive so I have this TOSHIBA MQ01ABF050 (AMFQ6E) hard drive which I was using to dual Ubuntu and Windows, until a day I on my laptop and it started asking for a HDD password which I have not even put there at all. So I later got another hard drive but I still want to use the HDD (I don't care if I lose all the files in it).
But when I tried formatting it on my newly installed Ubuntu. I have the following results

Result of sudo fdisk -l
    Disk /dev/loop0: 4 KiB, 4096 bytes, 8 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop1: 55.5 MiB, 58183680 bytes, 113640 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop2: 55.52 MiB, 58204160 bytes, 113680 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop3: 61.91 MiB, 64897024 bytes, 126752 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop4: 61.92 MiB, 64901120 bytes, 126760 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop5: 218.102 MiB, 229629952 bytes, 448496 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop6: 219 MiB, 229638144 bytes, 448512 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop7: 247.93 MiB, 259948544 bytes, 507712 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/sda: 465.78 GiB, 500107862016 bytes, 976773168 sectors
Disk model: WDC WD5000LPCX-6
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: 4AF05127-920D-409A-9568-CFC21D909FC4

Device       Start       End   Sectors   Size Type
/dev/sda1     2048   1050623   1048576   512M EFI System
/dev/sda2  1050624 976771071 975720448 465.3G Linux filesystem

Disk /dev/loop8: 248.78 MiB, 260841472 bytes, 509456 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop9: 94.54 MiB, 99119104 bytes, 193592 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop10: 94.6 MiB, 99176448 bytes, 193704 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop11: 64.79 MiB, 67915776 bytes, 132648 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop12: 51.4 MiB, 53522432 bytes, 104536 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop13: 65.22 MiB, 68378624 bytes, 133552 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop14: 54.24 MiB, 56872960 bytes, 111080 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop15: 43.6 MiB, 45703168 bytes, 89264 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Here is also the result for sudo fsck -f /dev/sdb
fsck from util-linux 2.34
e2fsck 1.45.5 (07-Jan-2020)
fsck.ext2: Input/output error while trying to open /dev/sdb

The superblock could not be read or does not describe a valid ext2/ext3/ext4
filesystem.  If the device is valid and it really contains an ext2/ext3/ext4
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
    e2fsck -b 8193 <device>
 or
    e2fsck -b 32768 <device>

Is there anyway I can get this HDD to be useful again


text:
Q: node.js / socket.io: lag and unexplained disconnections I have built a two player real time video game using node.js and express. The bidirectional communication is handled by socket.io. The game is just a clone of Space Invaders, you move a spaceship left and right and shoot at enemies, nothing graphically or computationally intensive.
The game is working fine locally on my computer. When I test it online (on Heroku), I run in two problems mostly:

*

*the game is laggy (just moving the spaceship left and right is hardly doable). I'm way under the Heroku memory limit and the web transaction response time of my app is good (under 7ms on average).

*sometimes one player disconnects for no obvious reason (on the client side the game just freezes).

It is my first nodejs/socket.io project so I have no idea if these problems can be solved or if it is the kind of technical problems we can expect and hardly solve at the current state of development of these technologies. I must also confess that I'm still using express version 3.2.6 and socket.io 0.9.6. Are there good reasons to think my problems could be solved by upgrading (knowing I don't have problems locally with the same versions)?
EDIT:
On localhost I get the (good) socket.io logs:
debug - authorized
info  - handshake authorized h3KKs0td7dWUV-d7dVPW
debug - setting request GET /socket.io/1/websocket/h3KKs0td7dWUV-d7dVPW
debug - set heartbeat interval for client h3KKs0td7dWUV-d7dVPW
debug - client authorized for
debug - websocket writing 1::
debug - emitting heartbeat for client h3KKs0td7dWUV-d7dVPW
debug - websocket writing 2::
debug - set heartbeat timeout for client h3KKs0td7dWUV-d7dVPW
debug - got heartbeat packet
debug - cleared heartbeat timeout for client h3KKs0td7dWUV-d7dVPW
debug - set heartbeat interval for client h3KKs0td7dWUV-d7dVPW

but this is what I get on Heroku:
2015-03-12T14:54:59.225532+00:00 app[web.1]: debug: authorized
2015-03-12T14:54:59.228461+00:00 heroku[router]: at=info method=GET path="/socket.io/1/?t=1426172098882" host=app.herokuapp.com request_id=bdb2d91f-3332-4b42-861a-373889e595c6 fwd="129.199.31.253" dyno=web.1 connect=0ms service=7ms status=200 bytes=209
2015-03-12T14:54:59.299001+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/socket.io/1/websocket/909762909928759556" host=app.herokuapp.com request_id=4609b498-cc7d-4f65-8a3c-244332150988 fwd="ip" dyno=web.1 connect=3ms service=5ms status=503 bytes=0
2015-03-12T14:54:59.228290+00:00 app[web.1]: info: handshake authorized 909762909928759556
2015-03-12T14:54:59.296245+00:00 app[web.1]: debug: setting request GET /socket.io/1/websocket/909762909928759556
2015-03-12T14:54:59.297418+00:00 app[web.1]: warn: websocket connection invalid
2015-03-12T14:54:59.297983+00:00 app[web.1]: debug: set close timeout for client 909762909928759556
2015-03-12T14:54:59.298944+00:00 app[web.1]: debug: cleared heartbeat interval for client 909762909928759556
2015-03-12T14:54:59.406210+00:00 app[web.1]: debug: set heartbeat interval for client 909762909928759556
2015-03-12T14:54:59.407576+00:00 app[web.1]: debug: cleared close timeout for client 909762909928759556
2015-03-12T14:54:59.296644+00:00 app[web.1]: debug: set heartbeat interval for client 909762909928759556
2015-03-12T14:54:59.297579+00:00 app[web.1]: info: transport end (undefined)
2015-03-12T14:54:59.298643+00:00 app[web.1]: debug: cleared close timeout for client 909762909928759556
2015-03-12T14:54:59.405871+00:00 app[web.1]: debug: setting request GET /socket.io/1/websocket/909762909928759556
2015-03-12T14:54:59.406676+00:00 app[web.1]: warn: websocket connection invalid
2015-03-12T14:54:59.406788+00:00 app[web.1]: info: transport end (undefined)
2015-03-12T14:54:59.407212+00:00 app[web.1]: debug: set close timeout for client 909762909928759556
2015-03-12T14:54:59.407731+00:00 app[web.1]: debug: cleared heartbeat interval for client 909762909928759556
2015-03-12T14:54:59.407046+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/socket.io/1/websocket/909762909928759556" host=app.herokuapp.com request_id=75d2c5e5-eac3-4ec0-8774-640892993a6e fwd="ip" dyno=web.1 connect=0ms service=3ms status=503 bytes=0
2015-03-12T14:55:09.394154+00:00 app[web.1]: debug: setting request GET /socket.io/1/xhr-polling/909762909928759556?t=1426172109066
2015-03-12T14:55:09.395831+00:00 app[web.1]: debug: client authorized for
2015-03-12T14:55:09.397405+00:00 app[web.1]: debug: xhr-polling writing 1::
2015-03-12T14:55:09.458911+00:00 app[web.1]: debug: setting request GET /socket.io/1/xhr-polling/909762909928759556?t=1426172109122
2015-03-12T14:55:09.459657+00:00 app[web.1]: debug: discarding transport
2015-03-12T14:55:09.491409+00:00 app[web.1]: debug: xhr-polling received data packet �41�5:::{"name":"player","args":["aaa"]}�25�5:::{"name":"update"}
2015-03-12T14:55:09.394628+00:00 app[web.1]: debug: setting poll timeout
2015-03-12T14:55:09.396896+00:00 app[web.1]: debug: clearing poll timeout
2015-03-12T14:55:09.397721+00:00 app[web.1]: debug: set close timeout for client 909762909928759556
2015-03-12T14:55:09.459456+00:00 app[web.1]: debug: setting poll timeout
2015-03-12T14:55:09.459867+00:00 app[web.1]: debug: cleared close timeout for client 909762909928759556

As I don't have a lot of time to fix version-related problems I would prefer to explore solutions that don't require to upgrade, except if you tell me the benefits will be great.
PS: I'll be happy to provide pieces of code but I don't know which ones matter for my problems.

A: My problem was that at work my internet connection go through a proxy, that probably doesn't accept websockets. Socket.io was then reverting to xhr-polling for communication.
Testing from another location than work gave no problems.
You can use websites such as http://www.lagado.com/proxy-test to test whether you're connecting to the internet through a proxy.


text:
Q: 5 equal width columns in bootstrap (full width of container) According to my psd template, i have CONTAINER which consists of 5 equal width (344px) columns. I decided to go with bootstrap in terms of responsiveness. But now i'm frustrated with this task.
Is there any way to implement this or i need:

*

*Rebuild my psd template to fit bootstrap grid and sizes

*Not to use bootstrap and write custom responsive classes

Codepen:
http://codepen.io/anon/pen/YZbBQG

A: I'd recommend using the auto layout col-lg columns for larger widths so that you can have 5 across, then scale down to the standard size grid columns on md, sm, etc..
Bootstrap 4.6 (update 2020)

           ...

           ...

           ...

           ...

           ...

           ...

           ...

Note: This will allow the columns to grow evenly to fill the width of the row. In rare cases where the column content forces the width (for example columns that contain fixed width images or non-wrapping text), use min-width:0 to force equal column width regardless of their content.
.col-lg {
    min-width: 0;
}

http://codeply.com/go/DVzExqdUZa

A: It's easy using bootstrap 4. You just need a single flex line on the columns to define the custom width.

.row > .col {
  flex: 0 0 344px;
  background: #eee;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

1

2

3

4

5

A: You can also use Flexbox. I suggest you to use 1200px or less as the maximum container width.

1

2

3

4

5

.container{

    display: flex;
    width: 1720px;

}

A: You can customize your version of bootstrap "the right way". The link to this page let's you customize A LOT of settings, including the number of grid columns.
http://getbootstrap.com/customize/


text:
Q: Angular: Controller as syntax not updating data I have this code
template
{{  GC.objectList }}
Controller
var self = this;
self.objectList = [];

           myService.list().then(function (data) {
                self.objectList = data.results;
            }, function (error) {
                console.log(error);
            })

Now when i get new data from server then my data dont get updated in template.
However if use $scope instead of self. Then it works fine

A: Anything that needs to have an effect with respect to the view in Angularjs   or with respect to the manipulation should be done making use of the $scope obj. It is like you play with $scope which is created as a new instance for every controller created.
So hence making use of $scope is the right way to do it.

A: $scope is an object which is two way dynamic is a functionality providing you by angularjs. $scope will help you in assigning variables to the objects and if you are changing in the template, it will automatically get reflected in the scope object also.


text:
Q: Remove Type from PHP Array: int(2) => "2" I am attempting to store a Epoch timestamp as an integer in an a map in PHP, however, I am running into trouble getting the pure integer value, instead getting (int) before the value of the timestamp.
$property = "test property";
$date = new DateTime();
$timestamp = $date->getTimestamp();
$tmpArray = array($property => $timestamp);
var_dump($tmpArray);

$tmpArray has a structure as the following:

array(1) { ["test property"]=> int(1493778589) }

Is there a way to get the value in the map to be just 1493778047 without the (int) before it?

A: You're misunderstanding the output of var_dump().
The value you have IS an integer. The int() you see it wrapped in is simply var_dump()'s way of telling you the data type.


text:
Q: How to add an onClick to a parent from within React Component whose Ref is passed to it? I am working on a Reusable Menu Component.
It takes an array of objects and generates the Menu based on the array sent as prop.
This menu will always be triggered on click.
Now what I wanted to do is have the onClick implementation(event listeners, onClick function, etc) inside the Menu component itself.
How I planned on doing it was assigning a Ref to whatever is the Parent of the menu(the element that needs to be clicked for the menu to show) and sending that ref down to Menu and using the Ref to attach the onClick function onto the parent.
Parent.jsx
import React, {useRef} from 'react';

const Parent = () => {

   const menuRef = useRef(null);

   return(
     <>
       {/*
         A lot of elements
       */}

Some svg's in a list

         .
         .
         .

            <svg>Another svg...</svg>
            <Menu parentRef={menuRef} items={menu} />

     </>
   )

}

Menu.jsx
import React, {useState} from 'react';

const Menu = ({parentRef,items}) => {
   const [isMenuActive, setMenuActive] = useState(false);

   const onParentClick = (e) => {
       // some code and then
       setMenuActive(!isMenuActive);
   }

   // This is what I intended to do
   parentRef.current.onClick(onParentClick);

   return(
     <div className={`menu-container ${isMenuActive ? 'active' : '' }`}
        {/*
              Menu population code
        */}

   )

}

The problem is every function of parentRef.current.* is returning null.
A console.log of parentRef is yielding an object with the current havin the entire
 tag as expected. But I am not getting how to assign an onClick onto it.
Any help is appreciated.

A: function call: parentRef.current.onClick(onParentClick)
function assignment: parentRef.current.onclick = function


text:
Q: Converting R function to Latex formula I'm having trouble converting an R function to a latex formula. I have a df (m) of x and y coordinates that I then calculate a centroid from using the following R function:
cnt = c(mean(m[,1]),mean(m[,2]))

I then take that same list and calculate the distance from each x,y pair to that centroid. Lastly, I then take the mean distance over all the records from the centroid using the following code:
mean_distance <- mean(apply(m,1,function(x,cnt) {(sqrt((x[1] - cnt[1])^2+(x[2]-cnt[2])^2))},cnt))

I think I got the first part figured out (finding the centroid coordinates)
cnt\left(x, y\right)   = \frac{\sum x_{i}}{n}, \frac{\sum y_{i}}{n}

I'm having trouble with the second calculation. I'm new to latex and would like to create (an elegant) formula to include in a paper I am writing. Is there any easy way to convert this R code to latex?

A: You can try something like
$$
C(x,y) = (C_1, C_2) = \left( \frac1n\sum_{i=1}^n x_i,\frac1n\sum_{i=1}^n y_i\right)
$$

$$
d = \frac1n \sum_{i=1}^n \sqrt{\left( x_i-C_1\right)^2+\left( y_i-C_2\right)^2}
$$

if I understood what you want.


text:
Q: datagridView filter and sort vb.net I have the following problem.
I've a datagridView which has as datasource a list of(objects).
I need to filter the list with a text inserted in a textbox. For this, I use the following code.
datagridView.datasource = list.findAll(Function (x) x like textbox.text).toList

On the other hand, I need to sort the datagridView when the events clickHeaderColumn is raised.
For this, I use the following code
Private Sub DataGridView_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView.ColumnHeaderMouseClick
If DataGridView.Columns(e.ColumnIndex).Name = column.Name Then
 Dim currentSortOrder = DataGridView.Columns(e.ColumnIndex).HeaderCell.SortGlyphDirection
If currentSortOrder = SortOrder.None OrElse currentSortOrder = SortOrder.Descending Then currentSortOrder = SortOrder.Ascending
datagridView.datasource = list.orderby(Function (x) x.columnName).toList
 Else
currentSortOrder = SortOrder.Descending
datagridView.datasource = list.orderByDescending(Function (x) x.columnName).toList
 End If DataGridView.Columns(e.ColumnIndex).HeaderCell.SortGlyphDirection = currentSortOrder
 End If End Sub

This last code works perfectly until I apply the filter code. Then I can not order.
The filter code works with a timer like a search bar.


text:
Q: jQuery - How to remove class if clicking outside of div or open/close button I'm fairly new to JS and I can't quite figure out how to get this to work. Any help is very much appreciated! So I have a hamburger button that, when clicked, simultaneously toggles the animation of a slide-in panel and hamburger animation by adding a class to the panel and button. I have successfully added a click event to close the panel if user clicks anywhere outside of the panel but I can't get the hamburger button to remove the added classes as well. I'd like the user to have both options (click button or click outside of panel).
HTML:

    <button class="mpp-menu-icon mpp-menu-icon--cross toggle-menu">

      menu
    </button>

Home

About

JS:
jQuery(document).ready(function($) {

    var openSidebar = function() {
        $('.menu--slide-right').addClass('is-active');
        $('.toggle-menu').addClass('is-active');
        $('#toggle-menu').addClass('toggle-close');
    }
    var closeSidebar = function() {
        $('.menu--slide-right').removeClass('is-active');
        $('.toggle-menu').removeClass('is-active');
        $('#toggle-menu').removeClass('toggle-close');
    }

    $('.toggle-menu').click(function(event) {
        event.stopPropagation();
        openSidebar();
    });

    $(document).click(function(event) {
        if (!$(event.target).closest('.menu--slide-right').length) {
            closeSidebar();
        }
    });
});

And here's a JSFIDDLE to demo what I have so far

A: Very simple fix - add an "open" variable which changes to true when the sidebar opens, and evaluate this variable in your click event handler.
Add the variable:
var open = false;

Add the variable mutators to your open and close functions:
var openSidebar = function(){
    $('.menu--slide-right').addClass('is-active');
    $('.toggle-menu').addClass('is-active');
    $('#toggle-menu').addClass('toggle-close');
    open = true; //This is the new part!
}

Then toggle which function to call on button click - I achieve this with a ternary operator:
$('.toggle-menu').click( function(event) {
    event.stopPropagation();
    var toggle = open ? closeSidebar : openSidebar;
    toggle();
});

Check the fiddle here

A: A quick and dirty way to fix this is to change your openSideBar function to use jQuery's toggleClass method, i.e.:
 var openSidebar = function() {
  $('.menu--slide-right').toggleClass('is-active');
  $('.toggle-menu').toggleClass('is-active');
  $('#toggle-menu').toggleClass('toggle-close');
}

This way when a user clicks on the button, it will toggle the class on/off, and you already have the code to turn it off when they click outside of the button.
Check it out here: https://jsfiddle.net/5ssccz2a/2/
jQuery .toggleClass(): http://api.jquery.com/toggleclass/

A: The simplest and most robust way would be to check if one of your classes are active on the button. So also no extra variables are needed. I would recommend, deciding on one class to control the others.
$('.toggle-menu').click(function(event) {
      if ($('.toggle-menu').hasClass('is-active') {
         closeSidebar();
      }
      else {
         openSidebar();
      }
      event.stopPropagation();
  });

A: Test for .is-active class before deciding whether to run closeSidebar() or openSidebar() when .toggleMenu is clicked.
$('.toggle-menu').click( function(event) {
    event.stopPropagation();
    if( $(this).is('.is-active') ) {
        closeSidebar();
    } else {
        openSidebar();
    }
});

DEMO
Or, using the ternary operator:
$('.toggle-menu').click( function(event) {
    event.stopPropagation();
    $(this).is('.is-active') ? closeSidebar() : openSidebar();
});

DEMO