text:
Q: How to get Kubernetes Ingress Port 80 working on baremetal single node cluster I have a bare-metal kubernetes (v1.11.0) cluster created with kubeadm and working fine without any issues. Network with calico and made it a single node cluster using kubectl taint nodes command. (single node is a requirement).
I need to run mydockerhub/sampleweb static website image on host port 80. Assume the IP address of the ubuntu server running this kubernetes is 192.168.8.10.
How to make my static website available on 192.168.8.10:80 or a hostname mapped to it on local DNS server? (Example: frontend.sampleweb.local:80). Later I need to run other services on different port mapped to another subdomain. (Example: backend.sampleweb.local:80 which routes to a service run on port 8080).
I need to know:

*

*Can I achieve this without a load balancer?

*What resources needed to create? (ingress, deployment, etc)

*What additional configurations needed on the cluster? (network policy, etc)
Much appreciated if sample yaml files are provided.
I'm new to kubernetes world. I got sample kubernetes deployments (like sock-shop) working end-to-end without any issues. I tried NodePort to access the service but instead of running it on a different port I need to run it exact port 80 on the host. I tried many ingress solutions but didn't work.
Screenshot of my setup:

A: In addition to the andswer of Nicola Ben , You have to define an externalIPs in your traefik service, just follow the steps of Nicola Ben and add a externalIPs section to the service "my-svc-1" .
apiVersion: v1
kind: Service
metadata:
  namespace: traefik
  name: my-svc-1
spec:
  selector:
    k8s-app: traefik-ingress-lb
  ports:
  - port: 80
    targetPort: 8080
  externalIPs:
  - <IP_OF_A_NODE>

And you can define more than on externalIP.

A: I recently used traefik.io to configure a project with similar requirements to yours.
So I'll show a basic solution with traefik and ingresses.
I dedicated a whole namespace (you can use kube-system), called traefik, and created a kubernetes serviceAccount:
apiVersion: v1
kind: Namespace
metadata:
  name: traefik
---
apiVersion: v1
kind: ServiceAccount
metadata:
  namespace: traefik
  name: traefik-ingress-controller

The traefik controller which is invoked by ingress rules requires a ClusterRole and its binding:
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: traefik-ingress-controller
rules:
  - apiGroups:
      - ""
    resources:
      - services
      - endpoints
      - secrets
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - extensions
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: traefik-ingress-controller
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: traefik-ingress-controller
subjects:
- kind: ServiceAccount
  namespace: traefik
  name: traefik-ingress-controller

The traefin controller will be deployed as daemonset (i.e. by definition one for each node in your cluster) and a Kubernetes service is dedicated to the controller:
kind: DaemonSet
apiVersion: extensions/v1beta1
metadata:
  name: traefik-ingress-controller
  namespace: traefik
  labels:
    k8s-app: traefik-ingress-lb
spec:
  template:
    metadata:
      labels:
        k8s-app: traefik-ingress-lb
        name: traefik-ingress-lb
    spec:
      serviceAccountName: traefik-ingress-controller
      terminationGracePeriodSeconds: 60
      containers:
      - name: traefik-ingress-lb
        image: traefik
        ports:
        - name: http
          containerPort: 80
          hostPort: 80
        - name: admin
          containerPort: 8080
        securityContext:
          capabilities:
            drop:
            - ALL
            add:
            - NET_BIND_SERVICE
        args:
        - --api
        - --kubernetes
        - --logLevel=INFO
---
kind: Service
apiVersion: v1
metadata:
  namespace: traefik
  name: traefik-ingress-service
spec:
  selector:
    k8s-app: traefik-ingress-lb
  ports:
    - protocol: TCP
      port: 80
      name: web
    - protocol: TCP
      port: 8080
      name: admin

The final part requires you to create a service for each microservice in you project, here an example:
apiVersion: v1
kind: Service
metadata:
  namespace: traefik
  name: my-svc-1
spec:
  selector:
    k8s-app: traefik-ingress-lb
  ports:
  - port: 80
    targetPort: 8080

and also the ingress (set of rules) that will forward the request to the proper service:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  namespace: traefik
  name: ingress-ms-1
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  rules:
  - host: my-address-url
    http:
      paths:
      - backend:
          serviceName: my-svc-1
          servicePort: 80

In this ingress I wrote a host URL, this will be the entry point in your cluster, so you need to resolve the name to your master K8S node. If you have more nodes which could be master, then a loadbalancer is suggested (in this case the host URL will be the LB).
Take a look to kubernetes.io documentation to have clear the concepts for kubernetes. Also traefik.io is useful.
I hope this helps you.


text:
Q: Custom data pass to pinterest in php I need pass custom data (image,name,price) to pinterest account.
How to do this one i have pinterest account and APP_ID & APP_SECRET so please help any one.
This is my HTML code :index.php
<?php require "boot.php"; ?>

<!DOCTYPE html>

Login with Pinterest

Use this <a href="<?php echo $pinterest->auth->getLoginUrl('https://localhost/pinterest/demo/callback.php', array('read_public', 'write_public')); ?>">link to login with your Pinterest account.

This my php code:callback.php
<?php require "boot.php"; ?>

<!DOCTYPE html>

        <?php
            $board = $pinterest->boards->create(array(
                "name"          => "Test from the pinterest",
                "description"   => "Test pinterest"
            ));
          $pinterest->pins->create(array(
                "board"         => "dirkgroenen/test-from-api",
                //"image_url"     => "https://images.unsplash.com/photo-1453974336165-b5c58464f1ed?crop=entropy&fit=crop&fm=jpg&h=1000&ixjsv=2.1.0&ixlib=rb-0.3.5&q=80&w=1925",
                //"image"         => "./test_image_from_unsplash.jpg",
                "image"         => "http://localhost/Pinterest/demo/testimage.jpg",
                "note"          => "test",
                //"link"          => "http://tld.com/072AE601DF7DB00445386F5C9CC46F74"
            ));

        ?>

This is my boot.php file:
<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    require "../autoload.php";
    //$dotenv = new Dotenv\Dotenv(__DIR__);
    //$dotenv->load();
     //$pinterest = new DirkGroenen\Pinterest\Pinterest(getenv("APP_ID"), getenv("APP_SECRET"));
     $pinterest = new DirkGroenen\Pinterest\Pinterest(getenv("4947671503463268619"), getenv("ce54e73e9f1f366748f3e616b48574c90f8557458bc1ed126bce70c9a6ae70cb"));

    print_r($pinterest);

    if (isset($_GET["code"])) {

       echo "comming";die;

        $token = $pinterest->auth->getOAuthToken($_GET["code"]);

        $pinterest->auth->setOAuthToken($token->access_token);

        setcookie("access_token", $token->access_token);

    } else if (isset($_GET["access_token"])) {

        $pinterest->auth->setOAuthToken($_GET["access_token"]);

    } else if (isset($_COOKIE["access_token"])) {

        $pinterest->auth->setOAuthToken($_COOKIE["access_token"]);

    } else {
        assert(false);
    }
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: asp.net mvc scaffolding and GUID as the primary key I have a table with the following structure
GUID uniqueidentifier with default value newid(), and set as primary key
ID int
Description varchar(max)

I created an Entity Model using visual studio, and generated the views for editing/deleting etc (mvc scaffolding)
The problem is with "Editing", when I click that link, the appropriate form is showed with the correct data, but the "save" button doesn't work at all. Please note that other links (delete,create,details) work perfectly..
So, when I click the "Edit" link, the url is
http://localhost:10871/admin/Edit/e7d0c5ee-7782-411f-920e-7b0d93c924e1
and the form is displayed correctly, but the save button doesn't work, no network activity happens. Is something particular about using uniqueidentifers as primary key?
Thanks
---Code---
Edit.cshtml
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Domain</legend>

        @Html.HiddenFor(model => model.GUID)

        @Html.HiddenFor(model => model.ID)

            @Html.LabelFor(model => model.Description)

            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)

            <input type="submit" value="Save" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

--AdminController.cs--
// GET: /Admin/Edit/5
public ActionResult Edit(Guid id)
{
    Domain domain = db.Domains.Single(d => d.GUID == id);
    return View(domain);
}

//
// POST: /Admin/Edit/5

[HttpPost]
public ActionResult Edit(Domain domain)
{
    if (ModelState.IsValid)
    {
        db.Domains.Attach(domain);
        db.ObjectStateManager.ChangeObjectState(domain, EntityState.Modified);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(domain);
}

Edit2
In response to a comment by  ZippyV, I added the following code in Edit.cshtml

            @Html.LabelFor(model => model.ID)

            @Html.EditorFor(model => model.ID)
            @Html.ValidationMessageFor(model => model.ID)

to  my surprise (or ignorance) - the GUID is being shown instead of ID

and apart from that - when I enter a value in that field (1,2 or any integer), I still get the message "The field ID must be a number."

A: The problem comes from the fact that you have a property called ID on your view model:
public class Domain
{
    public int ID { get; set; }
    ...
}

and at the same time you have a route parameter called id in your Edit controller action:
public ActionResult Edit(Guid id)
{
    ...
}

Now here's what happens: The Html helpers (such as TextBoxFor, HiddenFor, ...) always first looks in the model state when binding a value (i.e. query string parameters, route values) and only at the end it looks at the value in the model. That's how all Html helpers work and it is by design.
So you have the following:
@Html.HiddenFor(model => model.ID)

The ID is taken NOT from the model but from your Route data (which is a Guid as specified in your action parameter). That's why it is very dangerous to use properties in the view model and action parameters that have the same name.
One possible workaround would be to rename your action parameter to something else:
public ActionResult Edit(Guid domainId)
{
    Domain domain = db.Domains.Single(d => d.GUID == domainId);
    return View(domain);
}

Of course now your routes might need to be adapted or use query string parameters: controller/edit?domainId=d578b4b7-48ec-4846-8a49-2120c17b6441 to invoke the Edit action.


text:
Q: c# visifire(charts) I have developed one silverlight application on .net framework and used visifire for charting i.e. getting updated through MS SQL database.
The main thing is that when i am updating the database the data on chart are getting affected, but the look and feel of the chart is not happening smoothly during the value change.
I have used <vc:DataSeries RenderAs="QuickLine"  DataSource="{Binding ItemsSource, ElementName=MyGrid}" > for quickline presentation of the data on graph.
So what changes I have to make in my programm for smooth change in graph statistics after database updation.

A:
"but the look and feel of the chart is
  not happening smoothly during the
  value change"

What is your expected output and what is the current output? Please explain more in detail. Which version of Visifire you are using? Exactly how you are updating the ItemsSource property? Can you provide C# code and XAML?


text:
Q: Apps script - function () { [native code] } I am making a google apps script and i am trying to make a program that would read the first callendar event. The problem is, when I try to get anything from it it just writes:

function () { [native code] }.

I have seen some questions written for javascript, but i dont understand, how to add jquery to apps script and i am not sure if it would fix anything.
var now = new Date();
var today = new Date(now.getTime());
var events = CalendarApp.getDefaultCalendar().getEventsForDay(today);
Logger.log(events);
var event1 = events[0];
Logger.log(event1);
var startTime = event1.getStartTime;
Logger.log(startTime);
var id = event1.getId
Logger.log(id)
var title = event1.getTitle
Logger.log(title)
}

