Q:

set linkbutton as default button for asp:panel in asp.net

Possible Duplicate:
Link Button on the page and set it as default button, work fine in IE but not in Mozila

How to set linkbutton as default button for asp:panel in asp.net? I know a button can be set as default but my application uses linkbuttons for all forms. Any suggestion how it can be done.
EDIT:
Now i tried this,
It works in firefox as well but my javascript validation (ie) onclient click of my linkbutton doesn't work why?
var __defaultFired = false;

        function WebForm_FireDefaultButton(event, target) {
            var element = event.target || event.srcElement;

            if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {
                var defaultButton;

                if (__nonMSDOMBrowser)
                    defaultButton = document.getElementById(target);
                else
                    defaultButton = document.all[target];

                if (defaultButton) {
                    if (typeof (defaultButton.click) != "undefined")
                        defaultButton.click();
                    else
                        eval(unescape(defaultButton.href.replace("javascript:", "")));

                    event.cancelBubble = true;

                    if (event.stopPropagation) event.stopPropagation();
                    return false;
                }
            }
            return true;
        }

Second EDIT:
I was able make my custom linkbutton control work but couldn't able to hook OnClientClick to it. Source using-panel-defaultbutton-property-with-linkbutton-control-in-asp-net.
and i did this,
<%@ Register Namespace="App_Code" TagPrefix="ac" %>
<asp:Label runat="server" ID="lblHello" />
<asp:Panel runat="server" DefaultButton="lbHello">
    First name: <asp:TextBox runat="server" ID="txtFirstName" />
    <ac:LinkButtonDefault ID="lbHello" runat="server" Text="Click me"
        OnClientClick="javascript:alert('hai');" OnClick="lbHello_Click" />
</asp:Panel>

My Clientside function doesn't work why? Any suggestion.

A:

Rather than use a custom control you could take the simple approach of adding an attribute to handle the textbox's onKeyPress event. This correctly handles pressing Enter from the textbox and triggering the LinkButton's event. The downside to this approach is that any LinkButton OnClientClick event will not be triggered in Firefox, which is related to the issue described in that blog post you linked to. It will only be triggered when the user actually clicks on the link with their mouse. However, in IE, it will trigger from both the textbox and from being clicked on directly.
Solution #1 - The code to add the attribute is as follows:
protected void Page_Load(object sender, EventArgs e)
{
    txtFirstName.Attributes.Add("onKeyPress",
        "javascript:if (event.keyCode == 13) __doPostBack('" + lbHello.ClientID + "','')");
}

Try that and see if it fits your needs. Just bear in mind the limitation I described earlier.
Now, if you want the above limitation to go away, one of the comments from that blog post showed an approach that appears to work correctly. I've modified it to get rid of the StringBuilder and converted it to C#.
Solution #2 - The code to add the function and register it is as follows:
protected void Page_PreRender(object sender, EventArgs e)
{
    string addClickFunctionScript = @"function addClickFunction(id) {
           var b = document.getElementById(id);
           if (b && typeof(b.click) == 'undefined')
             b.click = function() {
               var result = true;
               if (b.onclick) result = b.onclick();
               if (typeof(result) == 'undefined' || result)
                 eval(b.getAttribute('href'));
             }
         };";

    string clickScript = String.Format("addClickFunction('{0}');", lbHello.ClientID);

    Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
    Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + lbHello.ClientID, clickScript, true);
}

Page Markup -
The page mark-up is the same for both of the aforementioned solutions:
<asp:Label runat="server" ID="lblHello" />
<asp:Panel ID="Panel1" runat="server" DefaultButton="lbHello">
    First name:
    <asp:TextBox runat="server" ID="txtFirstName" />
    <asp:LinkButton ID="lbHello" runat="server" Text="Click me" OnClick="lbHello_Click"
         OnClientClick="javascript:alert('Hello, World!');"/>
</asp:Panel>

In both cases a custom control is not needed to achieve this type of functionality. Keep it simple.


Q:

How can I iterate a dataTable into vutify?

I want to iterate my arrangement on a vuetify board but I haven't found the logic yet since I'm starting with vue, if someone could give me an example of how to iterate a vutify board would be perfect
example :
 <article class="artkccle-item" v-for="person in persons" :key="person.id">
  <v-data-table :headers="headers"  :items-per-page="5" class="elevation-1">
    <v-item>{{person.id}}</v-item>

  </v-data-table>
</article>

persons is my array

A:

Like the doc says, you have to provide the table headers description, and the table content.
Header's description must be objects like this:
headers: [
  {
    text: 'Dessert (100g serving)',
    align: 'left',
    sortable: false,
    value: 'name',
  },
  ...
]

The value key is the most important because it's the key that will be picked in each row item for display.
After providing the headers, provide your data :
{
   name: 'Frozen Yogurt',
   calories: 159,
   fat: 6.0,
   carbs: 24,
   protein: 4.0,
   iron: '1%',
}

With the headers provided above, the table will have one column only, and one row only with the data "Frozen Yogurt" (picked from "name" key of the object).
For information, you can see the code details on each vuetify-doc examples by using the "<>" icon, you will see a complete example.
https://vuetifyjs.com/en/components/data-tables


Q:

Regex works on .NET test site but not in C# environment

Referring to this stackoverflow question:
- Regex Pattern help: finding HTML pattern when nested ASP.NET Eval?
I received an answer to the problem here:
- regexstorm link
The .NET answer that works on the regex .NET testing site does NOT work in my C# Visual Studio environment. Here is the Unit Test for it:
[Test]
public void GetAllHtmlSubsectionsWorksAsExpected()
{
    var regPattern = new Regex(@"(?'o'<)(.*)(?'-o'>)+");

    var html =
        "<%@ Page Language=\"C#\" %>" +
        "" +
        "lorem ipsum" +
        "<div class=\"d1\" id=\"div2\" attrid=\"<%# Eval(\"CategoryID\") %>\">" +
        "testing 123" +
        "
" +
        "asdf" +
        "	";

    List<string> results = new List<string>();

    MatchCollection matches = regPattern.Matches(html);
    for (int mnum = 0; mnum < matches.Count; mnum++)
    {
        Match match = matches[mnum];
        results.Add("Match #" + (mnum + 1) + " - Value: " + match.Value);
    }

    Assert.AreEqual(5, results.Count()); //Fails: results.Count() == 1
}

Why does this work on the regexstorm website but not in my unit test?

A:

NOTE that parsing HTML with regex is not a best practice, you should use a dedicated parser.
Now, as for the question itself, the pattern you use will work only with lines having 1 single substring starting with < and ending with corresponding >. However, your input string has no newline characters! It looks like:
<%@ Page Language="C#" %>lorem ipsum<div class="d1" id="div2" attrid="<%# Eval("CategoryID") %>">testing 123
asdf

The .* subpattern is called a greedy dot matching pattern, and it matches as many characters other than a newline as possible (because it grabs the whole line and then backtracks to see if the next subpattern (here, >) is found, thus you get the last possible >).
To fix that, you need a proper balanced construct matching pattern:
<((?>[^<>]+|<(?<c>)|>(?<-c>))*(?(c)(?!)))>

See regex demo
C#:
var r = new Regex(@"
    <                      # First '<'
      (                    # Capturing group 1
        (?>                # Atomic group start
        [^<>]              # Match all characters other than `<` or `>`
        |
         < (?<c>)          # Match '<', and add a capture into group 'c'
        |
         > (?<-c>)         # Match '>', and delete 1 value from capture stack
        )*
        (?(c)(?!))         # Fails if 'c' stack isn't empty!
      )
    >                      # Last closing `>`
"; RegexOptions.IgnoreWhitespace);

DISCLAIMER: Even this regex will fail if you have unpaired < or > in your element nodes, that is why do not use regex to parse HTML.


Q:

python2.7 xlsxwriter doesn't write more then 65533 rows

Hi I am tring to create a xlsx file but, I can write more the 65533 rows
the object I am using is Xlsxwriter?
how can I write more rows?

A:

Simple test:
import xlsxwriter
workbook = xlsxwriter.Workbook("test.xlsx")
sheet = workbook.add_worksheet()
for i in range(1, 70000):
    sheet.write('B' + str(i), "Blub")
workbook.close()

After that I have opened the file test.xlsx in Libreoffice, eh voila :)


Q:

MSVC: what compiler switches affect the size of structs?

I have two DLLs compiled separately, one is compiled from Visual Studio 2008 and one is a mex file compiled from matlab.
Both DLLs have a header file which they include. when I take the sizeof() the struct in one DLL it returns 48, and in the other it returns 64.
I've checked the /Zp switch and in both compilations it is set to /Zp8.
What other compiler switches may affect the size of a struct?
The struct is a simple POCO with no inheritance and no virtual functions.

Edit
The struct looks like this:
class LIBSPEC SGeometry
{
public:

    std::vector<IGeometry> m_i;
    uint N;
    uint n_im, n_s;
};

In debug it sizeof() returns 56 in both cases, in release, in the mex compilation it's 48, from VS it's 64.
I can tell matlab the exact compiler options to use when compiling the mex so it's not it.

Edit
After checking with offsetof, it turns out that the difference is in the size of the std::vector. in one dll it's 32 and in the other it's 48.
Both dlls are x64.

A:

Ok, so this is possibly the most obscure thing ever.
It turns out that matlab add /D_SECURE_SCL=0 to the compilation which disables something called 'secure iterators'
This in turn causes a difference of 16 bytes in the size of std::vector


Q:

Will converting images to DNG improve post-processing performance in Lightroom?

I would like to know if converting my RAW files to DNG will improve the overall speed of Lightroom. The most painful issue is that it takes between 5 and 10 seconds to get my 1:1 image rendered when I zoom on it. I should add that my LR is configured so that it creates the 1:1 preview during importing of the files.
I use a MacBook Pro, Canon's RAWs, Lighroom 3.2. Thanks :)

A:

All image previews are stored as JPEG files of various sizes inside of a .lrprev file. The loading speed of the preview images will likely not change much if you switch to DNG. The benefit of DNG is that it is an open standard format, and can keep the metadata in the same file as the image data, which simplifies portability. On the flip side, you would incur not only the extra cost of generating 1:1 previews on import, but also converting from your native RAW to DNG raw.
You also have to consider that DNG stores image data in a specific way, using integer values for pixel data. That will generally work for most sensors, however there are some special sensors that use non-square bayer arrays, make use of extra luminance pixels, or might possibly use floating point numbers rather than integers to store individual pixel values. At the very least, if you convert to DNG, you should keep your original RAW images around.

A:

Adding to jrista's answer, you can always embed your original RAW file to the DNG file (in the Preferences dialog, under the tab File Handling). This way you can keep your original RAW files. Or you keep them separated, it is up to you.


Q:

Are all torsion groups finite groups?

Are all torsion groups finite groups?

I've been trying to find a counter example, but have had no luck so far. Can anyone throw me one, or give me an idea to prove this?

A:

Take infinite direct sum of finite abelian groups. For finitely generated examples google "Burnside problem".
If you do not know what is the direct sum of groups, take the group of roots of unity:
$$
\{ e^{i\pi r}: r\in {\mathbb Q}\}.
$$


Q:

Apache Ignite activating cluster takes a long time

I am trying to set up a cluster of Apache Ignite with persistence enabled. I am trying to start the cluster on Azure Kubernetes with 10 nodes. The problem is that the cluster activation seems to get stuck, but I am able to activate a cluster with 3 nodes in less than 5 minutes.
Here is the configuration I am using to start the cluster:
apiVersion: v1
kind: Service
metadata:
  name: ignite-main
  annotations:
    service.beta.kubernetes.io/azure-load-balancer-internal: "true"
  labels:
    main: ignite-main
spec:
  type: LoadBalancer
  externalTrafficPolicy: Cluster
  ports:
    - port: 10800 # JDBC port
      targetPort: 10800
      name: jdbc
    - port: 11211 # Activating the baseline (port)
      targetPort: 11211
      name: control
    - port: 8080 # REST port
      targetPort: 8080
      name: rest
  selector:
    main: ignite-main
---

#########################################
# Ignite service configuration
#########################################

# Service for discovery of ignite nodes
apiVersion: v1
kind: Service
metadata:
  name: ignite
  labels:
    app: ignite
spec:
  clusterIP: None
  # externalTrafficPolicy: Cluster
  ports:
    # - port: 9042 # custom value.
    #   name: discovery
    - port: 47500
      name: discovery
    - port: 47100
      name: communication
    - port: 11211
      name: control
  selector:
    app: ignite
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ignite-cluster
  labels:
    app: ignite
    main: ignite-main
spec:
  selector:
    matchLabels:
      app: ignite
      main: ignite-main
  replicas: 5
  template:
    metadata:
      labels:
        app: ignite
        main: ignite-main
    spec:
      volumes:
      - name: ignite-storage
        persistentVolumeClaim:
          claimName: ignite-volume-claim # Must be equal to the PersistentVolumeClaim created before.
      containers:
      - name: ignite-node
        image: ignite.azurecr.io/apacheignite/ignite:2.7.0-SNAPSHOT
        env:
        - name: OPTION_LIBS
          value: ignite-kubernetes
        - name: CONFIG_URI
          value: https://file-location
        - name: IGNITE_H2_DEBUG_CONSOLE
          value: 'true'
        - name: IGNITE_QUIET
          value: 'false'
        - name: java.net.preferIPv4Stack
          value: 'true'
        - name: JVM_OPTS
          value: -server -Xms10g -Xmx10g -XX:+AlwaysPreTouch -XX:+UseG1GC -XX:+ScavengeBeforeFullGC -XX:+DisableExplicitGC
        ports:
        - containerPort: 47100 # communication SPI port number.
        - containerPort: 47500 # discovery SPI port number.
        - containerPort: 49112 # JMX port number.
        - containerPort: 8080  # REST port number.
        - containerPort: 10800 # SQL port number.
        - containerPort: 11211 # Activating the baseline (port)
      imagePullSecrets:
        - name: docker-cred

A:

I was trying to activate the cluster remotely by providing --host parameter, like:
./control.sh --host x.x.x.x --activate

Instead, I tried activating the cluster by logging into one of the kubernetes nodes and activating from there. The detailed steps are mentioned here


Q:

What is the safest medium on which to store my wallet/private keys?

What is the safest medium on which to store my wallet/private keys?
I avoid eWallets like the plague.
I have my wallet on my computer at the moment with the Bitcoin passphrase encryption and I have a few backups on different harddrives/USB drives.
But USB drives don't seem to be the most reliable thing to store wallets on, and I want to move my wallet off my computer for improved safety, so I was looking at paper wallets and they seem good apart from if they deteriorate over time, or from things like water damage etc.
CDs seem okay to use but they can also get scratched and can't be updated once burnt.
I'd also rather avoid cloud file services.
A plastic card that I could print my public/private keys on seemed like a good idea, but this would have to be printed by a third party as card printers are expensive, unless there's somewhere I can go to do it myself.
Any recommendations on the safest medium to store Bitcoins on?

A:

Print out your private keys to a Paper Wallet and print the keys on Archival Quality Paper. Those should last until the year 2211. They are however un-encrypted so you should store them in a bank safety-deposit-box or somewhere just as safe.

A:

You probably should ask this question on other Stack Exchanges, like Super User, as the question is not specific to Bitcoins really.
Safest place to store your wallet key would be in your memory, if you are a type that can recall a long string of digits many years later. You could try using some mnemonic tricks, like encoding the numbers in a poem with number of letters in each word corresponding to a given number.
If you want something tangible, you should look into putting the key on some medium that does not deteriorate over a long period of time. You can try scratching it into a sheet of plastic, or using some soldering iron to melt it in. You could also go for carving it in stone or cement block, but that would start to get a bit excessive. You can always get a laminating device, print your wallet as a QR code and laminate it, should work well enough while not being too expensive.
It all boils down to how much time and money you want to spend securing your wallet and what hazards you want to protect it from.


Q:

converting json with gson error Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

[{"user_id":"5633795","username":"_Vorago_","count300":"203483","count100":"16021","count50":"1517","playcount":"1634","ranked_score":"179618425","total_score":"1394180836","pp_rank":"34054","level":"59.6052","pp_raw":"1723.43","accuracy":"96.77945709228516","count_rank_ss":"1","count_rank_s":"19","count_rank_a":"17","country":"US","events":[]}]

I'm trying to convert the JSON above with GSON but am running into errors.
package com.grapefruitcode.osu;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import com.google.gson.Gson;

public class Main {

static String ApiKey = "";
public static void main(String[]Args) throws Exception{
    String json = readUrl("");
    System.out.println(json);
    Gson gson = new Gson();
    User user = gson.fromJson(json, User.class);
    System.out.println();
}

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

}

The url and api key are left blank for security reasons, the variables are filled when I run the code and the json is converted to a string properly. I've tested it already. If somebody could tell me what is causing the error that would be wonderful.
package com.grapefruitcode.osu;

public class User {
 String user_id = "";
 String username = "";
 String count300 = "";
 String count100= "";
}

A:

In JSON

[ ... ] represents array
{ ... } represents object,

so [ {...} ] is array containing one object. Try using
Gson gson = new Gson();
User[] users = gson.fromJson(json, User[].class);
System.out.println(Arrays.toString(users));
//or since we know which object from array we want to print
System.out.println(users[0]);


Q:

How does the USA. have jurisdiction over FIFA?

It is not a surprise that the FBI (or CIA) investigates or closely monitors an organization. However, I don't understand when they arrest several of FIFA's members, some of whom are not American, in Switzerland. FIFA is based in Switzerland. Shouldn't the Swiss government be involved in the public arrest and trial of FIFA's executives and board members?

A:

Absent international treaties on the matter, every country is free to decide what it has jurisdiction over. That's because jurisdiction just controls what that country's courts do -- American jurisdiction means that American courts are willing to try the person and American law enforcement can arrest them if they set foot in America, and the only time the US doesn't get to establish jurisdiction is if US law prevents it (e.g. the Constitution) or if an international treaty forbids it (e.g. diplomatic immunity).
In this case, the allegations involved the use of US banks, and are heavily focused on the Miami-based CONCACAF. Several companies involved are US companies. US law gives jurisdiction at fairly low levels of connection to the US, and no one else gets a say in the matter. It's the same way in other places; Spain had a judge (Baltasar Garzón) who was (in)famous for making heavy use of their universal jurisdiction laws to investigate human-rights abuses having nothing to do with Spain, but which Spanish law could prosecute.
Of course, the fact that US law gives jurisdiction is only binding on US law enforcement and US courts. US courts can't order Swiss police to make an arrest or send someone to the US, and US police can't go into a Swiss hotel and slap handcuffs on people; for the arrest, there needs to be Swiss involvement (or use of force by the US, like in Panama in 1989; that's not typically the preferred option, though). If the US claimed jurisdiction over a German citizen mugging a French citizen in Poland, Switzerland would basically just laugh at the request (and if US law allowed jurisdiction there, Switzerland wouldn't enter an extradition treaty with the US).
However, in this case people in Switzerland were arrested by the Swiss, who absolutely do have the power to arrest anyone in Switzerland if allowed by Swiss law. Switzerland has agreed to normally extradite people to the US if they're not Swiss and if they're wanted in the US for violating certain kinds of laws by doing something that's also illegal in Switzerland. So, the Swiss (exercising their jurisdiction over anyone in Switzerland) put the people on a flight to the US according to Swiss law. When the flight lands, the people are in the US, and US law enforcement then take them before a US court that only cares about US law.


Q:

Connection to dev@redshift-cluster-1. failed

I am using DataGrip to connect to my AWS Redshift cluster.
Unfortunately, the connection failed.
Connection to dev@redshift-cluster-1.cfioxtdojc5x.eu-central-1.redshift.amazonaws.com failed. [28000][10100] [Amazon][JDBC](10100) Connection Refused: [Amazon][JDBC](11640) Required Connection Key(s): UID; [Amazon][JDBC](11480) Optional Connection Key(s): AccessKeyID, AuthMech, AutoCreate, BlockingRowsMode, ClusterID, DbGroups, DisableIsValidQuery, DriverLogLevel, EndpointUrl, FilterLevel, IAMDuration, Language, loginTimeout,

I checked jdbc driver,it seems OK

Properties

What else could cause this problem?
VPC?

A:

I guess you might be using wrong JDBC Redshift Driver or configuring Datagrip the wrong way.
Please follow this documentation-( Hope it helps )
Redshift-Datagrip-Forum
I am Asuming you are using the latest 2019 Version,
I am using the version 1.2.1.1001 JDBC Redshift Driver version.
Step 1 ->

Step 2 - >

The Error you got happens usually because of -