A: Explanation:

*

*The reason you are getting function () { [native code] } is because you are not executing the function. Namely, getStartTime, getId, getTitle are not properties but methods (functions). Therefore you need to add () at the end e.g. event1.getStartTime().

*You can simply use var today = new Date() when specifying the date.
Solution:
function myFunction() {
  var today = new Date();
  var events = CalendarApp.getDefaultCalendar().getEventsForDay(today);
  var event1 = events[0];
  var startTime = event1.getStartTime(); //modified ()
  Logger.log(startTime);
  var id = event1.getId(); //modified ()
  Logger.log(id);
  var title = event1.getTitle(); //modified ()
  Logger.log(title);
}


text:
Q: How to know which NSTableView opened a Contextual Menu? I have 5 NSTableView's instances that have the same contextual menu. When I get the message that the menu has been clicked I need to know which table sent it. I've checked the NSMenu documentation but I don't seem to find a way to check which of the tables opened the menu..
I'm thinking of subclassing NSTableView and send a message to the delegate on menuForEvent, would that be the best way?
UPDATE:
Thanks Joshua, I,am using 5 tables to display a 5 day week task planning. Each table represents a week day, and I added the contextual menu for adding and removing tasks. So when a user clicks "add task" on a week day I need to know which one. I've got it working by subclassing tableview and sending a message to the delegate when the menu is opened. In this manner my controller knows which of the tables was the last to call the menu.
But it doesn't seem to me like the best implementation to get this, maybe is like you said the problem lies on the UI, what do you think?
Jose.

A: I don't see a way to get this information. Menus aren't "attached" to anything; they're displayed in a location. Your -menuForEvent: override might work but it gives me the willies.
While this isn't an answer to your question, I confess my first reaction is "why do you have multiple tables with exactly the same menu?" This strikes me more as a UI issue. One would think a contextual menu would be pretty specific to the specific kind of thing (or view thereof) that it represents. That begs the question: why do you have 5 table views that all have exactly the same context? If all 5 tables represent things that are controlled in the same way by the (presumably) same controller, it's highly likely there's a better way to represent your "collection of things" than 5 separate tables.
I'm making a lot of assumptions, granted, but my curiosity is getting the best of me, I suppose. :-)


text:
Q: Gaps between the primes I had this question at the start of my number theory class so I think it is supposed to be an easy one but I did not receive a solution. Here is the problem:
Let $n\in \mathbb{N}$ be arbitary. Prove that there exists a number $k\in\mathbb{N}$,
such that $k + 1, k + 2, k+3, . . ., k+n\;$ are not primes.
I read somewhere that the gaps between the consecutive primes do not tend towards infinity so is this not a wrong statement? This is what confused me. Can someone shed some light on this?

A: Let $g_n$ be the sequence of gaps between consecutive primes. The problem posed is to show that $\limsup_{n\to\infty}g_n=\infty$. The Twin Prime conjecture, on the other hand, says that $\liminf_{n\to\infty}g_n=2$. The 2013 breakthrough theorem of Yitang Zhang says that $\liminf_{n\to\infty}g_n\le70{,}000{,}000$ (and follow-up work by others has reduced the upper bound to $246$). Conjecturally, $g_n$ takes every even value infinitely often, but Zhang's theorem alone is enough to show that $g_n$ does not tend to infinity, even though its limsup does.
Added later: Just to be clear, I am answering what I take to be the OP's main question, which is why the assigned problem does not conflict with their having read that the sequence of gaps does not tend to infinity. As the OP surmised, the assigned problem is a relatively easy one (and as such would be a duplicate).


text:
Q: using variables in search pattern in awk script #!/usr/local/bin/gawk -f  `

{
awkvar2="/id=22/";
awkvar3="/end/";

if ($0 ~ awkvar2) {
    triggered=1;
  }
  if (triggered) {
     print;
     if ($0 ~ awkvar3) {
        triggered=0;
        print "\n-----------------------------------------------\n"
     }
  }
}