Driver Related Issues
N/W Access ( VPC's , Subnets, SG's etc etc)
If you are tunneling to an EC2 and then connecting to redshift then, you should be really careful about where is this VM ( VPC i.e point 2 ). You can do a telnet and check if the EC2 is able to connect to redshift or not.

Yesterday I came across a similar issue but that is not related to datagrip.
I was running a spark Job on EMR when I encountered a similar issue .
ERROR -
19/08/28 08:54:17 ERROR RedshiftCommunicator: Error occured while Creating Redshift Tables. **Reason [Amazon][JDBC](10100) Connection Refused: [Amazon][JDBC](11640) Required Connection Key(s)**: PWD; [Amazon][JDBC](11480) Optional Connection Key(s): AccessKeyID, AuthMech, BlockingRowsMode, ClusterID, DbGroups, DisableIsValidQuery, DriverLogLevel, EndpointUrl, FilterLevel, IAMDuration, Language, loginTimeout, OpenSourceSubProtocolOverride, plugin_name, profile, Region, SecretAccessKey, SessionToken, socketTimeout, ssl, sslcert, sslfactory, sslkey, sslpassword, sslrootcert, SSLTruststore , SSLTrustStorePath, tcpKeepAlive, TCPKeepAliveMinutes, unknownLength
java.sql.SQLNonTransientConnectionException: [Amazon][JDBC](10100) Connection Refused: [Amazon][JDBC](11640) Required Connection Key(s): PWD; [Amazon][JDBC](11480) Optional Connection Key(s): AccessKeyID, AuthMech, BlockingRowsMode, ClusterID, DbGroups, DisableIsValidQuery, DriverLogLevel, EndpointUrl, FilterLevel, IAMDuration, Language, loginTimeout, OpenSourceSubProtocolOverride, plugin_name, profile, Region, SecretAccessKey, SessionToken, socketTimeout, ssl, sslcert, sslfactory, sslkey, sslpassword, sslrootcert, SSLTruststore , SSLTrustStorePath, tcpKeepAlive, TCPKeepAliveMinutes, unknownLength
    at com.amazon.exceptions.ExceptionConverter.toSQLException(Unknown Source)
    at com.amazon.jdbc.common.BaseConnectionFactory.checkResponseMap(Unknown Source)
    at com.amazon.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
    at com.amazon.jdbc.common.AbstractDriver.connect(Unknown Source)
    at com.amazon.redshift.jdbc.Driver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at com.hp.ta.utils.RedshiftCommunicator.recreateReportTables(RedshiftCommunicator.java:237)
    at com.hp.ta.apps.spark.CpuMemSilverJob.run(CpuMemSilverJob.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.hp.ta.controllers.AppRunner.main(AppRunner.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Command exiting with ret '1'

The Above issue was solved by -

Properly Configuring the IAM role Attached to the EMR with Redshift get_credentials Policy.
Also ensured same IAM Role is also being read by my spark code via spark env configs.

I know the above is a bit un-related but it might help you debugging the issue.
Another Request -
Can you please update your description with a few more details like -

Are you using SSH Tunneling ?
Security Groups ( is your IP Whitelisted for redshift accessing ) ( which i guess it is because the error is about credentials )
Have you tried connecting to redshift via SQL WorkbenchJ ?

An advice out of practice , You should also start with keeping your Redshift cluster encrypted ( atleast at server level using services like KMS or any other service ).


Q:

Как унаследоваться от родительского класса?

Есть ли способ классу Mail унаследовать класс Program, кроме способа передачи в Mail экземпляра Program? Что-то иные варианты у меня не работают.
from kivy.app import App

class Mail(object):
    def __init__(self, program):
        self.pr = program

    def get_var(self):
        print self.pr.var

class Program(App):
    def __init__(self, **kvargs):
        super(Program, self).__init__(**kvargs)
        self.var = True

        b= Mail(self)
        b.get_var()

program = Program()

A:

from kivy.app import App

class Mail(object):
    def __init__(self):
        self.x()

    def get_var(self):
        print self.var

class Program(Mail, App):
    def __init__(self, **kvargs):
        super(Program, self).__init__()
        self.var = True
        self.get_var()

    def x(self):
        print('I function x class Program')

   program = Program()


Q:

Loss data after space in EJS form

There is an EJS file with a form, that has a <select> drop-down list.
   <form action="/scheduler/jobEvent" method="POST">

        <select class="custom-select" id="addJobEvent" name="event[title]">
          <option selected>Select</option>

          <% personnelList.forEach(person => { %>
            <option value=<%- person.title %>><%- person.title %></option>
          <% }) %>
        </select>

        <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-outline-success">Save Event</button>

    </form>

The list is filled up dinamically from DB. Click on submit sends form's data to back-end JS file, where it is further processed:
router.post('/scheduler/jobEvent', middleware.loggedAsAdmin, async (req,res) => {
    var personTitle = req.body.event.title;
        console.log(personTitle);
});

The list itemizes people nicknames, that consist of a given name and the first letter of surname, e.g.
John H, Mike K, etc. And I found out that everything in nickname after space is being lost while transmitting from form to back-end. That is John H shortens to just John when console.log it in JS. Below is my troubleshooting:

Nickname is displayed properly with the letter after space on the list when rendering the EJS file, and so all data is transmitted from DB to <%- person.title %>.
I hardcoded nickname in the list, i.e. <option value='John H'><%- person.title %></option> and it comes to the back-end file in the same way, and so nothing loses between client and server-side.
I added underscore in nicknames in the DB, i.e. John_H and it works as it should be without losses, that is it relates somehow to space.
Has anyone encountered such an issue?
Thank you in advance.

A:

Compare the working and non-working code:

<option value=<%- person.title %>>

and

<option value='John H'>

What is different?
quotes
If you don't have quotes around an attribute value, then a space ends the value and whatever comes after the space starts a new attribute.


Q:

Node.js parser for link headers?

I'm using the Github API, which uses Link Headers, as defined here, for pagination.
Currently I'm just extracting 'next' URLs using some string manipulation but I was wondering if there was a proper module for this purpose (I haven't been able to find anything in 'npm search').
Thanks!

A:

There's this: https://npmjs.org/package/parse-links
It looks a bit fragile, to my mind, but it looks like it will do very basic parsing.


Q:

Bug in ng repeat with radio buttons

Im trying use radio button with ng-repeat, but when the repetitions are constructed the form dont bind the right way, bugs all radio -_-, what am i doing wrong? Like when I click in radio button change all or no one. I'm using angular js 1 and materialize.
Aqui: parte da estrututa do objeto
$scope.paineis = [
  {
    id:0,
    listaCotacoes:[
     {id:0, situacao:0},
     {id:1, situacao:4}
    ]
  },
  {
    id:1,
    listaCotacoes:[
     {id:6, situacao:0},
     {id:9, situacao:4}
    ]
  }
];

      description
      lock_open
      block
       thumb_up
       thumb_down
       21/02/2014

          <form action="">

                       <input name="{{cotacoes.id}}" type="radio" id="aberta" ng-checked="cotacoes.situacao == 0"  value="0" ng-model="cotacoes.situacao"/>
                       Abrir

                       <input name="{{cotacoes.id}}" type="radio" id="Finalizado" ng-checked="cotacoes.situacao == 2" value="2" ng-model="cotacoes.situacao"/>
                       Finalizado

                        <input name="{{cotacoes.id}}" type="radio" id="Aprovar" ng-checked="cotacoes.situacao == 3" value="3" ng-model="cotacoes.situacao"/>
                        Aprovar

                          <input name="{{cotacoes.id}}" type="radio" id="Reprovada" ng-checked="cotacoes.situacao == 4" value="4" ng-model="cotacoes.situacao"/>
                          Reprovar

               </form>

A:

If your radio buttons are a group i.e where you have to select one from a group. The name "name="{{cotacoes.id}}"" should match on all of them. So instead of having them name="{{cotacoes.id}}" change to name="radio-group" on all of them that should work

    <input type="radio" name="radio" id="radio2" ng-model="selectedItem.style_id" value="2">

     <input type="radio" name="radio" id="radio3" ng-model="selectedItem.style_id" value="3">

     <input type="radio" name="radio" id="radio4" ng-model="selectedItem.style_id" value="4">

     <input type="radio" name="radio" id="radio5" ng-model="selectedItem.style_id" value="5">

name="" attribute groups radio buttons


Q:

How do we determine what distant planets, stars etc are made of?

I remember this being covered somewhat back in school and I have casually read about it. I know it involves inferring from spectral analysis what physical properties an object may have right?
Though I was stumped when trying to give a quick explanation to some friends who ridiculed the idea astronomers can know for certain what composition a distant object has.
I'd love to personally understand what different test are involved but also a quick rebuttal to my friends. It's depressing when people belittle science just because they don't understand something. :/

A:

The major tool in investigating the composition of an astronomical body is spectroscopy.  This technique makes use of the fact that a body composing certain elements/compounds will shine more brightly(or less) at particular wavelengths.  The pattern of 'lines' taken by a spectrograph can then be used to infer the original composition.  This technique is used on Earth as well for calibration and has a pedigree of over 100 years.
A famous example is the discovery of helium, it's existence was discovered in the Sun before on Earth!  This was done by analysing the solar spectrum, and noticing particular dark bands.  These dark bands were where light was being absorbed by the Helium in the solar atmosphere.
The composition of extra solar planet should be taken with a pinch of salt, the science is very new and uses instruments not designed for the task.  Keep an eye out for new missions such as ECHO which might fly in the next 5 to 10 years...
Apart from stellar spectra we can also observe something called the 21cm line.  This a particular emission of Hydrogen, and it helps map out enormous clouds of hydrogen.  The science of astronomical compositions is quite battle hardened, it has survived many years of experiment and undergone much refinement.


Q:

Can I bake 2 small cakes at the same time?

I have to bake 3 small white cholocate mudcakes and put them together to make the final butt shaped cake, which I will ganache and fondant. I have to bake 1 rectangle cake (for the back) and 2 half hemisphere round cakes (for the cheeks).
I have one rectangle pan 13cmx24cm and one 16cm half hemisphere round pan. I was wondering if I could bake the rectangle and one half round cake at the same time in the middle rack of my fan force oven or will that be a risk and make the cakes dry or undercooked? I usually bake them at 150 degrees.

A:

As long as you monitor each cake for doneness individually, there is no reason not to bake them  together—assuming they both need the same temperature.
If the sizes are radically different (in terms of the thinnest dimension, which is usually the depth) you may need to adjust temperature to control crust formation during the time it takes the cakes through to the center.
If the cakes are close in depth, they should bake in approximately equal times.
You may wish to use cake strips or aluminum foil to protect the thing easily burned permiter of a hemispherical cake.
Note that 150 C (300 F) is an atypically low temperature for baking a cake.
See related:  Additional Cooking Time When baking more than one loaf of quick bread


Q:

Was decoupling actually detripling?

As I previously understood it, before recombination, high energy photons were bound up in interactions with excited electrons, meaning electrons couldn't settle into orbit with protons and other nuclei.
However, there were lots of free protons about, whose electric charge would have made them interact electromagnetically. Were photons as much bound up with protons as electrons during this phase? If so, did those interactions produce electron / positron pairs?

A:

From the theory of Thompson scattering (see http://farside.ph.utexas.edu/teaching/em/lectures/node96.html ) we know that a charged particle of mass m interacting with a plane wave electromagnetic field of Strength $E_0$ and frequency $\omega$ has an effective dipole moment of magnitude $$d=\frac{e^2E_0}{m\omega^2}$$
Note that the dipole moment scales inversely with the mass of the charged particle.  It is this dipole moment (actually $d^2$) that determines the amount of energy that the charged particle scatters (radiates) from the electromagnetic field.  Hence electrons with a mass some 2000 times less than that of the proton are much more efficient at interacting with (scattering) a high energy photon.  Technically the protons contribute as well but the overwhelming majority of energy scattering (and hence decoupling) is between electrons and photons.


Q:

How this inequality works?

I'm trying to understand the proof of Malinowski inequality by reading this article. But I don't know how Holder’s Inequality holds. specifically I don't know how this part works:

It says by summing over $i = 1, . . .,n,$ we obtain the last inequality. But I don't know how. And where did the last inequality came from.

A:

It comes from the following inequality: $xy \leq \dfrac{x^p}{p} + \dfrac{y^q}{q}$, with
$x = \dfrac{|a_i|}{\left(\displaystyle \sum_{i=1}^n |a_i|^p\right)^{\frac{1}{p}}}, y = \dfrac{|b_i|}{\left(\displaystyle \sum_{i=1}^n |b_i|^q\right)^{\frac{1}{q}}}$. Also:
$\displaystyle \sum_{i=1}^n \dfrac{|a_i|^p}{\displaystyle \sum_{k=1}^n |a_k|^p}=1$. The same is true for the other part which involves the $|b_i|^p$'s.


Q:

How to find final probability if I know the probability of the individual events leading to it.

I'm trying to understand a homework problem so I'm examining a simpler one.

The chance of getting heads on a single coin toss is .5.
The chance of getting heads at least once with 2 coin tosses is
.75, (3/4).
The chance of getting heads at least twice with 4 coin tosses is
.6875, (11/16).

I got that from simply counting. How would I get the answer without counting, purely with an equation? From the coin toss example, I can see that I can't naively add the .5 chance you have on an individual coin toss for each toss (.5 * n) for n = number of tosses.
What would be the equation to use, with just knowing the probability of the first event and the probability of each successive event, and the number of events? I know this is simple, I can't get it though.

A:

If it is for the events having only two possible outcomes, such as the coin-toss, you can use $$\sum _{r={\frac n2}}^n [(^nC_r)(p)^r(q)^{(n-r)}]$$
where p is the probability of getting the first event, and q is the probability of getting the second event, and $p+q=1$ always. In the coin-toss experiment, we can say that p is the probability of getting heads and q of getting tails. So, $p=\frac12$ and $q=\frac12$.
The above equation is for finding the probability that the event occurs at least $\frac n2$ times, as you gave in your examples. You can change the boundaries of the summation according to the problem.


Q:

is there an SQLite-based wiki?

I would like to find out if there is wiki software that runs on SQLite.

A:

Sure is.
Instiki

Instiki (What Is Instiki) is a basic
  Wiki clone so pretty and easy to set
  up, you’ll wonder if it’s really a
  wiki. Runs on Rails and focuses on
  portability and stability. Supports
  file uploads, PDF export, RSS,
  multiple users and password
  protection. Some use Instiki as a CMS
  - Content Management System because of its ability to export static pages.


Q:

Checking properties on different classes

I have multiple classes that all contain the same property along with a whole of different other properties. The classes don't use any kind of Interface. What I would like to do is pass an instance of each class to a method that can check for the property.
Can generics be used for this? If so, how can I construct a method to perform this task?

A:

Well, you could use reflection... but it would be better to use an interface which specified the property, then you could make each class implement the interface. Generics won't help you here - there's no way of specifying "T must be a type which has property X" for example.
If you're using C# 4 you could use dynamic typing:
public void Foo(dynamic d)
{
    Console.WriteLine(d.MyProperty);
}

However, I would advise you to try to use static typing (via interfaces) if at all possible.

A:

Sounds like a use for dynamic (in C# 4.0)
public void DoMethodThing (dynamic your_object){
   your_object.ThatThingYouDo();
}

http://msdn.microsoft.com/en-us/library/dd264736.aspx


Q:

Event.target issue with Firefox 6

In firefox 6 I tried to get the target element on which the event occured, but it does not show any element and it shows undefined in alert. Tried to debug it using the firebug tool and found the attribute "target" missing for the event object. Can anyone help me out? I do have the code below
function getSource(event)
{
    if(!event)
    {
        field = window.event.srcElement;
       alert(field);
    }
    else
    {
        field = event.target;
        alert(field) //Getting undefined in FF6
    }
}

Edited Portion
document.onkeypress = getSource;
document.onmouseup = getSource;

Any help would be appreciated.

A:

Try the code below
function getSource(e)
{
     if(!e)
        e = window.event;
     field = evt.srcElement || evt.target;
     alert(field);
     return true;
 }

Hope this helps you.


Q:

How to define a function or procedure that includes multiple steps?

I would like to define a procedure or function that takes as input an integer, s, and gives as output two nested lists. I have written code (shown below) that does this for one particular value of s, but I don't know how to generalize it. I would like to be able to get the nested lists for different input values without having to define and re-define s. Any help or suggestions would be much appreciated!
    s = 4;
    popIndicies = Range[s^2];
    list = Table[Table[Partition[popIndicies, s], {3}], {3}];
    test = list;
    output = {};
    Do[temp2 = {};
      Do[
       temp1 = {};
       Do[
        temp0 = {};
Do[AppendTo[temp0, test[[l, i, k, j]]], {j, s}];
AppendTo[temp1, temp0], {i, 3}];
       row = Flatten[temp1];
       AppendTo[temp2, row], {k, s}];
      AppendTo[output, temp2], {l, 3}];
    output = Flatten[output, 1];
    Partition[output, s*3];
    latticeWthPadding = {};
    Do[AppendTo[latticeWthPadding, output[[s + i, s ;; 2*s + 1]]], {i, 0,
       s + 1}];
    neighborhoods = {};
    Do[
     Do[AppendTo[
       neighborhoods, {latticeWthPadding[[i, j]],
        latticeWthPadding[[i, j - 1]], latticeWthPadding[[i, j + 1]],
        latticeWthPadding[[i - 1, j]],
        latticeWthPadding[[i + 1, j]]}], {j, 2, s + 1}], {i, 2, s + 1}]
    latticeWthPadding // TableForm
    neighborhoods // TableForm

A:

The following does (I believe) the same as your code. Perhaps I could do it better if I understood what are you trying to calculate
calc[s_Integer] :=
 Module[{output, latticeWthPadding, neighborhoods},
  output = ArrayFlatten[ Array[1 &, {3, 3}] /. 1 -> Partition[Range[s^2], s]];
  latticeWthPadding = (output[[s + #, s ;; 2*s + 1]]) & /@  Range[0, s + 1];
  neighborhoods = Flatten[Table[Flatten[{Permute[ #[[2]], Cycles[{{1, 2}}]], #[[1, 2]], #[[3, 2]]}]&@
      (latticeWthPadding[[i ;; i + 2, j ;; j + 2]] CrossMatrix[1]), {i, 1, s}, {j, 1, s}], 1];
  {latticeWthPadding, neighborhoods}]

{latticeWthPadding, neighborhoods} = calc[5]


Q:

Mobile friendly over images - lightbox

Good evening, thanks for trying to help first off.
I have a 'portfolio' page with 45 images of houses I've built. They're laid out in a grid, 5 wide 9 down. Simply, when you click and expand the image in browser, it works great. However, when I view on mobile, it get's a little fishy. The image tends to stretch past the view of the screen.
My question is: how can I make the image stay in the viewport of say my mobile device instead of stretching passed the screen? I tried absolutely positioning the overlay, that didn't work.
The lightbox script i'm using: http://tympanus.net/Tutorials/CSS3Lightbox/index3.html
My portfolio page: http://www.ocalaplastering.com/portfolio.html
This would be my html heavily reduced. Multiply the "li" element times 45 and that's basically the page.

                Expand

                Prev
                Next

                x Close

As for the CSS, this is the styles for the aforementioned elements:
.lb-album{
    width: 100%;
    margin: 0 auto;
    font-family: 'BebasNeueRegular', 'Arial Narrow', Arial, sans-serif;
}
.lb-album li{
    float: left;
    padding:0px;
    padding-right:1px;
    padding-bottom:1px;
    position: relative;
    list-style:none;
}
.lb-album li > a,
.lb-album li > a img{
    display: block;
}
.lb-album li > a{
    width: 150px;
    height: 150px;
    position: relative;
    padding: 3px;
    background: #816445;
    -webkit-box-shadow: 1px 1px 2px #fff, 1px 1px 2px rgba(158,111,86,0.3) inset;
    -moz-box-shadow: 1px 1px 2px #fff, 1px 1px 2px rgba(158,111,86,0.3) inset;
    box-shadow: 1px 1px 2px #fff, 1px 1px 2px rgba(158,111,86,0.3) inset;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px 4px 4px 4px;
}
.lb-album li > a span{
    position: absolute;
    width: 150px;
    height: 150px;
    top: 3px;
    left: 3px;
    text-align: center;
    line-height: 150px;
    color: rgba(27,54,81,0.8);
    text-shadow: 0px 1px 1px rgba(255,255,255,0.6);
    font-size: 24px;
    opacity: 0;
    filter: alpha(opacity=0); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
    background: rgb(241,210,194);
    background: -moz-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%, rgba(241,210,194,1) 100%);
    background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(255,255,255,0.56)), color-stop(100%,rgba(241,210,194,1)));
    background: -webkit-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -o-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -ms-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    -webkit-transition: opacity 0.3s linear;
    -moz-transition: opacity 0.3s linear;
    -o-transition: opacity 0.3s linear;
    -ms-transition: opacity 0.3s linear;
    transition: opacity 0.3s linear;
}
.lb-album li > a:hover span{
    opacity: 1;
    filter: alpha(opacity=99); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=99)"; /*IE8*/
}
.lb-overlay{
    width: 0px;
    height: 0px;
    position: fixed;
    overflow: hidden;
    left: 0px;
    top: 0px;
    padding: 0px;
    z-index: 99;
    text-align: center;
    background: rgb(241,210,194);
    background: -moz-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%, rgba(241,210,194,1) 100%);
    background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(255,255,255,0.56)), color-stop(100%,rgba(241,210,194,1)));
    background: -webkit-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -o-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: -ms-radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
    background: radial-gradient(center, ellipse cover, rgba(255,255,255,0.56) 0%,rgba(241,210,194,1) 100%);
}
.lb-overlay > div{
    position: relative;
    color: rgba(27,54,81,0.8);
    width: 550px;
    height: 80px;
    margin: 40px auto 0px auto;
    text-shadow: 0px 1px 1px rgba(255,255,255,0.6);
}
.lb-overlay div p{
    font-size: 14px;
    text-align: left;
    float: left;
    width: 260px;
}
.lb-overlay a.lb-close{
    background: rgba(27,54,81,0.8);
    z-index: 1001;
    color: #fff;
    position: absolute;
    top: 43px;
    left: 50%;
    font-size: 15px;
    line-height: 26px;
    text-align: center;
    width: 50px;
    height: 23px;
    overflow: hidden;
    margin-left: -25px;
    opacity: 0;
    filter: alpha(opacity=0); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
    -webkit-box-shadow: 0px 1px 2px rgba(0,0,0,0.3);
    -moz-box-shadow: 0px 1px 2px rgba(0,0,0,0.3);
    box-shadow: 0px 1px 2px rgba(0,0,0,0.3);
}
.lb-overlay img{
    /* height: 100%; For Opera max-height does not seem to work */
    max-height: 100%;
    position: relative;
    opacity: 0;
    filter: alpha(opacity=0); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
    -webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.3);
    -moz-box-shadow: 1px 1px 4px rgba(0,0,0,0.3);
    box-shadow: 0px 2px 7px rgba(0,0,0,0.2);
    -webkit-transition: opacity 0.5s linear;
    -moz-transition: opacity 0.5s linear;
    -o-transition: opacity 0.5s linear;
    -ms-transition: opacity 0.5s linear;
    transition: opacity 0.5s linear;
}
.lb-prev, .lb-next{
    text-indent: -9000px;
    position: absolute;
    top: -32px;
    width: 24px;
    height: 25px;
    left: 50%;
    opacity: 0.8;
    filter: alpha(opacity=80); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=80)"; /*IE8*/
}
.lb-prev:hover, .lb-next:hover{
    opacity: 1;
    filter: alpha(opacity=99); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=99)"; /*IE8*/
}
.lb-prev{
    margin-left: -30px;
    background: transparent url(../images/arrows.png) no-repeat top left;
}
.lb-next{
    margin-left: 6px;
    background: transparent url(../images/arrows.png) no-repeat top right;
}
.lb-overlay:target {
    width: auto;
    height: auto;
    bottom: 0px;
    right: 0px;
    padding: 80px 100px 120px 100px;
}
.lb-overlay:target img,
.lb-overlay:target a.lb-close{
    opacity: 1;
    filter: alpha(opacity=99); /* internet explorer */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=99)"; /*IE8*/
}
/*
    100% Height for Opera as the max-height seems to be ignored, not optimal for large screens
    http://bricss.net/post/11230266445/css-hack-to-target-opera
*/
x:-o-prefocus, .lb-overlay img {
    height: 100%;
}