this awk script is not working for me
i am trying to search from one line to another i.e id=22 till end
(the reason i am not using /<string>/,/<string>/ is because i want a big line after each block of search)
and i want this using variables only.
i could directly use the patterns if ($0 ~ /end/) {
but i dont want to do that, i want to use the variables inside the search pattern
(reason is i will be getting the values in the variables dynamically thorough the shell)
please advise me how to use variables inside the search pattern for awk
thanks...

A: {
awkvar2="id=22";
awkvar3="end";
if ($0 ~ awkvar2) {
        triggered=1;
         }
if (triggered) {
         print;
         if ($0 ~ awkvar3) {
              triggered=0;
              print "\n-----------------------------------------------\n"
         }
}
}

 Edit
Modified per request to print the line before "id=22"
{
  awkvar2="id=22";
  awkvar3="end";
  if ($0 ~ awkvar2) {
          print prev;
          triggered=1;
  }
  if (triggered) {
          print;
          if ($0 ~ awkvar3) {
              triggered=0;
              print "\n-----------------------------------------------\n"
          }
  }
  {prev=$0;}
}

Or, more awkish
BEGIN {awkvar2="id=22";awkvar3="end"}

($0 ~ awkvar2),($0 ~ awkvar3) { if ($0 ~ awkvar2) {print prev;}
                                print;
                                if ($0 ~ awkvar3) {
                                    print "\n---------------\n"
                                }
                               }
{prev=$0;}

A: More compact version of belisarius awk script, without 'if's
BEGIN {awkvar2="id=22";awkvar3="end"}

($0 ~ awkvar2) {print prev;}
($0 ~ awkvar2),($0 ~ awkvar3) {print; }
($0 ~ awkvar3) {print "\n---------------\n"}
               {prev=$0;}


text:
Q: HTTP interface for VLC. Combining Loop & Repeat functions I have a cd player I'm writing in Java, porting VLC with the http interface.  I'm trying to combine the loop and repeat functions in order to have a Repeat button with 3 states (Repeat none, Repeat One, and Repeat All).  For some odd reason, the "loop" boolean is switching back and forth every second, so there is no way to reliably "Repeat All".  I just have to hope the loop boolean is in the right state at the right time.  But as it is changing every second, this seems almost impossible to use.  Has anybody seen this?  Or know any solutions?
OK I FOUND IT.  Apparently you must explicitly put --loop or --no-loop in the parameters when you start up VLC via command line.  If you don't do that, it just keeps flip flopping back and forth, and you will really only have a 50% chance of getting what you want to happen.  If you choose one or the other at startup, you can at least change them whenever you want, without worrying about them reverting.


text:
Q: How weakly open imply open? When I am seeing the proof of the statement "Let $C$ be a convex set in a normed linear space $X$.
Then $C$ is closed if and only if $C$ is weakly closed."
Proof: Suppose that $C$ is weakly closed. Then $C^c$, the complement of
$C$ is weakly open and hence open. Hence $C$ is closed.
my problem is in the 2nd line of the proof written in bold line. How weakly open imply open?
Thanks.

A: Every open set in the weak topology is open in the norm. This follows from definition of weak topology.
Weak topology is the smallest topology that makes every element of the dual space continuous. Since every element of the dual space is continuous for the norm topology it follows that every weakly open set is open in the norm topology.


text:
Q: How to reuse a pattern rule for the same target in (GNU) make? I am automating a pipeline in make that consists of multiple operations that can be chained together.
Which operation was applied is indicated in the filename.
Sometimes I have to re-run the same operation within the same command chain to get a certain target, e.g. make input.filtered.sorted.updated.sorted should result in the following output files: input.filtered, input.filtered.sorted, input.filtered.sorted.updated and input.filtered.sorted.updated.sorted.
However, this seems not possible in one go.
Consider the following dummy implementation:
# just some dummy commands
save=and writing the result to $@
filter=@echo filtering $< accoring to some critera $(save)
sort=@echo sorting $< according to some criteria $(save)
update=@echo updating some values of $< according to $(word 2,$^) $(save)

# assume these input files exist
.PHONY : input update_table

# keep all intermediate files
.SECONDARY :

# this is what I would like to build
desired_target : input.filtered.sorted.updated.sorted

# this is what I can build
possible_target : input.filtered.sorted.updated

# just some dummy rules
%.filtered : % ; $(filter)
%.sorted : % ; $(sort)
%.updated : % update_table ; $(update)

Running make (i.e make desired_target) result in the following error:
make: \*** No rule to make target `input.filtered.sorted.updated.sorted', needed by `desired_target'.  Stop.

However, make possible_target works fine:
filtering input accoring to some critera and writing the result to input.filtered
sorting input.filtered according to some criteria and writing the result to input.filtered.sorted
updating some values of input.filtered.sorted according to update_table and writing the result to input.filtered.sorted.updated

Interestingly, running touch input.filtered.sorted.updated && make works as expected:
filtering input accoring to some critera and writing the result to input.filtered
sorting input.filtered according to some criteria and writing the result to input.filtered.sorted
updating some values of input.filtered.sorted according to update_table and writing the result to input.filtered.sorted.updated
sorting input.filtered.sorted.updated according to some criteria and writing the result to input.filtered.sorted.sorted.updated.sorted

How can I get make to run without the need of touching intermediate targets beforehand?
Addendum:
In case this was not clear from the previous examples, make possible_target && make [desired_target] works fine. So I want to get rid of the first call using makes dependecy tree.

A: From the make manual - 10.4 Chains of Implicit Rules

No single implicit rule can appear more than once in a chain. This
  means that make will not even consider such a ridiculous thing as
  making foo from foo.o.o by running the linker twice. This constraint
  has the added benefit of preventing any infinite loop in the search
  for an implicit rule chain.

So, for me, the only way to do this is to create an intermediate rule like possible_target and to add it as a dependency of the desired_target.
desired_target : possible_target

A: I wrote a patch against 3.82 which adds a -M option that allows using the same rule multiple times.
I use this for a particular Makefile that contains over 100 of the sort of rules you have here.
Let me know if you use it or if you want it adapted.


text:
Q: Sorting Kentico Repeater Items into Alphabet "Categories" Is there a way I can put the items that come out of a Repeater into a JavaScript array so that I can sort them into an alphabetical category?
Is there a ways to do this with a transformation?

A: Yes, use ApplyTrnasformation method with the code name of the transformation you use in your repeater and apply it on the collection of pages within a macro in your javascript.
Example:
<script>
var o = '{%Documents.Where("NodeParentID=123").ApplyTransformation("cms.menuitem.javascript")%}';
</script>

A: You might be able to do this using JQuery after the repeater has loaded its content. For example, if your repeater renders a list (un-ordered UL/LI for example) then you can iterate that list using a JQuery function and push the items into the array.
Here's an article which might help you along:
Jquery push all li's ID's into array


text:
Q: Serializing the complete Javascript state of a website including Closure/Hidden scopies? I would like to save a "snapshot" of a webpage which however should remain in an "interactive" state -> all Javascript state has to be saved and restored.
Example showing the issue I'm trying to solve: Given a webpage which executes the following script in the global scope:
function f(x) { return function() { return x; } }
var g = f(2);

I'd like to save both the function f (more or less trivial) and the variable g (which closes over x from the f invocation) to a file and restore the state of the website later.
As far as I could figure out it seems to be impossible to do this using only "web" technologies (ie. with the permissions the webpage itself has). I'm therefore guessing I'll have to implement a browser addon to achieve this.
Does something like this already exist? What would be a good starting point? I noticed that Firefox Session Restore does something similar, do you know if I could reuse this mechanism? If not would it be feasible to implement something like this as a "debugger" style addon? Are there simpler solutions?

A: Javascript objects hold onto DOM/other native objects. Native objects have hidden state and can be entangled with global browser state or addons.
So the only real way I can think of is to run a browser in a VM and snapshot/clone that VM.


text:
Q: Twitter API: Detecting, managing, and ending sessions At the moment, I am looking to offer a page to users to manage multiple social network accounts.  These can include multiples of each service type.  I am having a difficult time understanding how to detect if a user is logged into twitter(in order to prompt them to log in), manage multiple twitter accounts for a single user (say a business has multiple branches), and the like.
Now, I can already get the token credentials, so I can connect to the API.  I guess my real question is:
Is there a documented process for managing twitter accounts through the API?
Facebook has a pretty easy process that checks for an existing user on pageload.

A: What you mean by managing? You can update the authenticating user's settings by POST account/settings, update the authenticating user's profile image by POST account/update_profile_image and a plenty of other actions which you can find here in the Users section.


text:
Q: Contar numero de registros em uma tabela MySql com PHP? Gente, eu tenho um banco de dados com uma tabela chamada "usuarios", e eu gostaria de saber como eu faço para, através de PHP, contar quantos registros existem nessa tabela, e logo dar um 'echo' para mostrar essa quantidade na página. Por favor me ajudem!!

A: Só fazer dessa forma aqui.
$sql = "SELECT * FROM usuarios";
$resultado = count($sql);
echo $resultado;

A: $query = mysql_query("SELECT count(*) as total from tabela");
$resultado = mysql_fetch_assoc($query);
echo $resultado['total'];

A: Quando você faz uma consulta no banco, você pode passar o Count:
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";

A: O PHP possui uma função só pra contar as linhas sem usar o Count(*) que é o mysqli_num_rows(). Com isso você consegue reaproveitar o resultado da query.
$QUERY = "SELECT * AS Quantidade FROM BancoA.tabelaA";
$executa_query = mysqli_query($conexao, $QUERY);
$conta_linhas = mysqli_num_rows($executa_query);
echo $conta_linhas;


text:
Q: How to firebase AB test new user onboarding? As some other questions pointed out if you're setting up a Remote Config based AB test there's no activation event based on user first opened.
We want to AB test our new onboarding flow against the previous onboarding experience however without a startup trigger we're not sure how to properly create this experiment.
One SO answer talks about sending a custom activation event with a timestamp and then filtering the test participants by that timestamp e.g. custom_first_open > 1234567... however the onboarding flow is the first thing the user is to see.
From my understanding as soon as the user initializes their remote config they will be subscribed to any active experiments. We would have to send the custom event before initialization and it would have to be immediately available to the AB test. AB test data and Firebase events both seem to be very slow to register (hours to days) so I doubt it would properly configure the user for the onboarding test using this trick.
Is there another way to use AB testing to test onboarding efficacy only against new users?

A: There are a couple of ways to go about this.
First, when you create the experiment you can limit the experiment targeting to only include users on a new version or build of the app -- or country, etc.
example targeting
You can also only target users in an Audience you define, which give you pretty flexible abilities to define whatever group you'd like to roll the tests out to.
creating an audience
Note - we tend to recommend you use first_touch_timestamp for correctly identifying new users. Better than first_open.
Also, outcomes are easier to measure when you're looking at ARPU/LTV outcomes


text:
Q: NameValueCollection.Get() alternative for DataRow I can safely get a value from a NameValueCollection using NameValueCollection.Get(), if the key doesn't not exist then a null is returned.
However many times I want to try to load a DataColumn value, unfortunately dr["BadColumn"]
will throw an exception.
Is there a simpler way than having to create a checking method?

A: Go with the suggestion of @Tim Schmelter . You might perform that check in an extension method for DataRow if you would like and also give that an alternative default for scenarios where you would like some other value rather than null.
public static Object GetOrDefault(this DataRow dr, String columnName, String defaultValue = null)
{
    if (dr.Table.Columns.Contains(columnName)) return dr[columnName];
    return defaultValue;
}


text:
Q: Find differences betwen 2 dataframes with different lengths I have two dataframes with each two columns c("price", "size") with different lengths.
Each price must be linked to its size. It's two lists of trade orders. I have to discover the differences between the two dataframes knowing that the two databases can have orders that the other doesn't have and vice versa. I would like an output with the differences or two outputs, it doesn't matter.  But I need the row number in the output to find where are the differences in the series.
Here is sample data :
> out
           price       size
     1: 36024.86 0.01431022
     2: 36272.00 0.00138692
     3: 36272.00 0.00277305
     4: 36292.57 0.05420000
     5: 36292.07 0.00403948
    ---
923598: 35053.89 0.30904890
923599: 35072.76 0.00232000
923600: 35065.60 0.00273000
923601: 35049.36 0.01760000
923602: 35037.23 0.00100000

>bit
      price       size
     1: 37279.89 0.01340020
     2: 37250.84 0.00930000
     3: 37250.32 0.44284049
     4: 37240.00 0.00056491
     5: 37215.03 0.99891906
    ---
923806: 35053.89 0.30904890
923807: 35072.76 0.00232000
923808: 35065.60 0.00273000
923809: 35049.36 0.01760000
923810: 35037.23 0.00100000

For example, I need to know if the first row of the database out is in the database bit.
I've tried many functions : comparedf()
summary(comparedf(bit, out, by = c("price","size"))

but I've got error:

Error in vecseq(f__, len__, if (allow.cartesian || notjoin ||
!anyDuplicated(f__, :

I've tried compare_df() :
compareout=compare_df(out,bit,c("price","size"))

But I know the results are wrong, I've only 23 results and I know that there are more than 200 differences minimum.
I've tried match(), which() functions but it doesn't get the results I search.
If you have any other methods, I will take them.

A: Perhaps you could just do inner_join on out and bit by price and size? But first make id variable for both data.frame's
library(dplyr)

out$id <- 1:nrow(out)
bit$id <- 1:nrow(bit)

joined <- inner_join(bit, out, by = c("price", "size"))

Now we can check which id from out and bit are not present in joined table:
id_from_bit_not_included_in_out <- bit$id[!bit$id %in% joined$id.x]
id_from_out_not_included_in_bit <- out$id[!out$id %in% joined$id.y]

And these ids are the rows not included in out or bit, i.e. variable id_from_bit_not_included_in_out contains rows present in bit, but not in out and variable id_from_out_not_included_in_bit contains rows present in out, but not in bit

A: First attempt here. It will be difficult to do a very clean job with this data tho.
The data I used:
out <- read.table(text = "price       size
                  36024.86 0.01431022
                  36272.00 0.00138692
                  36272.00 0.00277305
                  36292.57 0.05420000
                  36292.07 0.00403948

                  35053.89 0.30904890
                  35072.76 0.00232000
                  35065.60 0.00273000
                  35049.36 0.01760000
                  35037.23 0.00100000", header = T)

bit <- read.table(text = "price       size
                  37279.89 0.01340020
                  37250.84 0.00930000
                  37250.32 0.44284049
                  37240.00 0.00056491
                  37215.03 0.99891906
                  37240.00 0.00056491
                  37215.03 0.99891906
                  35053.89 0.30904890
                  35072.76 0.00232000
                  35065.60 0.00273000
                  35049.36 0.01760000
                  35037.23 0.00100000", header = T)

Assuming purely that row 1 of out should match with row 1 of bit a simple solution could be:
df <- cbind(distinct(out), distinct(bit))
names(df) <- make.unique(names(df))

However judging from the data you have provided I am not sure if this is the way to go (big differences in the first few rows) so maybe try sorting the data first?:
df <- cbind(distinct(out[order(out$price, out$size),]), distinct(bit[order(bit$price, bit$size),]))
names(df) <- make.unique(names(df))


text:
Q: C++ Sockets - Server doesn't accept multiple clients (linux) I have working server and client code. The server and client can connect and chat with each other correctly. But when I open another client terminal, the client is says Awaiting confirmation from the server and nothing else. Although server and client #1 can still chat.
I searched on multi-threading but the examples or code snippets they show is advanced. Maybe a little explanation or an example will help a lot!
The code below is working. I have a working server but it only accepts one connection. How do I make the server to allow multiple connection? So that I can make the program look like a group chat.
client.cpp (when client #2 connects, the code freezes at line 40)
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

int main()
{
    char a;
    int client;
    int portNum = 1500;
    int bufsize = 1024;
    char* buffer = new char[bufsize];
    bool isExit = false;
    char* ip = "127.0.0.1";

    struct sockaddr_in direc;

    if ((client = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        cout << "\nError creating socket..." << endl;
        exit(0);
    }

    cout << "\nSocket created successfully..." << endl;
    direc.sin_family = AF_INET;
    direc.sin_port = htons(portNum);
    inet_pton(AF_INET, ip, &direc.sin_addr);

    if (connect(client,(struct sockaddr *)&direc, sizeof(direc)) == 0)
        cout << "Connection to the server " << inet_ntoa(direc.sin_addr) << endl;

    cout << "Awaiting confirmation from the server..." << endl; //line 40
    recv(client, buffer, bufsize, 0);

    cout << "\n=> Enter # to terminate the connection\n" << endl;

    do {
        cout << "Client: ";
        do {
            cin >> buffer;
            send(client, buffer, bufsize, 0);
            if (*buffer == '#') {
                send(client, buffer, bufsize, 0);
                *buffer = '*';
                isExit = true;
            }
        } while (*buffer != 42);

        cout << "Server: ";
        do {
            recv(client, buffer, bufsize, 0);
            cout << buffer << " ";
            if (*buffer == '#') {
                *buffer = '*';
                isExit = true;
            }

        } while (*buffer != 42);
        cout << endl;

    } while (!isExit);
    cout << "=> Connection terminated.\nGoodbye";

    close(client);
    return 0;
}

server.cpp
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

int main()
{
    int client, server;
    int bufsize = 1024;
    int portNum = 1500;
    bool isExit = false;
    char* buffer = new char[bufsize];

    struct sockaddr_in direc;
    socklen_t tamano;
    pid_t pid;

    if ((client = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        cout << "\nError establishing socket..." << endl;
        exit(1);
    }

    cout << "\nSocket server has been created..." << endl;

    direc.sin_family = AF_INET;
    direc.sin_addr.s_addr = htons(INADDR_ANY);
    direc.sin_port = htons(portNum);

    if ((bind(client, (struct sockaddr*)&direc,sizeof(direc))) < 0) {
        cout << "\nError binding connection..." << endl;
        return -1;
    }

    tamano = sizeof(direc);
    cout << "Looking for clients..." << endl;
    listen(client, 1);

    while ((server = accept(client,(struct sockaddr *)&direc,&tamano)) > 0) {
        strcpy(buffer, "Server connected...\n");
        send(server, buffer, bufsize, 0);
        cout << "Connected with the client, you are good to go..." << endl;
        cout << "Enter # to end the connection\n" << endl;

        cout << "Client: ";
        do {
            recv(server, buffer, bufsize, 0);
            cout << buffer << " ";
            if (*buffer == '#') {
                *buffer = '*';
                isExit = true;
            }
        } while (*buffer != '*');

        do {
            cout << "\nServer: ";
            do {
                cin >> buffer;
                send(server, buffer, bufsize, 0);
                if (*buffer == '#') {
                    send(server, buffer, bufsize, 0);
                    *buffer = '*';
                    isExit = true;
                }
            } while (*buffer != '*');

            cout << "Client: ";
            do {
                recv(server, buffer, bufsize, 0);
                cout << buffer << " ";
                if (*buffer == '#') {
                    *buffer == '*';
                    isExit = true;
                }
            } while (*buffer != '*');
        } while (!isExit);

        cout << "\n=> Connection terminated... " << inet_ntoa(direc.sin_addr);
        close(server);
        cout << "\nGoodbye..." << endl;
        isExit = false;
    }

    close(client);
    return 0;
}

How do I make the server accept multiple connection?
Thanks!

A: In order to properly support multiple connections you should fire up a new thread for each incoming connection. Each new connection is identified by its own unique socket descriptor returned by accept(). A simple example:
while ((accepted = accept(client,(struct sockaddr *)&direc,&tamano)) > 0) {
    /*Create the thread and pass the socket descriptor*/
    if( pthread_create(new_thread, &thread_attributes, &handle_tcp_connection, (void *)accepted) != 0){
      perror("create thread");
      exit(EXIT_FAILURE);
    }
}

A: You will need to use select or poll and a state machine pattern to do what you want to do. This means that you will need to process the data as it comes in from whichever client is sending it. Take a look here for a working example.


text:
Q: Are collaborations needed to be productive in physics? If you look at most published articles, or those on the preprint server, you find the vast majority of articles have more than one authors. Are collaborations needed to be productive in physics? In other fields like math, single author articles are the norm.

A: There are two things at work here: First, physics has advanced to the point where all the interesting problems are sufficiently complex that they almost require multiple people working on them with different areas of expertise. It's not impossible to do publishable physics research as a single individual-- it's more common in theory than experiment, but you do occasionally see single-author experimental papers. (Not in high-energy physics, but high-energy physics isn't the whole of physics by any stretch.)
The second factor is that modern physics is relatively generous about co-authorship. There are other disciplines where you have to have been far more involved in every aspect of the work to get author credit than you do in physics, where contributing to a sub-part of the data analysis will often get authorship credit.
This hasn't always been the case. If you look up some classic papers from the early 20th century, you will often find people thanked in the text for their invaluable contributions; contributions that, when described, make it sound like the person thanked really should've been listed as an author, by modern standards.

A: Nobody seems willing to try and answer this soft question, so I will have a go.
The answer is yes. Experimental High Energy Physics is the worst, with 3000 people signing  the papers in the LHC, even most theoretical papers have at least 2 names.
The basic reason, imo, is that physics has become a discipline where in order to keep everything in your head you have to have special talents, like an eidetic memory. A middle of the road physicist  has to rely on interactions outside his/her head, and what is better than a colleague to thresh out a problem or a proposition. It is a peer review right there and then, so useless ideas can be discarded fast and new ones explored. Efficiency goes up for success in publications. This holds for theorists and disciplines where one could think that one person could carry off the whole paper. It is more productive to discuss the snags with somebody else, before submitting  a publication.
In the case of experimental HEP the added burden is the enormous complexity of the experiments that need teams of people coordinated to build detectors and innumerable shifts to get at the data. It is group work, like building a cathedral.


text:
Q: What's the best rounding_method for Ruby Money gem? We're using Ruby's Money gem. In our application, we're also converting between currencies.
So the issue of rounding comes up when you convert between currencies. Currently we're using the Ruby's built-in Float#round.
However, this introduces "the dangling penny" problem.
Money.new(500,'USD').exchange_to('EUR')
#=> #Money cents:385 currency:EUR

Money.new(500,'USD').exchange_to('EUR').exchange_to('USD')
#=> #Money cents:501 currency:USD

So $5.00 becomes $5.01 after converting to Euro and then back! These are the exchange rates we're using:
{
  "GBP_TO_USD"=>1.6,
  "USD_TO_GBP"=>0.625,
  "GBP_TO_EUR"=>1.2,
  "EUR_TO_GBP"=>0.8333333333333334,
  "EUR_TO_USD"=>1.3,
  "USD_TO_EUR"=>0.7692307692307692
}

Is it possible to have a rounding method to avoid this problem of an extra or missing penny?  What would that rounding method be?
Or is this a mathematically insoluble problem?

A: Once you round a number, the information is lost. The best solution to your problem is to stop rounding (which you should not do with money anyway) and only round when you are displaying the value somewhere.

A: The latest Ruby Money gem supports fractional cents.  This would ensure that when a money object is converted to another currency and back to itself, its value would be retained.
So there's no missing/extra cent problem.

A: In the real world this may be less of an issue because the exchange rates of "from" and "to" will not be the inverse of each other.
On the other hand, what is the scenario that you need to convert back and forth? The only scenario I can think of is that you are summing up a bunch of Money objects in different currencies:
[1 USD, 2 EUR, 3 USD]
And this will trigger currency exchange from USD to EUR and back to USD.
If this is the case, try https://github.com/lulalala/money-collection to skip unnecessary currency exchange when summing up many Money objects.


text:
Q: Div shrinks when border is removed I have a problem. I have the following layout at This Weaver. (Make sure to view it fullscreen- the button is at the bottom right.)
My problem is this: when I change a border element(the border element in the .centered selector--around lines 238-240) the div appears to shrink around the content inside it. I have a background image, and it is there while the border exists, but then when you remove the border element, the image retracts as well.
For a better explanation, visit the Weaver above, and try removing line 239. See what happens. Unfortunately for me, I added that border for demonstrative purposes, and I need it removed, but what happens is unacceptable.
I need it to stay EXACTLY AS IS but WITHOUT the border(or if you could find a way to make it invisible and have the desired effect that works too). Please Help! If I'm not being clear enough please let me know, and I'll  make an edit.

A: You can make a border transparent via the border-color attribute:
.borderless { border-color: transparent; }

This can be shortened into a single line with other border related properties like so:
.borderless { border: 2px solid transparent; }

If you would prefer something you can transition smoothly to, consider RGBA values:
.centered { border: 2px solid rgba(0, 0, 0, 1); }
.borderless { border: 2px solid rgba(0, 0, 0, 0); }

Any of these methods will maintain the layout, as the border is technically still present and taking up space. If you continue to find yourself having problems with layouts shifting unexpectedly on you, try looking into box sizing:
* { box-sizing: border-box; }

will encourage layout elements to wrap borders in with their computed sizes and will make divisions behave in a fashion that's much more intuitive.

A: I think this has to do with the box model, and using padding vs. margin.
.s_container{
    margin-top: 20px;
    }

switch to:
.s_container{
    padding-top: 20px;
    }

and it seem to work fine on my machine.
To be honest, I don't don't really understand why adding/removing the border to the #configurator-container div would cause this behavior.
My understanding of the box model is that if you add a border, it's edge begins right where the padding left off. I'm confused by the large, 20px difference caused by the border's presence (as I know you are too).
Maybe one of our more experienced friends could explain this.


text:
Q: Move div onclick and back onclick I have a jQuery code that moves a certain div element on right as I click it, i'd like to move it back to its original position when I click back on it.
$(document).ready(function() {
    $("#wel1").click(function() {
        $("#sidemenu").animate({left: "80px"});
    });
});

Give me a simple example of how to achieve it?

A: One possible way to achieve it is to store the state in a variable and check its state on click.
$(document).ready(function() {
   var sideMenu = false;
    $("#wel1").click(function() {
      if (!sideMenu) {
        $("#sidemenu").animate({left: "80px"});
        sideMenu = true;
      }
      else {
        $("#sidemenu").animate({left: "0px"});
        sideMenu = false;
      }
    });
});

Please be aware that this solution has several issues:

*

*will not work for multiple menus

*can produce unwanted animation effects ("jumping") if quickly clicked

A: You can simplify this by adding an attribute to store the current state of the div.
Implemented at : http://jsfiddle.net/mwtrsw9p/
$('#movable').click(function(){
if($(this).attr("trigger")==="0"){
    $(this).animate({"left":"100px"},700);
    $(this).attr("trigger","1");
}
else{
    $(this).animate({"left":"0px"},700);
    $(this).attr("trigger","0");
}
});

HTML:

CSS :
#movable{
position:relative;
height:50px;
width:50px;
background-color:red;
}

A: I think this way is best:

css:
.animated_right{
    left:80px;
}

js:
$(document).ready(function() {
    $("#wel1").on("click", function() {
        $("#sidemenu").toggleClass("animated_right", 1000); // 1sec
    });
});

A: You could do something like this:
var toggle = 1;
$(document).ready(function() {
    $("#wel1").click(function() {
    if (toggle == 1){
        $("#sidemenu").animate({left: "80px"});
toggle = 0;
    } else{
$("#sidemenu").animate({right: "80px"});
toggle = 1;
    }
    });
});

You have a variable 'toggle' with a value of 1, when you click it will check if 'toggle' equals 1, if it does it will move to the left, and then set 'toggle' to 0, because of this the first if will result false if you click a second time, and it will use the if statement and move the object to the right, after which it will set the value of 'toggle' to 1 which will result in your desired behaviour.

A: You need a status to check whether it has been clicked or not, like below:
$("#wel1").click(function() {
    if($(this).hasClass("clicked")){
        $(this).removeClass("clicked");
        $("#sidemenu").animate({left: "80px"});
    }else{
        $(this).addClass("clicked");
        $("#sidemenu").animate({left: "0px"});
    }
});

Check out my fiddle..


text:
Q: Can't forward e-mail with .procmail rc I set up following .procmailrc
MAILDIR=$HOME/Maildir/
DEFAULT=$MAILDIR
:0 c
* ! ^X-Loop: user@hoge.jp
! forward@forward.com

but, I can't forward e-mails

A: Did you tell postfix to use procmail??  I have the following in my '~/.forward':
"|IFS=' ' && exec /usr/bin/procmail -f- || exit 75 #user"

A: Set something like:
    LOGFILE=/home/you/procmail.log
and see what shows up.  Paste it in here, and we'll be able to help more.

A: *

*why the c after :0 ? delete it

*Knows your MTA something about
procmail? under exim4 there is a
procmail router...

*if not, use also a .forward with something like that:
"|IFS=' ' && exec /usr/local/bin/procmail || exit 75 #your_user_name"

*whats with a logfile in your .procmailrc?
PATH=/bin:/usr/bin
MAILDIR=$HOME/Maildir/
DEFAULT=$MAILDIR
LOGFILE=$HOME/procmail.log


text:
Q: how to read git show command output I am just getting into VC and in particular git. I am aware of basic commands like git add/commit/remote but having a hard time understanding the output:
$ git show f27d852

commit f27d852fc750a9c3f71eaf0acf586164b76faddf
Author: myusername <myemail@gmail.com>
Date:   Tue Jun 28 22:59:35 2016 +0530

    changed color to a different color

diff --git a/css/business-casual.css b/css/business-casual.css
index bbd44d7..ee1765e 100644
--- a/css/business-casual.css
+++ b/css/business-casual.css
@@ -194,5 +194,5 @@ footer p {
 /* CUSTOM CSS - BY ME */

 .brand {
-       color: #ff0000;
-       }
\ No newline at end of file
+       color: #ffdd000;
+       }

What does each line mean? How to read it. can anyone explain?
Thanks
dk

A: commit f27d852fc750a9c3f71eaf0acf586164b76faddf

The sha1 of the commit.
Author: myusername <myemail@gmail.com>

The author's name and email, which might be different from the committer's name and email.
Date:   Tue Jun 28 22:59:35 2016 +0530

The author date, which might be different from the committer date.
changed color to a different color

The commit log message. It could be one line, or the first part + empty line(s) + the other part. The only line or the first part before the empty line(s) is subject, and the other part after the empty line(s) is body.
diff --git a/css/business-casual.css b/css/business-casual.css

The two files that have been compared.
index bbd44d7..ee1765e 100644

bbd44d7 is the sha1 of the blob before the change and ee1765e the sha1 of the blob after the change. You could run git show <blob-sha1> or git cat-file -p <blob-sha1> to see the blob's content.
--- a/css/business-casual.css

The file before the change.
+++ b/css/business-casual.css

The file after the change.
    @@ -194,5 +194,5 @@ footer p {
 /* CUSTOM CSS - BY ME */

 .brand {
-       color: #ff0000;
-       }
\ No newline at end of file
+       color: #ffdd000;
+       }

194 is the diff start line and 5 is the context lines. footer p { indicates where the diff part locates. The lines without prefixing + or - are unchanged lines. If you add one line, it's a +. If you delete a line, it's a -. If you modify a line, it's a - and a +.

A: It provides the details about commit and then list of changed files with its differencies (see unified diff for details):
# commit id:
commit f27d852fc750a9c3f71eaf0acf586164b76faddf
# author:
Author: myusername <myemail@gmail.com>
# date committed:
Date:   Tue Jun 28 22:59:35 2016 +0530
# commit message:
    changed color to a different color
# difference for css/business-casual.css :
diff --git a/css/business-casual.css b/css/business-casual.css


text:
Q: d3js / jQuery selector does not work So I have this SVG, and I want to select all paths that have a certain attribute with a certain value. Specifically the attribute key is "NEN2580" and the value can be a number of things.
So lets say we have a set of paths similar to:
<path style="stroke: rgb(0, 0, 0); fill: rgb(255, 255, 255); color: black; stroke-width: 0.25px; background-color: white;" d="M486.623,219.237 L486.375,217.624 L454.744,222.999 L454.972,224.497 L455.785,230.259 L456.344,235.117 L456.471,236.294 L457.993,236.122 L458.354,235.678 L459.039,236.234 L457.298,238.38 L462.863,242.894 L469.513,242.52 L469.228,237.441 L465.083,237.079 L465.16,236.2 L470.067,236.629 L470.395,242.471 L489.055,241.423 L488.64,236.886 L488.513,235.176 L488.369,233.611 L487.935,228.895 L487.716,226.954 L487.502,225.366 L486.623,219.237" guid="3e_Z0UB95FzQ84RHxlySDx" _id="3e_Z0UB95FzQ84RHxlySDx" type="IfcSpace" name="Cel" number="A1.01" ruimtefunctie="" toegankelijkheid="false" area="11.58914065878" NEN2580="Nuttige ruimte" ancestors="1EbDErTW54e9tQrrOBatzH,1EbDErTW54e9tQrrRq52Ux,1EbDErTW54e9tQrrRq52Uu,1EbDErTW54e9tQrrRq52Uw"></path>

I had this code which I was sure to work, but it doesn't:
d3.selectAll("path[NEN2580='Nuttige ruimte']").style({fill: 'rgb(41, 128, 185)'});

Also changing it to the following does not work:
$("path[NEN2580='Nuttige ruimte']").css("fill", "rgb(41, 128, 185)");

Is it impossible to select for keys that end with numbers? Only thing I can come up with, but I could not find any constraints in css selector documentation for attribute keys that end with numbers.
Thanks in advance

A: The attribute you're using NEN2580 is not a valid SVG attribute. To make it valid, you could define a custom XML namespace and reference that namespace in your <svg> tag. (The other attributes in your example have the same problem.) Because it's not valid, browsers aren't parsing it, so JavaScript can't select based on it.

A: Assuming you're doing this in html (rather than XML) the attribute needs to be lower case in the selector (html is not case sensitive)
$("path[nen2580='Nuttige ruimte']").css("fill", "rgb(41, 128, 185)");

A: since the attributes of the SVG are dynamically generated from a noSQL database, which is populated through another service, the name of the attribute was in capitols, NEN2580. I changed the database to write the attribute in lower case, like nen2580, and that did the trick.
Weird though that when it is in capitols, querying for lowercase does not work, but when it is in lower case as attribute, querying for capitols does not seem to matter.
So:
What doesnt work:
svg:
<path NEN2580="Nuttige ruimte">

js:
$("path[NEN2580='Nuttige ruimte']").css("fill", "rgb(1,1,1)")
$("path[nen2580='Nuttige ruimte']").css("fill", "rgb(1,1,1)")

What works:
svg:
<path nen2580="Nuttige ruimte">

js:
$("path[NEN2580='Nuttige ruimte']").css("fill", "rgb(1,1,1)")
$("path[nen2580='Nuttige ruimte']").css("fill", "rgb(1,1,1)")


text:
Q: Using Hyperledger Fabric REST interface in multi-organization network I'm trying to set up a 3-organization network, with users of each org connecting to their own peer over a REST interface.
In the examples I've seen for single-org networks, the rest connection is made to localhost, i.e. the host of all the Docker containers. In a multi-org network, what should I be trying to connect the REST interface to from the client, is it the peer of that org, i.e. peer0.org1 etc?


text:
Q: How to change bash version with homebrew I have used homebrew to install the newest version of bash on my local system. I have added a symbolic link from: /usr/local/bin/bash to /usr/local/Cellar/bash/4.2.20/bin/bash and added the line: /usr/local/bin/bash to /etc/shells
When I load my terminal I am still getting the older version of bash, also when i execute the command: /etc/local/Cellar/bash/4.2.20/bin/bash my prompt changes to bash-4.2$ but when i do bash --version it still says I am in version 3.2. Does anyone know what step I am missing?

A: You'll need to change your account's login shell from System Preferences, Users & Groups. You need to access the Advanced Options by right-clicking on your username and changing your shell to /usr/local/bin/bash. Once you've done that, restart Terminal.app (to make sure no old sessions with the wrong shell are left hanging around) and you should be set.

You can do the same using dscl:
dscl . -change /Users/<username> UserShell /usr/local/bin/bash


text:
Q: Help passing a complex object via a JSNI call to get around static scope So I've got a GWT app and I'm trying to invoke a function to change the app's view from an outside button.  Normally this is called with as "this.internalFunction('string')".  The problem is that JSNI works via static methods and so the object in question is lost.  The solution: pass the app's object itself to the JSNI call and invoke that object's function calls from there!  The problem to the solution: this doesn't work.  :(
Class looks something like this:
package blah.package;
public class Foo implements A, B {
    public native void initChangeFunc() /*-{
        $wnd.jsChangeView = $entry(this.@blah.package.Foo::doSomething
            (Lblah.package.Foo;)(this));
            //Pass this to the function call to do calls on app object
    }-*/;
    public void doSomething(Foo obj) {
        //Change view here.
        obj.internalFunction("parameter");
    };
    public void internalFunction(String param) {
        //Do stuff with param.
    }
}

On module load, call initChangeFunc() and access jsChangeView() on the page itself.
Compile errors suggest that the compiler can't find blah.package.Foo, and that's because my parameter type signature (the Lblah.package.Foo part) is wrong.
[ERROR] Line 64: Expected a valid parameter type signature in JSNI method reference

A: First thing's first, try not to break the line calling Foo::doSomething, and check to see if it helps.


text:
Q: Convert array to string in LUA Trying to convert this to a string
customLog2 = {} Which will really look like
Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
I tried this
local Data = string.format( "LogBook = %s ", customLog2 )

But Because CustomLog is an array and not a string or a number I cant insert it. Im trying to get the array into a string for this VariableFile:write(Data) So if anyone can help that would be awesome thanks.
So I want my Output to look like this "local Data = string.format( "LogBook = %s ", customLog2 )" so I can use :write then in my newly created file it should look like this Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
So this function works expect one thing.
function TableSerialization(t, i)
    local text = "{\n"
    local tab = ""
    for n = 1, i + 1 do                                                                 --controls the indent for the current text line
        tab = tab .. "\t"
    end
    for k,v in pairs(t) do
        if type(k) == "string" then
            text = text .. tab .. "['" .. k .. "'] = "
        else
            text = text .. tab .. "[" .. k .. "] = "
        end
        if type(v) == "string" then
            text = text .. "'" .. v .. "',\n"
        elseif type(v) == "number" then
            text = text .. v .. ",\n"
        elseif type(v) == "table" then
            text = text .. TableSerialization(v, i + 1)
        elseif type(v) == "boolean" then
            if v == true then
                text = text .. "true,\n"
            else
                text = text .. "false,\n"
            end
        elseif type(v) == "function" then
            text = text .. v .. ",\n"
        elseif v == nil then
            text = text .. "nil,\n"
        end
    end
    tab = ""
    for n = 1, i do                                                                     --indent for closing bracket is one less then previous text line
        tab = tab .. "\t"
    end
    if i == 0 then
        text = text .. tab .. "}\n"                                                     --the last bracket should not be followed by an comma
    else
        text = text .. tab .. "},\n"                                                    --all brackets with indent higher than 0 are followed by a comma
    end
    return text
end

My input array lets say looks like this Log = { Group = WestAPC } now this does not work because WestAPC is not a string but if WestAPC looks like this "WestAPC" it works. I need it to not be in string form.

A: To be clear, customLog is a table - that is, an associative array of key value pairs. Here's an easy way to iterate over all key/value pairs and concatenate the pairs into one string:
s = ""

t = {"a", "b", "c", 123, 456, 789} -- sample table
t.someKey = "some value" -- just an extra key value, to show that keys can be strings too

for k, v in pairs(t) do
    s = s .. k .. ":" .. v .. "\n" -- concatenate key/value pairs, with a newline in-between
end

print(s)

Of course, if the value of a key is another table {}, then you will need some extra logic to recursively iterate over these nested tables. I'll leave that for you as an exercise :)
EDIT 1:
Print table as string, showing variable values
s = ""
local ID = 123
local Numbers = 456
local Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }

s = s .. "{"
for k, v in next, Log do
    s = s .. "{"

    for vk, vv in next, v do
        if next(v, vk) ~= nil then
            s = s .. vk .. " = " .. vv .. ", "
        else
            s = s .. vk .. " = " .. vv
        end
    end

    if next(Log, k) ~= nil then
        s = s .. "}, "
    else
        s = s .. "}"
    end

end
s = s .. "}"

print(s)

EDIT 2:
Print table as string, showing variable names
s = ""
local ID = 123
local Numbers = 456
local Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }

s = s .. "{"
for k, v in next, Log do
    s = s .. "{"

    i = 1
    for vk, vv in next, v do
        name = debug.getlocal(1, i)
        if next(v, vk) ~= nil then
            s = s .. vk .. " = " .. name .. ", "
        else
            s = s .. vk .. " = " .. name
        end
        i = i + 1
    end

    if next(Log, k) ~= nil then
        s = s .. "}, "
    else
        s = s .. "}"
    end

end
s = s .. "}"

print(s)


text:
Q: Three versions of the independent two sample t-test (and R) This post concerns three versions of the independent two sample t-test:

*

*Student's t-test uses a pooled standard deviation in the denominator (all equations are shamelessly copied from Wikipedia - Student's t-test):
$$ {\displaystyle t={\frac {{\bar {X}}_{1}-{\bar {X}}_{2}}{s_{p}\cdot {\sqrt {{\frac {1}{n_{1}}}+{\frac {1}{n_{2}}}}}}}}$$
where:
$$ {\displaystyle s_{p}={\sqrt {\frac {\left(n_{1}-1\right)s_{X_{1}}^{2}+\left(n_{2}-1\right)s_{X_{2}}^{2}}{n_{1}+n_{2}-2}}}} $$
and: $$d.f. = n_1 + n_2 -2 $$
It is well known that Student's t-test can be seriously biased for unequal sample sizes and variances (Welch 1938 demonstrated this analytically, before computers and the many published simulation studies on this subject).

*Next is "an alternative criterion that has often been employed," which is less biased for unequal sample sizes and variances than is Student's t (Welch 1938). This version uses the standard error of the difference in the denominator:
$$ {\displaystyle t={\frac {{\bar {X}}_{1}-{\bar {X}}_{2}}{s_{\bar {\Delta }}}}} $$
where:
$$ {\displaystyle s_{\bar {\Delta }}={\sqrt {{\frac {s_{1}^{2}}{n_{1}}}+{\frac {s_{2}^{2}}{n_{2}}}}}.} $$
Note that if $ n_1 = n_2 $ or $ s_{X_{1}}^{2} = s_{X_{2}}^{2} $ then Student's t-test is identical to this alternative (I'll let the reader do the algebra).

*Welch (1938) presented an approximate degrees of freedom for the above statistic that further reduces bias (see Wikipedia - Welch's t-test for the formula).
Edit: I replaced the example with one that better demonstrates a Type I error.
The t.test function in R uses versions 1 or 3 above (with var.equal = TRUE or FALSE, respectively). Here's an example (see this post) where Student's and the alternative t-test are calculated from the data and then compared with the t.test function:
set.seed(4)
n1 <- 15
n2 <- 50
dat1 <- rnorm(n1, 100, 20)
dat2 <- rnorm(n2, 100, 5)
m1 <- mean(dat1)
m2 <- mean(dat2)
v1 <- var(dat1)
v2 <- var(dat2)
vp <- ((n1-1)*v1 + (n2-1)*v2) / (n1+n2-2)
t.S <- (m1-m2)/sqrt(vp/n1 + vp/n2) # Student's t (not available in R {stats})
df.S <- n1 + n2 -2 # same for Student's and Alternative t
t.A <- (m1-m2)/sqrt(v1/n1 + v2/n2) # "Alternative" t (for comparison with R)
t.R <- t.test(dat1, dat2, var.equal=TRUE) # R t.test
t.W <- t.test(dat1, dat2, var.equal=FALSE) # Welch t.test
cat(" Student's t = ", round(t.S, 3), "d.f. =" , df.S, "p.value = ",     round(2*pt(abs(t.S), df=df.S, lower.tail=F), 3), "\n",
    "Alternative t = ", round(t.A, 3), "d.f. =" , df.S, "p.value = ", round(2*pt(abs(t.A), df=df.S, lower.tail=F), 3), "\n",
    "R (var.equal=TRUE) t = ", round(t.R$statistic, 3), "d.f. =" , t.R$parameter, "p.value = ", round(t.R$p.value, 3), "\n",
    "R (var.equal=FALSE) t = ", round(t.W$statistic, 3), "d.f. =" , round(t.W$parameter, 1), "p.value = ", round(t.W$p.value, 3), "\n")

Here is the output:
Student's t =  2.956 d.f. = 63 p.value =  0.004
Alternative t =  1.768 d.f. = 63 p.value =  0.082
R (var.equal=TRUE) t =  2.956 d.f. = 63 p.value =  0.004
R (var.equal=FALSE) t =  1.768 d.f. = 14.6 p.value =  0.098

See that R is calculating the t statistics correctly. The parameters were chosen to demonstrate the serious bias that can occur when using Student's t with unequal sample sizes and variances.
Also of concern is that a linear model/ANOVA is equivalent to Student's t-test:
dat <- data.frame(y=c(dat1, dat2), g=as.factor(c(rep("A", length(dat1)), rep("B", length(dat2)))))
summary(lm(y~g, dat))
summary(aov(y~g, dat))

Here is the (abbreviated) output:
> summary(lm(y~g, dat))
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  108.827      2.388  45.569  < 2e-16 ***
gB            -8.049      2.723  -2.956  0.00438 **

> summary(aov(lm(y~g, dat)))
            Df Sum Sq Mean Sq F value Pr(>F)
g            1    747   747.5   8.737 0.00438 **
Residuals   63   5390    85.6

Note that $ F = t^2 $ for independent samples. In a subsequent paper, Welch (1951) proposed a more robust version of ANOVA (the oneway.test function in R).
OK, some questions:

*

*What is the source of the "alternative criterion," for which Welch (1938) did not provide a reference? And, what should we call it?

*Why is the standard error of the difference superior to the pooled s.d.?

*It seems that ANOVA (LM) is robust only when sample sizes or variances are equal across the groups? I should read Welch's other paper (1951).

Welch, B.L. (1938). The significance of the difference between two means when the population variances are unequal. Biometrika 29: 350–362.
Welch, B.L. (1951). On the comparison of several mean values: an alternative approach. Biometrika 38: 330–336.

A: Finally! I found this answer in Lumley et. al. (2002):

*

*The "unequal variance t-statistic" (i.e. the "alternative criterion") can easily be derived by applying the Central Limit Theorem (see the image at the bottom of this answer and note that n1 is missing in the SE in the second line).

*The CLT guarantees that the unequal variance t-statistic is normally distributed with variance equal to one for large samples. It's presented as a "Z-test" in some textbooks.

*For small samples, the unequal variance t-statistic doesn't exactly follow a t-distribution, even if the outcomes are Normal. Approximate degrees of freedom (Welch 1938) can be used for small samples.

*The CLT guarantees that Student's t (the "equal variance t-statistic") is normally distributed for large samples however the variance may not equal one, i.e. Student's t is sensitive to unequal variances when sample sizes are unequal. Likewise, LMs are sensitive to heteroscedasticity.

Lumley et. al. (2002) concluded that heteroscedasticity is a more serious problem for LMs than is Normality.
I suggest that more flexible models be applied when there is strong heteroscedasticity, including Generalised Least Squares (where the analyst specifies the form of the heteroscedasticity) and Generalised Linear Models (where the error distribution and link function define the heteroscedasticity).
The traditional approach of transforming the response variable and applying LMs can "muddy" the results: it can be difficult to explain estimates on the transformed scale (e.g. what are log dollars?) and even more difficult to back-transform estimates and associated confidence intervals to the original scale. Transformation can also bias the results (which I am currently studying).
Here's GLS applied to the same data in the question:
library(nlme)
summary(gls(y~g, dat, weights=varIdent(form = ~ 1 | g)))

Here is the (abbreviated) output:
Variance function:
 Structure: Different standard deviations per stratum
 Formula: ~1 | g
 Parameter estimates:
        A         B
1.0000000 0.2763807

Coefficients:
                Value Std.Error   t-value p-value
(Intercept) 108.82652  4.500116 24.183046  0.0000
gB           -8.04867  4.551386 -1.768399  0.0818

The weight for group B in these results equals the ratio of standard deviations, i.e. sd(dat2)/sd(dat1). The p-value is the same as that for the unequal variance t-test with d.f. = n1 + n2 - 2 (which shouldn't be surprising).
Knowing that the Normality is not an important assumption for large samples and that autocorrelation and/or heteroscedasticity are common, the GLS framework could be used more frequently (e.g. fitting a GLS model to count data with autocorrelated errors could be easier than fitting a GLM with autocorrelated errors).

Lumley T, Diehr P, Emerson S, Chen L (2002) The importance of the normality assumption in large public health data sets. Annu Rev
Public Health 23: 151–169.


text:
Q: How to set NULL values to a single character in IICS? There are 100+ incoming fields for a target transformation in IICS. NULLs can appear in any of these columns. But the end goal is to convert the NULLs in each of the incoming fields to * so that the data in the target consists of * instead of NULL.
A laborious way to do this is to define an expression for each column. That 100+ expressions to cover each and every column. The task of the expression is to convert NULL into *. But that is difficult in terms of maintenance.
In Informatica Power center there is a property on the target object that converts all the NULL values to * as shown in the below screenshot.

Tried setting the property Replacement Character on IICS for the target transformation. But that didn't help. The data is still coming in as NULL.

Do we have a similar functionality or property for target transformation on IICS? If so how to use it?

A: i think i find easier to create a reusable exp transformation with 10 input and 10 putput. Then copy it 10 times for 100 fields.

*

*create an input, output port like below -

in_col
out_col = IIF(isnull(in_col) OR is_spaces(in_col),'*',in_col)

*Then copy in_col - 10 times. And copy out_col 10 times. You need to adjust/fix the formula though.

*Save it and make it reusable'

*Then copy that reusable widget 10 times.

This has flexibility - if formula changes, you just have to change only 1 widget and viola, everything changed.

A: Try using Vertical macro. It allows writing a function that will affect a set of indicated ports. Follow the link for full documentation with examples.


text:
Q: How to install a font system wide in iOS I have created a custom keyboard plugin to support the Amharic character set (an Ethiopian dialect). The issue I'm having is that iOS doesn't have any Amharic support built in, this means that in other apps that use my keyboard, the characters appear as question marks.
Is there a way to install a custom font systemwide to make it available to all the user's apps. For example, I'd like a user to be able to type into the Notes app in Amharic.
I remember installing another Amharic keyboard from an app and it prompted me to install a new profile which did make the font available. But I'm unsure about what I need to do to make this happen in my keyboard component.

A: http://norbertlindenberg.com/2015/06/installing-fonts-on-ios/
The documentation for configuration profiles lists five ways to install them, of which the most practical ones are through email or a web server.
To install a configuration profile from email, for example for testing, simply email it to an account that you can access from the test device. If you tap on the profile icon in the email received on the device, Mail switches to Settings, which offers to install the profile. After the installation is done (or cancelled), control returns to Mail.
To make a configuration profile available for installation from a web server, store it on the web server and make sure that the extension is .mobileconfig. The content type for configuration profiles is application/x-apple-aspen-config, but Safari doesn't seem to care whether the server reports that correctly as long as the extension is there. If you point Safari to a URL with extension .mobileconfig and reasonable content, it switches to Settings, which offers to install the profile. After the installation is done (or cancelled), control returns to Safari.
Installing configuration profiles from within apps
If you want to enable installation of configuration profiles from within an app without depending on an external web server, or if you don't want to make the configuration profile available on a web server at all, then things get a little difficult. There's no API that enables installation of configuration profiles from within apps. A basic solution that developers have come up with involves multiple steps:
Set up a web server within the app.
Configure the server to respond to a request from Safari with the configuration profile, using a Content-Type header with value application/x-apple-aspen-config.
Start a background task to keep the app running in the background.
Send a request to Safari to get the configuration profile from the app's server. When receiving the profile, Safari automatically starts the installation. Once installation is done (or cancelled), control returns to Safari.
In order to return from Safari to the app automatically, additional steps are necessary:

*

*Define a custom URL scheme for the app so that Safari can return to the app (not its web server!) with a request.

*Configure the server to first send an HTML page that reloads itself periodically.

*Configure the server to send the configuration profile for the first reload, and a redirect to the app's custom URL scheme for subsequent reloads.

*Respond to the custom URL scheme by shutting down the web server.

Installing a configuration profile on iPhone - programmatically


text:
Q: Where does pam get credential information? I am learning how to write a application program which use pam to do authentication. I checked the Linux documents and some example codes, now I have a basic understanding about the pam APIs and pam configuration in /etc/pam.d/.
But I have a question is where pam get the credential information to do authentication. E.g.: If the application send the pam request with username "abc" and password "XXXXX".
How does pam check the credential information to determine whether authenticate or not? If "abc" is not a valid user for my application, but I want to add it as a valid user, how should I do to make pam authenticatin succeed ?


text:
Q: Value passed as parameter doesn't work in sql server for built in functions of datetime DECLARE @GET DATETIME
SET @GET= GETDATE()
DECLARE @Val VARCHAR(10)
SET @Val='wk'

--SELECT DATEADD(@Type,2,@GET)

 SELECT DATEPART(wk,GETDATE())  -- WORKING

The above line works but when i pass it as a paramter it doesn't work.
 SELECT DATEPART(@val,GETDATE())  -- NOT WORKING

The interval passed seems to be of other data type.

A: Make it as Dynamic Query
DECLARE @sql nvarchar(500)

DECLARE @Val VARCHAR(10)

 SET @Val='week'  --Quarter, Month

set @sql = 'SELECT DATEPART('+@val+',GETDATE())'

exec sp_executesql @sql

Or Alternatively you can use this
If @val = 'Week'
SELECT DATEPART(Week,GETDATE())
Else If @val = 'Month'
SELECT DATEPART(Month,GETDATE())
....


text:
Q: QNetworkAccessManager upload to local FTP server I can download from the server but I can't upload to it. It uploads the file but it's an empty file.
This is basically what I'm doing:
QString filename="Data.txt";
QFile file( filename );
file.open(QIODevice::ReadWrite);
file.write("HELLO") ;

QUrl urlup("ftp://127.0.0.1/file.txt");
urlup.setPassword("123");
urlup.setUserName("user");
urlup.setPort(21);
QNetworkAccessManager *nam = new QNetworkAccessManager;
QNetworkRequest requp(urlup);
nam->put(requp,&file);
file.close();

but it's not working; just uploads an empty file.

A: Instead of 127.0.0.1 use localhost
Instead of setPort append :PortNumber to url. (For example ftp://localhost:21)
Answer in this link: Putting large size file on FTP using QNetworkAccessManager

A: Try file.flush(); after write.


text:
Q: Почему разваливается адаптив? Сайт : http://окнавтуле.рф
При просмотре с телефона или через консоль в хроме, сайт выглядит нормально (версия для смартфонов)
При просмотре с других браузеров, например firefox сайт будто приближен.
Пробовал менять viewport, минимальная ширина body установлена но от изменения толку нет.
Что я проглядел?


text:
Q: webpack-dev-server fails to run with error of validateSchema this is a react hello-world proj , on local machine win7, use npm download
packages, when run " webpack-dev-server --open " it has an error like these:

F:\now\react\setup\node_modules\webpack-cli\bin\convert-argv.js:7
const validateSchema = process.webpackModule.validateSchema;

TypeError: Cannot read property 'validateSchema' of undefined
...

screenshot about error info
this is the package.json and webpack.config.js

{
  "name": "setup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --open"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "webpack": "^4.10.2",
    "webpack-cli": "^3.0.0",
    "webpack-dev-server": "^3.1.4"
  }
}

webpack.config.js:

const webpack = require('webpack');

module.exports = {

  devServer: {
    contentBase: "./src",
    historyApiFallback: true,
    inline: true
  },

  module: {
        rules: [
            {
                test: /(\.jsx|\.js)$/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: [
                            "env", "react"
                        ]
                    }
                },
                exclude: /node_modules/
            }
        ]
    }
}

A: The webpack-cli just bumped from v2 to v3 about 10 hours ago, and it looks like this might be a bug with v3. I haven't figured out an actual fix yet, but a temporary workaround is to downgrade to webpack-cli v2 by manually changing the version number in your package.json to ^2.0.0.
Hope that helps you get unstuck for the moment.


text:
Q: Review soqls on debug log to avoid too many soqls limit I have a test class which calls a visual force page and executes methods in apex controller. Currently the test class is failing on too many soql limits exception. I am trying to debug which soql query is executed multiple times. What is the best way to identify how many soqls are executed, identify any loops in the debug log? What setting in the debug log will tell me how many loops are there, how many soql queries are executed?
Thanks
Buyan

A: You can define log level as follows to view finest logs.

For more information refer Debug log levels


text:
Q: Restriction to Levi Subgroups and the Affine Grassmannian Let $G$ be a complex reductive group, $L\subset G$ a Levi subgroup and $Rep(G)$ the category of rational representations of $G$.

My Question:
  What is the geometric analogue of the restriction  functor $Res^G_L:Rep(G)\to Rep(L)$?

To be a little bit more precise:
Let    $\check{G}$ be the  dual group of $G$. As usual define $\mathcal{K}:=\mathbb{C}$ and $\mathcal{O}:=\mathbb{C}[[t]]$. Let further
$Gr_{\check{G}}:=\check{G}(\mathcal{K})/\check{G}(\mathcal{O})$ denote the affine Grassmannian and  $P_{\check{G}(\mathcal{O})}(Gr_{\check{G}})$ the category of $\check{G}(\mathcal{O})$-equivariant perverse sheaves on $Gr$.
The geometric Satake Isomorphism gives an equivalence of tensor categories categories
$$P_{\check{G}(\mathcal{O})}(Gr_{\check{G}}) \cong Rep(G)$$

Is there a nice (from the  geometric viewpoint) functor $\check{Res}:P_{\check{G}(\mathcal{O})}(Gr_{\check{G}})\to P_{\check{L}(\mathcal{O})}(Gr_{\check{L}})$ which corresponds under the geometric Satake isomorphism to the restriction functor $Res^G_L$?

A: On the level of sheaves, the construction is indeed a pull-push formula. I believe it was first worked out by Beilinson and Drinfeld in section 5.3 of their preprint "Quantization of Hitchin's Hamiltonians and Hecke eigen-sheaves". For published references, look at section 2.4 in Braverman and Gaitsgory's paper "Crystals via the affine Grassmannian" (Duke Math. J. 107 (2001), 561–575) or at section 1.3 in Vasserot's paper "On the action of the dual group on the cohomology of perverse sheaves on the affine Grassmannian" (Compositio Math. 131 (2002), 51–60).


text:
Q: How can I add objects to a "pygame.sprite.Group()"? I want to draw 3 rows of rectangles. In doing so, I want to use pygame.sprite. Group(). I get the error message: TypeError: 'type' object is not subscriptable.I checked the error message here.
Unfortunately I still don't understand why I get this error message. My pygame knowledge is not that deep.
import pygame, sys
import random
pygame.init()
clock = pygame.time.Clock()
bg = (173,216,230)
breite = 1000
hoehe = 800
screen = pygame.display.set_mode((breite,hoehe))

class Boden:
    def __init__(self):
        self.blocks = []
        self.spalten =20
        self.sp = breite // self.spalten # breite des rechtecks
        self.ho = 10 # höhe des rechtecks
        self.zeilen = 3
        self.counter_z = -1
        self.counter_s = -1
    def bauboden(self):
        self.counter_z +=0
        for i in range(self.zeilen):
            self.counter_z += 1
            for j in range(self.spalten):
                self.counter_s += 1
                block =  pygame.Rect[(i * self.ho,self.sp * j,self.sp,self.ho)]
                alle_sprites.add(block)
                self.blocks.add(self.block)

alle_sprites = pygame.sprite.Group()
boden = pygame.sprite.Group()
boden = Boden()
boden.bauboden()

alle_sprites.add(boden)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    alle_sprites.draw(screen)
    pygame.display.flip()
    clock.tick(120)

A: Your first problem has nothing to do with pygame.sprite.Group(). However, pygame.Rect is an object:
block =  pygame.Rect[(i * self.ho,self.sp * j,self.sp,self.ho)]
block =  pygame.Rect(i * self.ho,self.sp * j,self.sp,self.ho)

But still you can't add a pygame.Rect to a pygame.sprite.Group().
alle_sprites.add(block)
You have to create a pygame.sprite.Sprite object. Here is a very basic example for using a Sprite in pygame (see also Sprite):
 repl.it/@Rabbid76/PyGame-Sprite
import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):

    def __init__(self, center_pos, image):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect(center = center_pos)

    def update(self, surf):
        keys = pygame.key.get_pressed()
        self.rect.x += (keys[pygame.K_d]-keys[pygame.K_a]) * 5
        self.rect.y += (keys[pygame.K_s]-keys[pygame.K_w]) * 5
        self.rect.clamp_ip(surf.get_rect())

player_surf = pygame.image.load('Bird64.png').convert_alpha()
player = Player(window.get_rect().center, player_surf)
all_sprites = pygame.sprite.Group([player])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    all_sprites.update(window)

    window.fill(0)
    all_sprites.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

An image can be loaded to a pygame.Surface object with pygame.image.load. See How to draw images and sprites in pygame?.
A pygame.sprite.Sprite encapsulates an pygame.Surface object and an pygame.Rect object. It should have and an image and a rect attribute. image stores the sprite and rect stores the position and size of the sprite.
pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The latter delegates to the update method of the contained pygame.sprite.Sprites — you have to implement the method. See pygame.sprite.Group.update():

Calls the update() method on all Sprites in the Group. [...]

The former uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects — you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]

The Sprites in the Groups can be removed and thus destroyed by calling pygame.sprite.Sprite.kill. When the object is no longer referenced, it is destroyed:

The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.


text:
Q: GXT Scrollbars hiding fields I have a verticalLayoutContainer with a fieldset inside it and a FlowLayoutContainer inside that. When I set scroll mode to ALWAYS on the FlowLayoutContainer , the scroll bar is now hiding some of the fields inside.
Screenshots before and after adding scroll attached .
 <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder' xmlns:g="urn:import:com.google.gwt.user.client.ui"
  xmlns:c="urn:import:com.sencha.gxt.widget.core.client" xmlns:container="urn:import:com.sencha.gxt.widget.core.client.container"
  xmlns:form="urn:import:com.sencha.gxt.widget.core.client.form" xmlns:button="urn:import:com.sencha.gxt.widget.core.client.button"
  xmlns:icon="urn:import:com.ffobar.widget">

    <ui:with type="com.sencha.gxt.core.client.util.Margins" field="nomargins">
        <ui:attributes top="0" right="0" bottom="0" left="0" />
    </ui:with>
    <ui:with type="com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData" field="verticalLayoutChildData">
        <ui:attributes width="1" height="1" margins="{nomargins}"/>
    </ui:with>
    <ui:with type="com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData" field="verticalLayoutData">
        <ui:attributes width="0.32" height="1"/>
    </ui:with>

    <c:FramedPanel headerVisible="false">
        <container:VerticalLayoutContainer layoutData="{verticalLayoutData}">
            <container:child layoutData="{verticalLayoutChildData}">
                <form:FieldSet headingText="Cross References" collapsible="true" expanded="true" ui:field="fsXref" >
                    <container:FlowLayoutContainer scrollMode="ALWAYS" ui:field="gcXref" >
                        <icon:FixedGrid ui:field="grid"></icon:FixedGrid>
                    </container:FlowLayoutContainer>
                </form:FieldSet>
            </container:child>
        </container:VerticalLayoutContainer>
    </c:FramedPanel>
</ui:UiBinder>

There are text fields added to the grid, these text fields are now covered by the H. scroll.
Before

After

A: You can either put a padding on the right side of your panel to account for the scroll bar or you can use the scrolling support in VLC which has a method adjustForScroll. However, this always adjusts the content to account for the scrollbar, even if there is no scroll bar.
I overcame this issue by checking if a scroll bar was present on the VLC:
boolean hasScroll = container.getScrollSupport().getMaximumVerticalScrollPosition() > 0;
container.setAdjustForScroll(hasScroll);


text:
Q: Decomposition of modules using computer packages I am interested in computing direct sum decomposition of  modules over some quotients of polynomial rings over a field (do not care much about the field at this point). Does any one know a package which does that? I tried searching Macaulay 2 but could not find any. Thanks.
EDIT: Perhaps the question was a bit vague, so I will add a specific example. Let $R=k[X_{11},...X_{33}]/I$, with $k$ say, $\mathbb Q$ or $\mathbb Z/(p)$ with $p>3$ and $I$ generated by the 2x2 minors. Let $M=(x_{11},x_{12},x_{13})$. I would like to be able to understand the direct summands of syzygies of $M$. They are all maximal Cohen-Macaulay, but that's all I know.

A: Suppose A = C[[x,y,z]]/f(x,y,z) is one of the ADE singularities, where there are finitely many indecomposables P_1,...,P_n.  In analogy with character theory of finite groups, we want to set up a situation where Hom(P_i,P_j) = delta _ij.  That will allow us to decompose a reflexive A-module into a direct sum of indecomposables (in the same way one decomposes a representation into a direct sum of irreducible representations).
The triangulated category \underline{CM}(A)  = CM(A)/A has a t-structure with heart CM(A), in which the finitely many indecomposables are the simple objects.  The simples satisfy Hom^0(S_i, S_j) = delta ij.  To compute Hom^0 in this category use the equation \underline{Hom}(M,N) \simeq Ext^2_A(M,N).  (See Burban and Drozd's survey paper, especially page 46.)
So basically you just have to compute Ext^2 in the complete local ring A. Singular can do this directly.
If you don't want to download Singular, Macaulay2 can do it, although it takes some care, because Macaulay naturally works with graded modules over polynomial rings; (one has to be careful with grading shifts.)  For more information on the graded case, see the papers by [Kajiura Saito and Takahashi].


text:
Q: How to change the position of the control SWT? I am new in SWT
I tried to create scroller and two buttons
The problem that the layout of the button is not in the right place.
I want that the scroller will be in the right place and the buttons will be near to the scroller
    Composite composite= new Composite(parent, SWT.NONE);
    GridLayout layout= new GridLayout(1, false);
    layout.marginHeight= 0;
    layout.marginWidth= 0;
    layout.horizontalSpacing= 0;
    layout.verticalSpacing= 0;
    composite.setLayout(layout);

    fComposite= new Composite(composite, SWT.NONE);
    GridData layoutData= new GridData(SWT.FILL, SWT.TOP, true, false);
    fComposite.setLayoutData(layoutData);
    layout= new GridLayout(1, false);
    layout.marginHeight= 0;
    layout.marginWidth= 0;
    layout.horizontalSpacing= 0;
    layout.verticalSpacing= 0;

    fComposite.setLayout(layout);

    Composite eComposite= new Composite(composite, SWT.NONE);
    eComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    FillLayout fillLayout= new FillLayout(SWT.VERTICAL);
    fillLayout.marginHeight= 0;
    fillLayout.marginWidth= 0;
    fillLayout.spacing= 0;

    eComposite.setLayout(fillLayout);

    Display display = parent.getDisplay();
    Shell shell = parent.getShell();
    Button button = new Button(fComposite, SWT.RIGHT_TO_LEFT);
    button.setText("Left"); //$NON-NLS-1$
    button.setImage(display.getSystemImage(SWT.ICON_ERROR));

    final Scale scale = new Scale (fComposite, SWT.BORDER);
    Rectangle clientArea = fComposite.getClientArea ();
    scale.setBounds (clientArea.x, clientArea.y, 200, 64);
    scale.setMaximum (4);
    scale.setPageIncrement (1);
    scale.setSelection(4);

    Button rButton = new Button(fZoomerComposite, SWT.RIGHT_TO_LEFT);
    rButton.setText("Right"); //$NON-NLS-1$
    rButton.setImage(display.getSystemImage(SWT.ICON_INFORMATION));

    scale.addListener(SWT.Selection, new Listener() {
          public void handleEvent(Event event) {
          }
        });
![current control should move right and need to fix the buttons][1]


text:
Q: Flatten/Concatenate an array to a list for match in excel formula I have a table of data in excel which has double header rows.  I would like to perform an hlookup against this table using a flattened version of the two headers.  For example, if my data were like this
    A      B      C     D       E      F
 1  cat    cat    boy    boy    egg    egg
 2  1      2      1      4      3      1
 3  val1  val2   val3   val4   val5   val6
 4  val7  val8   val9   val10  val11  val12
 5  val13 val14  val15  val16  val17  val18
 6  val19 val20  val21  val22  val23  val24

I want to  match something like this: =match("boy4", concatenate(A1:A6,b1:b6)) ) with a result of 4.
This doesn't work though, because  concatenate(A1:A6,b1:b6) returns egg1 as a regular formula, or cat1 as an array formula.
Is there a way within a single function (without creating a separate row to hold those values) to generate a list like cat1   cat2   boy1   boy4   egg3   egg1 that can then be wrapped inside match?

A: CONCATENATE() cannot accept a range of cells as arguments. Instead you just have to concatenate the ranges yourself with &. This is an array formula, and must be confirmed with ctrl+shift+enter.
=MATCH("boy4",A1:F1&A2:F2,0)


text:
Q: Updating ResultSet with select query containing rownum I'm trying to execute select query with table that doesn't contain primary key therefore I'm including row num in the select query so that the result set becomes scrollable but it is not updating and gives the error below
Java Code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        Connection con = Provider.getOracleConnection();
        String sql = "select rownum, users.* from users";
        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = st.executeQuery(sql);
        rs.absolute(1);
        rs.updateString(3, "Bibek Bhusan");
        rs.updateRow();
    }
}

Error:
Exception in thread "main" java.sql.SQLException: ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc.

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1169)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3285)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3368)
    at oracle.jdbc.driver.UpdatableResultSet.executeUpdateRow(UpdatableResultSet.java:2690)
    at oracle.jdbc.driver.UpdatableResultSet.updateRow(UpdatableResultSet.java:1835)
    at Test.main(Test.java:15)

A: Just remove the rownum column and it should work. rownum does not identify a specific row. It's just the position of the row in that particular query result. Rexecuting the same query can return the rows in a different order in which case the rows will have different rownums.