There isn't jQuery involved, so i'm assuming it will just be a very simple property to add, but I cannot figure it out.
Cheers for the help!

A:

This can be solved with a simple addition to your CSS on line 355 (.lb-overlay img):
Add a max-width: 100%; below the max-height:100%;
Let me know if that makes it behave how you are expecting!


Q:

HTML: Paragraphs after table, appearing to right of table

We are designing an application that will send e-mail to managers reminding them that they have to do certain approvals.  The e-mail is in HTML form, and contains a table.  We don't understand what we're doing wrong to cause the last paragraph to appear to the right of the table instead of under it.
A sample is below.  The tool "tidy," on which I rely for things like this, has no tips this time.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta content=
"HTML Tidy for Linux/x86 (vers 6 November 2007), see www.w3.org"
name="generator">
<meta content='text/html; charset=us-ascii' http-equiv=
"Content-Type">

<title>Payable Time awaiting approval</title>

Hello, Daffy Duck:

According to our records, the following Payable Time is awaiting
approval. Items shown below must be approved in order for
compensation to take place.

For questions, please contact Support

Awaiting approval by your reporting
structure

Name

ID
Work

Date

Type

Hours

Reporting to Mickey M Mouse (MMM)

Daisy
D_DUCK
04/29/2013
REG
8.00

Daisy
D_DUCK
05/01/2013
REG
8.00

Daisy
D_DUCK
05/02/2013
OT
7.50

This message comes from The Support Team

We would very much like for the text "This message comes from..." to appear below the table, but instead it appears to the right of the table, aligned with the table's top.  This is true for IE7, IE8 and Firefox 12.
I'd appreciate any suggestions to help this situation.
Regards,
Dennis

A:

Just remove the align="left" to your table.
see the link: http://jsfiddle.net/rhyDe/
Tested on IE10, FF24, Chrome 30

A:

you could use similar markup to this: http://jsfiddle.net/7fAy9/2/

      Month
      Savings

      January
      $100

      This is the text you want under the table

or,
you could do something like this: http://jsfiddle.net/NNrnc/

My savings

    Month
    Savings

    January
    $100

but please notice the caption align is deprecated in HTML5,
the correct way to do it in HTML5 would be:

My savings

    Month
    Savings

    January
    $100


Q:

Change view width constraint

I set up width of UIView like this:
contentView.widthAnchor.constraint(equalToConstant: CGFloat(scrollWidth())).isActive = true

Now I want to change that width. The question is: how to remove old constraint and add new? I did create NSLayoutConstraint like this
scrollWidthConstraint = NSLayoutConstraint(
    item: contentView,
    attribute: .width,
    relatedBy: .equal,
    toItem: nil,
    attribute: .notAnAttribute,
    multiplier: 1.0,
    constant: CGFloat(scrollWidth())
)

How to set that constraint for UIView for changing later?

A:

First use this better and short  and assign a reference to it
var widCon:NSLayoutConstraint!

widCon = contentView.widthAnchor.constraint(equalToConstant: CGFloat(scrollWidth()))
widCon.isActive = true

instead of NSLayoutConstraint(item: contentView,  then  Change it's constant
widCon.constant = ////


Q:

Plotting two lists of different lengths versus each other

I have two data lists and would like to plot them versus each other.
list1 = Get["http://pastebin.com/raw/Y9FFBzV5"];
list2 = Get["http://pastebin.com/raw/UjWXjgEL"];

The problem is they are of different length:
Dimensions[list1]
{4882}

Dimensions[list2]
{1392}

I would like to "stretch" list2 to the same length as list1, so that missing data should be interpolated.
UPDATE:
In the plot the minimum point should be {list1[[1]],list2[[1]]}. The maximum point should be (after data processing of list2): {list1[[4882]],list2[[4882]]}
What do I have to do?

A:

Jason. B. has answered to my problem.
His solution is:
ListLinePlot[Thread[{list1, ArrayResample[list2, Length@list1]}],
 Frame -> True, FrameLabel -> {{"list2", ""}, {"list1", ""}}]


Q:

Take data from a field from exsisting node and make that the default value of a field in different content type

I don't know if I'm on the right track but I'm trying to let users of my web site create there own versions of pages on my web site.
Basically I'd like to make our documentation used as a starting point where they just add details and make a new page for themselves in the process.
I have a 'book' content type that I have changed with CCK and a 'client edits' content type that uses a nodereferencefromURL widget to link itself to the book node.
So simple version of what I'm saying is I have a link on my book pages that creates a node using client edits content type. I would like to put some fields on the client edits content type that take the values of some of the fields from the book page it is linked from.
I'm sure I'm missing something as I would have thought someone would have tried this before but I can't even find a hint on how to go about this.
All I really need is a point in the right direction if my current thinking is wrong.
Current thinking is that I use a php script to get the default value for a field on the new node add screen that drags the value for a field from the book I'm linking from.
I'm thinking this is the case because there is an option for default values for the field in cck manage fields that lets you put in a php value to return a default value for your field.
Am I on the right track or is there already a module or process that does what I'm talking about and I'm just too dumb to find it.

A:

I ended up using rules to save information from the user and the cloned node into hidden fields.
One that saved the original node ID into a field when ever you create content of that type unless the url ends with Clone. This means that when you create the clone the original node ID is kept in the field.
That made it easy to use a views argument that took the node ID to make the clone appear along side the original when a user visits the original page.
The second rule trick was to compute a field that saved the "store name" from the profile of the user only when saving clone content.
This meant that there was a hidden field on the clone that stored the info so I could then use another views argument to restrict the view to only people with the same store name in their profile.
I am no good with PHP but I managed to find a snippet (can't remember where) that returns the store name of the current logged in user as the argument.
 global $user;
profile_load_profile($user);
return $user->profile_store_name;


Q:

What would be a cool yet simple way to style an "!" with just CSS?

I want to create a cool looking yet simple exclamation mark with just CSS. Anyone have any cool ideas?

A:

You could find a font that has a very unique "!" and use the Font Squirrel @font-face generator and choose expert settings with custom subsettings and only include the ! character for the font.
Add the font to your stack as the first font and it will only render for the !
For this example I chose Heartbreaker Regular as the font and created an @font-face kit.

The specimen which is falling back to Helvetica for everything except the !.

A:

You can create a simple exclamation mark using pure CSS + HTML markup:
HTML:

This is a simple paragraph

CSS:
.exc_mark {
position: relative;
top: -5px;
left: 3px;
width: 10px;
font-size: 8px;
border: 3px solid #888;
background-color: #888;
border-radius: 3px;
}

.exc_mark span {
position: absolute;
top: 15px;
left: -3px;
border: 3px solid #888;
border-radius: 3px;
height: 1px;
width: 1px;
background-color: #888;
}

The span's CSS will do the work.
It's not the best looking exclamation mark, but you can play with CSS3's border-radius property, border-width and gradients as backgrounds to get a much better look.
Creativity is the limit.


Q:

Add values to dataframe when condition met in R

I have a dataframe like this:
ID1   ID2   Position  Grade   Day
234   756      2        87     27
245   486      4        66     26
321   275      1        54     20
768   656      6        51     7
421   181      1        90     14
237   952      8        68     23
237   553      4        32     30

And I have another dataframe like this:
ID1   ID2   Day  Count
234   756    2     3
245   486    2     1
209   706    2     1
124   554    2     2
237   553    2     4

I need to add the Counts to the first dataframe where the ID1, ID2 and Day are matched. However, I also need to have it so that if there is no match (no Counts in the second dataframe for the set of ID1, ID2 and Day in the first dataframe) then a zero is put in that place.  So the final dataframe would be something like:
ID1   ID2   Position  Grade   Day   Count
234   756      2        87     27     3
245   486      4        66     26     1
321   275      1        54     20     0
768   656      6        51     7      0
421   181      1        90     14     0
237   952      8        68     23     0
237   553      4        32     30     4

A:

This can be useful
> # First, merge df1 and df2
> df3 <- merge(df1, df2, by=c("ID1", "ID2"), all.x=TRUE)
> # Replace NA with 0's
> transform(df3[, -6], Count=ifelse(is.na(Count), 0, Count))
  ID1 ID2 Position Grade Day.x Count
1 234 756        2    87    27     3
2 237 553        4    32    30     4
3 237 952        8    68    23     0
4 245 486        4    66    26     1
5 321 275        1    54    20     0
6 421 181        1    90    14     0
7 768 656        6    51     7     0


Q:

Are there special security recommendations if I run a webserver under Ubuntu desktop edition instead of server edition?

I have a small PC with Ubuntu 10.04 LTS desktop edition used for basic computing and as a backup location. I want to use it to set up a NAS and personal webserver. I've been reading a little bit about having a webserver at home have read some nebulous comments about security concerns of having something like the Gnome shell installed, but nothing I've found has been especially clear why.
Is it safe to run a webserver on a box with desktop packages installed? Are there a few things I can change to prevent security risks? Or do I need to install server edition instead?

A:

Basically, there are no security issues worth worrying about.
Having said that, the more stuff that is on a server, the more possible attack vectors there are. I would guess that a fully patched machine with Gnome on it is going to be more secure than a machine without Gnome that has been left unpatched because you can't be bothered to ssh into it.
You may be interested in having a look at some Gnome Security notes.
If you are not logging on to the machine very often, you could also consider not having Gnome running all the time waiting for you to log in.


Q:

IllegalStateException: Need to use Theme.AppCompat or one of its descendants

I am receiving the following error in my Activity. It is occurring when I try and instantiate an AlertDialog, which I noted below. I am using an AppCompat theme, therefore I am not sure why this error is triggering:
  java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:343)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:312)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:277)
                                                                                at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:80)
                                                                                at android.support.v7.app.AlertController.installContent(AlertController.java:214)
                                                                                at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
                                                                                at android.app.Dialog.dispatchOnCreate(Dialog.java:397)
                                                                                at android.app.Dialog.show(Dialog.java:295)
                                                                                at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:953)
                                                                                at com.troychuinard.fanpolls.NewImageActivity$MyAdapter$1.onClick(NewImageActivity.java:243)
                                                                                at android.view.View.performClick(View.java:5210)
                                                                                at android.view.View$PerformClick.run(View.java:21294)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

However, I am actually applying the theme to my Activity:
Values-V21
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>

The error is occurring when I try and programmatically instantiate a TextInputLyout:
public class CreateActivity extends AppCompatActivity {

private String mParam1;
private String mParam2;

private Button mAddImageButton;

private ImageView mAddAnswersButton;
private ImageView mImagePreview;
private String mSpinnerPosition;

private EditText mCreatePollQuestion;

private View mRootView;

private TextInputLayout mCreatePollAnswer;
private EditText mCreatePollAnswerEditText;
private TextView mCreatePollAnswerCounter;
private int mNumberOfPollAnswersCreatedByUser;
private ViewGroup mEditTextAnswerLayout;
private FloatingActionButton mSubmitPollCreation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create);

    mAddImageButton = (Button) findViewById(R.id.add_image_button);
    mAddAnswersButton = (ImageView) findViewById(R.id.add_answers_button);
    mImagePreview = (ImageView) findViewById(R.id.preview_image);
    mCreatePollQuestion = (EditText) findViewById(R.id.create_poll_question_editText);
    mCreatePollAnswerCounter = (TextView) findViewById(R.id.create_poll_answer_counter_TextView);
    mEditTextAnswerLayout = (ViewGroup) findViewById(R.id.create_poll_questions_answer_layout);
    mSubmitPollCreation = (FloatingActionButton) findViewById(R.id.submit_poll_FAB);
    mNumberOfPollAnswersCreatedByUser = 2;
    mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
    for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++){
        createAnswerChoice(i+1);
    }
    mAddAnswersButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mNumberOfPollAnswersCreatedByUser++;
            if (mNumberOfPollAnswersCreatedByUser > 5){
                Toast.makeText(getApplicationContext(), R.string.max_create_answers, Toast.LENGTH_SHORT).show();
                return;
            }
            createAnswerChoice(mNumberOfPollAnswersCreatedByUser);
            mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
        }
    });

    mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mNumberOfPollAnswersCreatedByUser > 5){
                mNumberOfPollAnswersCreatedByUser = 5;
            }
            for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++){
                EditText editText = (EditText) mEditTextAnswerLayout.findViewWithTag(getResources().getString(R.string.created_answer_editText_id)+String.valueOf(i+1));
                String editTextInputForAnswer = String.valueOf(editText.getText());
                Toast.makeText(getApplicationContext(),editTextInputForAnswer,Toast.LENGTH_SHORT).show();
            }
        }
    });

    mAddImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent toImageSearch = new Intent(getApplicationContext(), NewImageActivity.class);
            startActivityForResult(toImageSearch, 1);
        }
    });

}

//programatically create editText based
private void createAnswerChoice(int answerNumber) {
    EditText editText = new EditText(getApplicationContext());
    editText.setHint(getResources().getString(R.string.answer_text) + " " + answerNumber);
    editText.setSingleLine(true);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
    String editTextID = ((getResources().getString(R.string.created_answer_editText_id))+String.valueOf(answerNumber));
    editText.setTag(editTextID);
    Toast.makeText(getApplicationContext(), editTextID, Toast.LENGTH_SHORT).show();
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    editText.setLayoutParams(layoutParams);
    TextInputLayout newAnswer = new TextInputLayout(getApplicationContext());
    newAnswer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    newAnswer.addView(editText, layoutParams);
    mEditTextAnswerLayout.addView(newAnswer);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if(resultCode == CreateActivity.RESULT_OK){
            String resultURL =data.getStringExtra("result");
            mAddImageButton.setVisibility(View.INVISIBLE);
            Picasso.with(getApplicationContext())
                    .load(resultCode)
                    .into(mImagePreview);
        }
        if (resultCode == CreateActivity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }

}

}

A:

You're using AlertDialog from android.suppport.v7.app package, that's why you need to apply AppCompat theme to the dialog.


Q:

Query update result in huge unexpected number

I have some problems with my hiscore table. Some players have got a lot of points really fast, more then possible. I post two code below:
The first one is the one I currently use, which cause the problem:
$name = mysql_real_escape_string($_POST['name']);
$set = mysql_real_escape_string($_POST['set']);

if ($set == 1 && isset($_POST['score']))
{
    $score = mysql_real_escape_string($_POST['score']);

    $query = mysql_query("UPDATE users SET totalScore=totalScore + '$score' WHERE username='$name'");

    if ($query)
    {
        echo 'success';
    }
    else {
        echo 'error';
    }

}

I tried to cast the score as an int in the code below, but the update result is a huge number (4294967295) to be set as the totalScore. The totalScore is of type int(25) and I set attribute to unsigned so a player can't end up on the minus side.
Please help
Thanks
$name = mysql_real_escape_string($_POST['name']);
$set = (int)$_POST['set'];

if ($set == 1 && isset($_POST['score']))
{
    $score = (int)$_POST['score'];

    $query = mysql_query("UPDATE users SET totalScore=totalScore + $score WHERE username='$name'");

    if ($query)
    {
        echo 'success';
    }
    else {
        echo 'error';
    }

}

A:

if this is the only script that you use to save the score no wonder that people cheated to get high score - in order to prevent it you need to insert some encryption to the parameters, and add some session and time based protections to the script


Q:

How to make a website work with Django development server?

I understand that this is never to be done.  But I have a situation  where I need to get something done real quick.  I have to do a website where may be 200 people would register for an event.  I need to present a simple registration form. Very basic functionality, register and view list of registrants. Very few hits.  It would be live for about a month or so.
I know a little bit of Django which can allow me to put together this thing quickly.  However, I have only worked with the Django development server.
My problem is setting up Apache to work with Django.  I understand that, for Django, I need mod_wsgi installed. I have a VPS but mod_wsgi is not installed.  I have asked my hosting provider to install it for me.  Even if I can get mod_wsgi installed, it appears that it may take me some time to configure it and it may take a while.
I have the following questions.

Can I run this website on the Django development server?  Will it hold up for very light traffic?
If I do, how do I get traffic to go from port 80 to the development server port. From the landing page, I can have the port number added to all the subsequent URLs.

I would also appreciate some guidance on getting Django to work with mod_wsgi.
Thanks

A:

I use cloud9 for development. It is essentially a cloud ubuntu 14 virtual box, so it gives you a real url when django server is running (on port 80). Another use case of cloud 9 is for university classes, which is similar to your event use case. You can go there and setup your django project for free and people can find the page normally. But there are some restarts in your workspace that prevents it to be real server. If you pay 20 bucks per month they give you 2 premium workspaces that they assure that this does not happen ever. But I'm not sure if this is a good idea. I could not even imagine what kind of errors would you get if all 200 people chose to login at the same time, for example.
Another way to go is making a free amazon AWS account (or digital ocean) and doing your deploy there. AWS have 1 year free trial if you run only one microinstance with a particular setup which is plenty of time for your use case. I open the instance on AWS and SSH into it with cloud 9, so it feels like developing even in production. I'm far from a devops expert but I could deploy Nginx, gunicorn, django in AWS following this tutorial. You can do it too for sure, but is a lot of work.
Left my prefered choice for your use case to the end: pythonanywhere. It has free trial and it's really easy to setup. You follow some very basic steps (doing stuff with mod_wsgi that I still dont understand) and make it work in minutes. It's a whole business dedicated to serve python programs.
Hope this helps


Q:

Passing output stream object and other arguments to multiple threads

I'm trying to pass multiple arguments, one of which is an ofstream object, to multiple threads using the C++11 standard.
I want to pass an ofstream object because I want every thread to write in a different output file.
I'm initializing the threads and output streams in this way:
std::thread execution_threads[NUMBER_OF_THREADS]; // creating multiple empty threads
std::ofstream output_files[NUMBER_OF_THREADS]; // Empty output streams
// Opening and initializing the output files

Each thread executes a function that takes two arguments:
void execution(int thread_id, std::ofstream& output_file)

So I've looked around and I've read that in C++11 when a function func has multiple arguments a,b,c,d there's no need to use a struct and you can pass them just by writing std::thread t(func, a,b,c,d);. So I wrote this loop in order to launch the threads:
for (int i = 0; i < utils::NUMBER_OF_THREADS; i++) {
    execution_threads[i] = std::thread(execution, i, output_files[i]);
}

The thing is that this code doesn't compile with this error:
Call to implicitly-deleted copy constructor of
'typename decay<basic_ofstream<char, char_traits<char> > &>::type'
(aka 'std::__1::basic_ofstream<char, std::__1::char_traits<char> >')

While if I use a struct as input in this way, everything works fine:
// Struct definition
struct thread_input {
    int thread_id;
    std::ofstream& output_file;
};

// This is the function that now has only one argument
void execution(struct thread_input input)

// And this is the loop that launches the threads
for (int i = 0; i < utils::NUMBER_OF_THREADS; i++) {
    struct thread_input input = {i, output_files[i]};
    execution_threads[i] = std::thread(execution, input);
}

// join() functions for each thread and end of the program

In this way everything works fine it compiles and it runs perfectly. But I really don't get why the compiler tells me that I'm trying to use the deleted copy-constructor if I use the other method.
Thank you for your help.

A:

std::thread stores a copy of its arguments.  When you pass it a non-copyable object like a std::ofstream it will complain.
You have two options:
1) Don't store an array of std::ofstream objects; just let your threads store their own streams.  In this case, there's no need to copy the stream (just a move, which is fine):
for (int i = 0; i < utils::NUMBER_OF_THREADS; i++) {
    execution_threads[i] = std::thread(execution, i, std::ofstream{});
                                                   //^^^^^^^^^^^^^^^ anonymous temporary
}

Of course, in this case you could just have the thread construct its own stream (maybe just pass in the filename).
2) Pass a std::reference_wrapper<std::ofstream> to your thread.  std::reference_wrapper<T> is an object that holds a reference to T and has an implicit conversion to T&, so you'll just end up copying the reference instead of the stream itself.  You can use the std::ref factory to deduce T and reduce typing:
for (int i = 0; i < utils::NUMBER_OF_THREADS; i++) {
    execution_threads[i] = std::thread(execution, i, std::ref(output_files[i]));
                                                   //^^^^^^^^ std::ref added
}

This leaves you with all of the same ownership and lifetime issues that passing a struct containing a std::ofstream& would have (after all, that's all std::reference_wrapper is).  It's up to you to make sure your output_files array survives until all of your threads have finished with it.


Q:

Issues with building an electron app with serialport

I have been able to run a node.js app using serialport. Now trying to port it to electron for cross-platform use. 'npm install serialport' yielded the following:
  serialport@2.0.5 install /Users/ylh/0/electron/electron-quick-start-master/node_modules/serialport
  node-pre-gyp install --fallback-to-build

  CXX(target) Release/obj.target/serialport/src/serialport.o
  CXX(target) Release/obj.target/serialport/src/serialport_unix.o
  CXX(target) Release/obj.target/serialport/src/serialport_poller.o
  SOLINK_MODULE(target) Release/serialport.node
  COPY /Users/ylh/0/electron/electron-quick-start-master/node_modules/serialport/build/Release/node-v47-darwin-x64/serialport.node
  TOUCH Release/obj.target/action_after_build.stamp

  electron-prebuilt@0.34.3 postinstall /Users/ylh/0/electron/electron-quick-start-master/node_modules/electron-prebuilt
  node install.js

When I ran the app with electron, the pop-up window complains that
The app provided is not a valid electron app, please read the docs on how to write one:
https://github.com/atom/electron/tree/master/docs

Error: Cannot find module '/Users/ylh/0/electron/electron-quick-start-master/node_modules/serialport/build/Release/node-v46-darwin-x64/serialport.node'

Sure enough, the version in the node_modules directory is node-v47-darwin-x64. I don't know why npm install builds v47 but looks for v46 to run.

A:

export npm_config_disturl=https://atom.io/download/atom-shell
export npm_config_target=0.34.3
export npm_config_arch=x64
export npm_config_runtime=electron
HOME=~/.electron-gyp npm install serialport

After this, go to /Users/ylh/0/electron/electron-quick-start-master/node_modules/serialport/build/Release/
And rename electron-0.34-darwin-x64 to node-v46-darwin-x64


Q:

Automatic NSView resizing

I'm doing something with cocoa which I think is a bit complicate for a beginner like me. I tried a few things, but I admit I need some theory first, because I would like to understand exactly the meaning of this concepts.
I see that every NSView and every class that subclasses it has one thing called frame, and one called bounds. They both have a size with width and height and an origin.
I have an NSView with an NSTableView inside of it.
I have the size of a row from the table view, and I would like to set the height of both NSView and NSTableView equal to rows*rowSize, in a way that the group NSView+subviews is automatically resized when an object is added or removed to and from the data source of the Table View.
I made some experiments, but I did end a bit confused about frame, bounds, sizes and so on. I don't know what I should change and how.
Can you please give me an hint about what bounds and frame basically are, and how can I achieve that magic resizing?
Thank you for your replies in advance. Best regards,
—Albé

A:

The difference between frame and bounds is covered very nicely in the View Programming Guide (under View Geometry).
You'll also want to peruse the NSView Class Reference, where you'll find some handy notifications, such as NSViewFrameDidChangeNotification and handy methods such as setPostsFrameChangedNotifications:.


Q:

Cmake compiling python into build folder

I think an example would be the best way to demonstrate my problem:
Lets say I have a source directory named src. This directory has two files, a CMakeLists.txt file and a python file named blah. In the same place where src is stored, there is a folder named build. Now, I would like to be able to run cmake and make it compile my python file blah and place it into my build directory. Currently, my CMakeLists.txt is just copying the uncompiled code straight into my build directory using the call:
CONFIGURE_FILE(${PATH_TO_SOURCE}/blah.py ${PATH_TO_BUILD}/blah.py COPYONLY)

Then I run make in the terminal to compile the actual file. This leaves the uncompiled python file in my build directory, which is no good. I've tried using ADD_EXECUTABLES, creating a custom target and using COMMAND, but my syntax must be off somewhere. Any help would be greatly appreciated!

A:

CMake doesn't support Python out of the box, AFAIK. Because of this, you will need to write rule to build python files, something like that:
macro(add_python_target tgt)
  foreach(file ${ARGN})
    set(OUT ${CMAKE_CURRENT_BINARY_DIR}/${file}.pyo)
    list(APPEND OUT_FILES ${OUT})
    add_custom_command(OUTPUT ${OUT}
        COMMAND <python command you use to byte-compile .py file>)
  endforeach()

  add_custom_target(${tgt} ALL DEPENDS ${OUT_FILES})
endmacro()

After defining it, you can use it this way:
add_python_target(blabla blah.py)

If you want to make adjustmenets or need more information, see CMake documentation.


Q:

For each word in the text file, extract surrounding 5 words

For each occurrence of a certain word, I need to display the context by showing about 5 words preceding and following the occurrence of the word.
Example output for the word 'stranger' in a text file of content when you enter occurs('stranger', 'movie.txt'):
My code so far:
def occurs(word, filename):

    infile = open(filename,'r')
    lines = infile.read().splitlines()
    infile.close()

    wordsString = ''.join(lines)
    words = wordsString.split()
    print(words)

    for i in range(len(words)):
        if words[i].find(word):
            #stuck here

A:

I'd suggest slicing words depending on i:
print(words[i-5:i+6])

(This would go where your comment is)
Alternatively, to print as shown in your example:
print("...", " ".join(words[i-5:i+6]), "...")

To account for the word being in the first 5:
if i > 5:
    print("...", " ".join(words[i-5:i+6]), "...")
else:
    print("...", " ".join(words[0:i+6]), "...")

Additionally, find is not doing what you think it is. If find() doesn't find the string, it returns -1 which evaluates to True when used in a if statement. Try:
if word in words[i].lower():


Q:

Does color spray affect undead?

The first-level illusionist spell color spray operates by overloading the senses/neural networks of its subject. Our view is that the same lack of conventional consciousness that makes the undead immune to sleep and charm also makes them immune to color spray. Would love to hear different interpretations, or assent.
This is a by-the-book First Edition AD&D game (PHB, DMG, no orange spines allowed).

A:

As an AD&D DM - I might rule differently. But, your dungeon master has house-ruled this result, so that's the call. I'd support him/her in this call and suggest out of game discussion amongst the group if dissent remains.
You didn't present your interpretation. Preparing an alternate explanation might help.
If you're ever a DM, I hope your players will support your decisions. For myself (and myself only) I usually say "yes" - I now tend to rule in favor of the PC that everything "works as described" in all cases, unless there is explicit disqualifying clause. But, I didn't always DM this way - there was a day when I would have ruled exactly as your DM did.
It was over time that I learned to be a better, more interactive DM that I learned to interpret the rules for fun over a logical/strict rules mindset. Most DMs go through this same learning cycle.

A:

First and foremost, consider the nature of the works you cite. When 1st edition Advanced D&D (aka 1e) was written, roleplaying was still new and error-correction and (extensive) rules extrapolations had not yet occurred. Worse yet, this rules set was written while Original D&D was being played by everyone, including the 1e author Gary Gygax. Several errors (see footnote) occurred during this overlap phase, and a general lack of specificity is common, most rules being left to the DM's logic and discretion.
Any question demanding a "by-the-book" (BtB) 1e ruling is thus subject to these errors and omissions, and the answer may be contradictory and/or illogical.

The first-level illusionist spell color spray operates by overloading the senses/neural networks of its subject.

Sorry Rich, but 'overloading the senses' is your deduction, and is not BtB. We can only say (BtB) that the 1st level spell (i.e. minimum power) causes unconsciousness, blindness, or stun, and that some victims get no saving throw.

Our view is that the same lack of conventional consciousness that makes the undead immune to sleep and charm also makes them immune to color spray.

While this is a logical sentiment it again is not supported by the Rules As Written. Nowhere do the rules refer to a 'lack of conventional consciousness'. Although it is a logical deduction, your BtB emphasis again precludes it.
It is true that most undead are immune to sleep and charm effects. But note that a Ghost is not explicitly given those immunities. This was probably a mere omission -- but again we have the BtB issue. (Deductions about immunities of undead as a class may also be faulty; many undead are also immune to hold and cold effects, but the Ghost is not, nor are ghouls or ghasts.)
THUS: given the descriptions in Monster Manual (1977) and lacking any explicit prohibition in the subsequent volumes, the Players Handbook (1978) and Dungeon Master's Guide (1979), the BtB ruling should be that Color Spray affects all undead mentioned in those works (Skeleton, Ghoul, Shadow, Wight, Ghast, Wraith, Mummy, Spectre, Vampire, Ghost, Lich).
In my own games I apply additional deductions and agree with your stance. But strictly BtB I must respectfully disagree with the other answers offered here.
Corollary: Don't insist on BtB answers for 1e. ;)

One of the most famous contradictions of the OD&D/AD&D crossover period represented in the 1e rulebooks is one At-Will ability of the Demon Yeenoghu, a "magic missile... having a +2 to hit" (MM1 p20, 1977) although the magic missiles (per spell) "unerringly strike their target" (PH p67, 1978).

A:

It's how we played when we played first edition. If I remember correctly, we had some limitations - higher level illusion spells were more effective on lower level undead, and more complete illusion spells had a higher chance of success, but, generally, when we ran into undead creatures, we stayed away from illusions.


Q:

Activating Site Features Question

When I Activate a Site Feature under Site Settings within SharePoint 13, does it only activate the Site Feature from my account or does it activate it for anyone else who is using SharePoint? I am not an administrator.
Thanks

A:

This would activate the feature for any account that can access the site - not only for you.
Example:
If you activate the "Community Site Feature" every user with access to the site can access the discussion board, categories etc (if they have contribute rights).
If you activate the Site Feed feature every user can post on that site's newsfeed (if they have contribute rights).
Things might be different for custom features/solutions depending on the solution.


Q:

How to access the property of a GridView - or ListView - element

Here is the code, I create 4 buttons. When one is clicked I wanna that its color changes to red and the color of all the others change to black.
But looks like I could not access the color property.
Rectangle {
    id: root
    width: 200; height: 100

    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement { my_color: "red" }
            ListElement { my_color: "black" }
            ListElement { my_color: "black" }
            ListElement { my_color: "black" }
        }

        groups: [
            DelegateModelGroup { name: "selected" }
        ]

        delegate: Rectangle {
            id: item
            height: 25
            width: 200
            color:my_color
            MouseArea {
                anchors.fill: parent
                onClicked: {
                   console.log(visualModel.items.get(index).color)
                   for (var i = 0; i < root.count; i++){
                       if(index == i)
                        visualModel.items.get(i).color = "red";
                       else
                        visualModel.items.get(i).color = "black";
                   }
                }
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
    }
}

A:

I advice you to use  ExclusiveGroup from QML controls. Usually it is used for Action but it's possible to use it for any other Item. From the Qt docs:

It is possible to add support for ExclusiveGroup for an object or
  control. It should have a checked property, and either a
  checkedChanged, toggled(), or toggled(bool) signal.

So all we need is to add suitable property. Small example:
import QtQuick 2.5
import QtQuick.Window 2.0
import QtQuick.Controls 1.4

Window {
    width: 200
    height: 400

    ExclusiveGroup { id: exclusiveGroup }
    ListView {
        anchors.fill: parent
        anchors.margins: 5
        spacing: 2
        model: 10
        delegate: Rectangle {
            id: myItem
            property bool checked: false // <-- this is necessary
            height: 30
            width: parent.width
            color: myItem.checked ? "lightblue" : "#DEDEDE"
            border { width: 1; color: "#999" }
            radius: 5
            Text { text: "item" + (index + 1); anchors.centerIn: parent}
            MouseArea {
                anchors.fill: parent
                cursorShape: Qt.PointingHandCursor
                onClicked: myItem.checked = !myItem.checked;
            }
            Component.onCompleted: {
                exclusiveGroup.bindCheckable(myItem);
            }
        }
    }
}


Q:

Буквы в окнах gtk отображаются квадратами

На моем компьютере установлен Linux. Занимаюсь программированием на Python именно в этой операционной системе. Естественно, приходится тестировать написанные приложения и в среде Windows. Было решено установить Wine и Python for Windows. Так вот, собственно, проблема: при использовании библиотеки gtk (Wine/Python) вылазят вот такие предупреждения... Сам шрифт в окнах интерфейса в квадратах, будь то кириллица либо же латиница.
Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 248
    self.show_all()
PangoWarning: couldn't load font "Sans Bold Not-Rotated 14", falling back to "Sans Bold Not-Rotated 14", expect ugly output.

Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 248
    self.show_all()
PangoWarning: All font fallbacks failed!!!!

Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 248
    self.show_all()
PangoWarning: failed to choose a font, expect ugly output. engine-type='PangoRenderWin32', script='latin'

Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 248
    self.show_all()
PangoWarning: couldn't load font "Sans Not-Rotated 12", falling back to "Sans Not-Rotated 12", expect ugly output.

Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 373
gtk.main()
PangoWarning: couldn't load font "Sans Bold Not-Rotated 10", falling back to "Sans Bold Not-Rotated 10", expect ugly output.

Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 373
    gtk.main()
PangoWarning: All font fallbacks failed!!!!

Warning (from warnings module):
  File "Z:\home\zavulon\Programming\Opt\Package_for_Windows\gtkPopupNotify-master\gtkPopupNotify.py", line 373
    gtk.main()
PangoWarning: failed to choose a font, expect ugly output. engine-type='PangoRenderWin32', script='common'

A:

Дык этих же шрифтов у тебя нет, что теме gtk для винды прописаны.
Поставить их в wine нужно.


Q:

Probability of choosing value of variable in equation - 4 tuple ($x_1 +x_2+x_3+x_4=10$)

It may be the wording in this problem that is throwing me off but I can't seem to figure out the number of possible successful outcomes to calculate the probabiliy:
Suppose a non-negative integer solution to the equation $w+x+y+z=10$ is chosen at random (each one being equally likely to be chosen). What is the probability that in this particular solution that $w$ is less than or equal to 2?
Let $A = w \leq 2 $
To find P(A) I need:
\begin{align}
P(A)=\frac{|E|}{|S|}
\end{align}
Where |E| = Successful outcomes and |S| = Size of sample space.
I start by finding the sample space of possible solutions, since this is a 4 tuple: ${\{w,x,y,z\}}$ --  order does not matter and repeats are allowed,  I would say the size of sample space is
\begin{align}
|S| = C(10+4-1,4) =C(13,4)
\end{align}
So this gives me:
\begin{align}
P(A)=\frac{|E|}{C(13,4)}
\end{align}
However, I can't seem to figure out $|E|$ as I don't know how to account for all cases...
I am guessing since there are 4 variables: $\{w,x,y,z\}$ and we assume $w$ is aleady chosen from the following: $\{0,1,2\}$ (since $w\leq 2$) this leaves us with 3 variables left to determine. The number of outcomes for this would look like:
$$
\begin{array}{c|lcr}
case & \text{Number of outcomes} \\
\hline
0+x+y+z= 10  & C(10+3-1,3) = C(12,3) \\
1+x+y+z= 10  & C(10+3-1,3) = C(12,3)\\
2+x+y+z= 10  & C(10+3-1,3) = C(12,3)
\end{array}
$$
This feels wrong.. or maybe I am overthinking it. But would the solution be:
\begin{align}
P(A)=\frac{3 \cdot C(12,3)}{C(13,4)}
\end{align}

A:

Put w = 0
Find solution for $x+y+z = 10$ and that is ${12\choose2}=66$
Put w = 1
Find solution for $x+y+z = 9$  and that is ${11\choose2}=55$
Put w = 2
Find solution for $x+y+z = 8$  and that is ${10\choose2}=45$
Add the above cases to a total of $166$
For all non negative w,x,y,z
Find the solution for $w+x+y+z = 10$ and that is ${13\choose3}
=286$
Thus the probability $=\frac{166}{286}$


Q:

Wrap a span around pagination text using jquery

I have this HTML structure I can't edit, because of our CMS and as you can see it's missing a class/span making it difficult to style the active page, which is the '5'. Meanwhile, the end chevron is removed when the last pagination is active, which is the '7'.
Can someone provide a jquery solution to wrap  around the '5' when its active and when the last pagination is active, which is the '7', so I may style it?

The active page will increase/decrease depending on the number selected, so it's not always going to be '5' and a '7' that requires the span.
The jquery shouldn't touch summary "xx records / xx records per page / x pages" that exists within the same div block.
When the last pagination is clicked, which is the 7, the chevron is removed and the active number is next to the summary. This isolated pagination would need the span tag without affecting the summary.

This is my fiddle to provide a demo: http://jsfiddle.net/evanmoore/yay9W/
Example 1:

    ‹‹
    1
    2
    3
    4
    5
    6
    7
    ››
    xx records / xx records per page / x pages

Example 2: Then should the last pagination be active, in this case its the 7, the html looks like this:

    ‹‹
    1
    2
    3
    4
    5
    6
    7 xx records / xx records per page / x pages

This is my fiddle to provide a demo: http://jsfiddle.net/evanmoore/bqyYA/

A:

Assuming that we want to wrap any content that is a text node except for the last one (which holds your summary), this should work:
$('div.pag').contents(':not(:last-child)').filter(function() {
  return this.nodeType == 3;
})
.wrap('')

The .contents function is similar to the .children function, except that it also returns text nodes.  The filter checks for a text node type.  An added filter skips the final child node.
Here's the demo:
http://jsfiddle.net/36Wwt/