Q: Is it possible to control order of replication? I have a huge master CouchDB database and slave read-only CouchDB database, that synchronizes with master database.
Because rate of changes is quick, and channel between servers is slow and unstable, I want to set order/priority to define what documents come first. I need to ensure that the documents with highest priority are definitely of the latest version, and I can ignore documents in the end of list.
SORTING, not FILTERING
If it is not possible, what solution could be?
Resource I have already looked at:
http://wiki.apache.org/couchdb/Replication
http://couchapp.org/page/index
UPDATE: the master database is actually Node.js NPM registry, and order is list of Most Depended-upon Packages. I am trying to make proxy, because cloning 50G always fails after a while. But the fact is "we don't need 90% of those modules, but quick & reliable access to those we depend on."

A: CouchDB, out of the box, does not provide you with any options to control the order of replication. I'm guessing you could piece something together if you keep documents with different priorities in different databases on the master, though. Then, you could replicate the high-priority master database into the slave database first, replicate lower-priority databases after that, etc.

A: The short answer is no.
The long answer is that CouchDB provides ACID guarantees at the individual document level only, by design. The replicator will update each document atomically when it replicates (as can anyone, the replicator is just using the public API) but does not guarantee ordering, this is mostly because it uses multiple http connections to improve throughput. You can configure that down to 1 if you like and you'll get better ordering, but it's not a panacea.
After the bigcouch merge, all bets are off, there will be multiple sources and multiple targets with no imposed total order.

A: You could set up filtered replication or named document replication:

*

*http://wiki.apache.org/couchdb/Replication#Filtered_Replication

*http://wiki.apache.org/couchdb/Replication#Named_Document_Replication
Both of these are alternatives to replicating an entire database.  You could do the replication in smaller batch sizes, and order the batches to match your priorities.


Q: component moves to original position when window is resized I have a draggable JPanel that is added into a JFrame with the NetBeans IDE JFrame Form editor. When I run the program and drag the card somewhere other than the original position and resize the JFrame, the JPanel is returned to its original position.
Before (When program first run):

Moved Card:

Resized Window:

I'm at a loss to understand why this happens and how to prevent it.
My Frame:
package cards;

import cards.cards.*;
/**
 *
 * @author Nicki
 */
public class ImgTest extends javax.swing.JFrame {

    /**
     * Creates new form ImgTest
     */
    public ImgTest() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        card2 = new cards.cards.Card();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Imgtest");
        setMinimumSize(new java.awt.Dimension(250, 250));
        setPreferredSize(new java.awt.Dimension(250, 250));

        javax.swing.GroupLayout card2Layout = new javax.swing.GroupLayout(card2);
        card2.setLayout(card2Layout);
        card2Layout.setHorizontalGroup(
            card2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 71, Short.MAX_VALUE)
        );
        card2Layout.setVerticalGroup(
            card2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 96, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(card2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(158, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(card2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(133, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]){
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ImgTest().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private cards.cards.Card card2;
    // End of variables declaration
}

My card panel:
package cards.cards;

import cards.images.CardImageProvider;
import java.awt.Canvas;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;

/**
 *
 * @author Nicki
 */
public class Card extends JPanel {

    private Image cardImg;
    private Cards card;
    private volatile int draggedAtX, draggedAtY;

    public Card(Cards c) {
        this.setSize(71, 96);
        card = c;
        cardImg = CardImageProvider.getCardImage(c);
        addMouseListener(new MouseAdapter(){

            public void mousePressed(MouseEvent e){
                draggedAtX = e.getX();
                draggedAtY = e.getY();
            }
        });

        addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseDragged(MouseEvent e){
                setLocation(e.getX() - draggedAtX + getLocation().x,
                        e.getY() - draggedAtY + getLocation().y);
                repaint();
            }
        });
        this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }

    public Card(){
        this(Unknown.UNKNOWN);
    }

    @Override
    public void paintComponent(Graphics g) {
        this.setSize(71, 96);
        g.drawImage(cardImg, 0, 0, this);
    }

    public void setCard(Cards c) {
        card = c;
        cardImg = CardImageProvider.getCardImage(c);
        repaint();
    }

    public Cards getCard() {
        return card;
    }

}

I would like to know how to prevent the card moving back to its first position.
Thanks in advance.

A: By defaults an IDE will use a layout manager to position components on the frame.
When you drag the panel you are manually setting the location of the panel and overriding the location determined by the layout manager.
However, when you resize the frame the layout manager code is again executed and the panel is set back to its original position.
You need to change your code so that the parent panel of the panel you drag uses a "null layout". However, when you do this you are now responsible for setting the size and location of the panel.


Q: MATLAB insert character separated with space from GUI I need to input characters from a GUI but they need to be separated by spaces. Every time a new character is added, it should be appended to the existing array.
For example:

*

*user enters 'a', the content of array is 'a'

*if user enters 'b' next, the content of array is 'a b'
Edit 1
These lines of code should be inside the pushbutton1_callback function, so whenever the user presses the button, a new character should be added to static text; separated by a space.
Edit 2
My only line of code in here is:
letter = get(handles.edit1, 'string')

A: Without details I can provide a conceptual solution.
Initialize the variable that holds the text to:
txt = '';

Then the callback will do:
txt = strtrim(sprintf('%s %s',txt, get(handleToTextBox,'String')));

A: letter = get(handles.edit1, 'string');
global txt;
txt=[txt letter];
txt=[txt ' '];
set(handles.text1, 'string', txt);

That's how I solved it.


Q: Citrix unable to start session in Firefox Quantum In order to access the database service DBoD it is necessary to create a session through Citrix Receiver. But in Firefox this is no longer possible. Is this because "Citrix Receiver" was replaced by "Citrix Workspace"? And how to solve this problem for Firefox?
Here is the error message:

Citrix Receiver cannot connect to the server. To resolve this issue,
  please report this error to your help desk. Please verify that the ICA connection is available and that the server
  address is present.

And here the same error in German language:

Citrix Receiver kann keine Verbindung mit dem Server herstellen.
  Melden Sie diesen Fehler dem Helpdesk, um das Problem zu beheben.
  Überprüfen Sie, ob die ICA-Verbindung verfügbar und
  die Serveradresse vorhanden ist.

A: According to the Citrix blog
Firefox 52 and Citrix Receiver for Web,
the reason for the problem is that Firefox version 52 has dropped support for NPAPI.
The advice given was:

you have to edit the web.config file under the Receiver for Web
  (RfWeb) site (typically C:\inetpub\wwwroot\Citrix\StoreWeb) to
  activate the Citrix Receiver Launcher for Firefox 52.
Open web.config using your preferred text editor and locate the line
  highlighted in the screen shot:

This is a regular expression specifying that the Citrix Receiver Launcher is used for Firefox 53 and later. Change the highlighted bit to (Firefox/((5[2-9]|[6789][0-9])|\d\d\d)) to make RfWeb use the Citrix Receiver Launcher on Windows and Mac for Firefox 52 onward.


Q: How would I write this as another form of PHP Hey I had a question I can not figure out how to write this code:

<?=$rs['username']." ~ ".$rs["webcam_status"]?>

When I have my code already set up as only 1 php markup, the code:
<?php
echo"

";
    include "../../access/$template/header.php";
    echo "

<?=$rs['username']." ~ ".$rs["webcam_status"]?>

";
    include "../../access/$template/footer.php";
    echo "

";
?>

I know how to write it differently, does anybody know how to write it that way?

A: You can't cause PHP to output PHP and then parse that PHP and execute it.
Add your data via string concatenation instead.
Better yet: Geek echo statements to a minimum, and drop out of PHP mode with <? when you are just outputting static data.

A: <?php
echo"

";
    include "../../access/$template/header.php";
    echo "

".$rs['username']." ~ ".$rs["webcam_status"]."

";
    include "../../access/$template/footer.php";
    echo "

";
?>


Q: Remove all CSS Stylesheets from a page I want to show a page without any css applied. Is it somehow possible to add a jquery switch inside the page to disable all stylesheets?
Reason: I want to show a client the importance of Design by giving him the opportunity to disable the css styles of his site. It is way more convincing when he can trigger it on his own :)

A: If you want it to fire after a click:
$(".element").click(function(){
    $("link[rel='stylesheet']").remove();
});

or at the beginning:
 $(document).ready(function(){
        $("link[rel='stylesheet']").remove();
 });

A: Try this:
$('link[rel="stylesheet"]').remove();

This will remove all stylesheets (all the styles applies due to those stylesheets) from the page.

A: Just spent few mintues to draft one
 (function(f,a,s,x){
  x=$(a);x.map(function(i,o){o=$(o);o.data(s+s,o.attr(s));o.removeAttr(s)});
  $(s+',link[rel='+s+'sheet]').appendTo(f);
  setTimeout(function(){
   $(a,f).appendTo('head');
   x.map(function(i,o){o=$(o);o.attr(s,o.data(s+s))})
  },999);
 })($('<i>'),'*','style');

A: Disable all
StyleSheetList.prototype.forEach=Array.prototype.forEach; // *Note
document.styleSheets.forEach((ss)=>ss.disabled=true);

or (Disable All)
for(styleSheet of document.styleSheets){ styleSheet.disabled=true; }

or (Remove all)
StyleSheetList.prototype.forEach=Array.prototype.forEach;
document.styleSheets.forEach((ss)=>ss.ownerNode.parentNode.removeChild(ss.ownerNode));

or (Remove all)
for(styleSheet of document.styleSheets){ styleSheet.ownerNode.parentNode.removeChild(styleSheet.ownerNode); }

*Note:
If you don't want to change the prototype, you can invoke it like this:
Array.prototype.forEach.apply(document.styleSheets,[(ss)=>ss.disabled=true])

A: Try this
$('link[rel="stylesheet"]').remove();

A: Place this on document ready:
$('link[rel=stylesheet]').remove();

Or bind it to a button.

A: A rough, dirty and brute approach:
document.querySelector("head").remove();

A bookmarklet version of the same code that you can paste as the URL of a bookmark.
You can also paste it into the address bar (for security reasons, when you paste the text, chrome/firefox remove the javascript: bit at the beginning so you'll need to type that by hand):
javascript:(function(){document.querySelector("head").remove();})()

A: Use below code to remove all kinds of styles, inline, internal, external.

let elements=document.querySelectorAll("*");
elements.forEach(el=>{
    if(el.tagName==="LINK" || el.tagName==="STYLE") el.remove();
    else el.removeAttribute("style");
});

Thank me later! ;)


Q: gurobipy.GurobiError: Element 302194 of a double array is Nan or Inf I am trying to solve an ILP that optimises a problem on graphs using Gurobi. Unfortunately, I get the following error when creating the problem:

gurobipy.GurobiError: Element 302194 of a double array is Nan or Inf.

The error is thrown when setting the objective.

m.setObjective(quicksum([G.G.nodes[node]['prize'] * node_var for
node, node_var in nodes.items()])
- quicksum([mod_var * mod[1][1] for mod, mod_var in modules.items()]),
GRB.MAXIMIZE)

All my variables are initialised and have a finite value. I don't understand which double array is being referenced. I have not found a solution online.
Can anyone help me?

A: It's difficult to debug inside a Python generator expression. Try debugging by rewriting as loops, like the following:
obj = 0
for node, node_var in nodes.items():
  # print(f"node={node}, prize={G.G.nodes[node]['prize']}, node_var={node_var}")
  obj += G.G.nodes[node]['prize'] * node_var

for mod, mod_var in modules.items():
  # print(f"mod_var={mod_var}, mod={mod[1][1]}")
  obj -= mod_var * mod[1][1]

m.setObjective(obj, GRB.MAXIMIZE)

Since I can't test this code, it's possible there may be errors, but this should give you some ideas how to debug your issue.


Q: In Javascript selenium webdriver how to use if statement to check if web element actual exists? I would like to write a loop (if there is another solution even better) where i check if a given element exists.  I have select list with huge amounts of options, when i select item various new items appear. They constist of constant elements with assigned values
E.g
product exmaple :
-product
-something something
There is a limited number element like procduct exmaple with the same first semi row names like product. I would like to write a loop that checks if product exmaple  is existing or not  and get something something element
I try if use asserts in if loop, i try to get to made findElement  to boolean value but i don't know what to do 2


Q: How can I change the IP address of all sites in IIS6 using powershell 1.0? Using Powershell 1.0 under Windows Server 2003 with IIS 6.
I have about 200 sites that I would like to change the IP address for (as listed in the website properties on the "website" tab in the "Web site identification" section "IP address" field.
I found this code:
$site = [adsi]"IIS://localhost/w3svc/$siteid"
$site.ServerBindings.Insert($site.ServerBindings.Count, ":80:$hostheader")
$site.SetInfo()

How can I do something like this but:

*

*Loop through all the sites in IIS

*Not insert a host header value, but change an existing one.

A: The following PowerShell script should help:
$oldIp = "172.16.3.214"
$newIp = "172.16.3.215"

# Get all objects at IIS://Localhost/W3SVC
$iisObjects = new-object `
    System.DirectoryServices.DirectoryEntry("IIS://Localhost/W3SVC")

foreach($site in $iisObjects.psbase.Children)
{
    # Is object a website?
    if($site.psbase.SchemaClassName -eq "IIsWebServer")
    {
        $siteID = $site.psbase.Name

        # Grab bindings and cast to array
        $bindings = [array]$site.psbase.Properties["ServerBindings"].Value

        $hasChanged = $false
        $c = 0

        foreach($binding in $bindings)
        {
            # Only change if IP address is one we're interested in
            if($binding.IndexOf($oldIp) -gt -1)
            {
                $newBinding = $binding.Replace($oldIp, $newIp)
                Write-Output "$siteID: $binding -> $newBinding"

                $bindings[$c] = $newBinding
                $hasChanged = $true
            }
            $c++
        }

        if($hasChanged)
        {
            # Only update if something changed
            $site.psbase.Properties["ServerBindings"].Value = $bindings

            # Comment out this line to simulate updates.
            $site.psbase.CommitChanges()

            Write-Output "Committed change for $siteID"
            Write-Output "========================="
        }
    }
}


Q: AttributeError: 'DataFrame' object has no attribute 'droplevel' in pandas I am getting a strange (to my understanding) message when I try to drop a level from a multi-indexed pandas dataframe.
For a reproducible example:
toy.to_json()
'{"["ISRG","EPS_diluted"]":{"2004-12-31":0.33,"2005-01-28":0.33,"2005-03-31":0.25,"2005-04-01":0.25,"2005-04-29":0.25},"["DHR","EPS_diluted"]":{"2004-12-31":0.67,"2005-01-28":0.67,"2005-03-31":0.67,"2005-04-01":0.58,"2005-04-29":0.58},"["BDX","EPS_diluted"]":{"2004-12-31":0.75,"2005-01-28":0.75,"2005-03-31":0.72,"2005-04-01":0.72,"2005-04-29":0.72},"["SYK","EPS_diluted"]":{"2004-12-31":0.4,"2005-01-28":0.4,"2005-03-31":0.42,"2005-04-01":0.42,"2005-04-29":0.42},"["BSX","EPS_diluted"]":{"2004-12-31":0.35,"2005-01-28":0.35,"2005-03-31":0.42,"2005-04-01":0.42,"2005-04-29":0.42},"["BAX","EPS_diluted"]":{"2004-12-31":0.18,"2005-01-28":0.18,"2005-03-31":0.36,"2005-04-01":0.36,"2005-04-29":0.36},"["EW","EPS_diluted"]":{"2004-12-31":0.4,"2005-01-28":0.4,"2005-03-31":0.5,"2005-04-01":0.5,"2005-04-29":0.5},"["MDT","EPS_diluted"]":{"2004-12-31":0.44,"2005-01-28":0.45,"2005-03-31":0.45,"2005-04-01":0.45,"2005-04-29":0.16},"["ABT","EPS_diluted"]":{"2004-12-31":0.63,"2005-01-28":0.63,"2005-03-31":0.53,"2005-04-01":0.53,"2005-04-29":0.53}}'

toy.droplevel(level = 1, axis = 1)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-982eee5ba162> in <module>()
----> 1 toy.droplevel(level = 1, axis = 1)

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   4370             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   4371                 return self[name]
-> 4372             return object.__getattribute__(self, name)
   4373
   4374     def __setattr__(self, name, value):

AttributeError: 'DataFrame' object has no attribute 'droplevel'

A: Problem is the use of an older pandas version, because if you check DataFrame.droplevel:

New in version 0.24.0.

The solution is to use MultiIndex.droplevel:
toy.columns = toy.columns.droplevel(level = 1)


Q: built in __dict__ is returning names of attributes with class names as prefix class Enrollment(object):

    def __init__(self,enrollmentId=None, enrollmentReference=None):
        self.enrollmentId = enrollmentId
        self.enrollmentReference = enrollmentReference

    @property
    def enrollmentId(self):
        return self.__enrollmentId

    @enrollmentId.setter
    def enrollmentId(self, enrollmentId):
        self.__enrollmentId = enrollmentId

    @property
    def enrollmentReference(self):
        return self.__enrollmentReference

    @enrollmentReference.setter
    def enrollmentReference(self, enrollmentReference):
        self.__enrollmentReference = enrollmentReference

If i now try to print the attributes of the above class:
print(Enrollment().__dict__)

It prints the attributes prefixed with class name as below:
{'_Enrollment__enrollmentId': None, '_Enrollment__enrollmentReference': None}

Note: If I remove object as the super class, all works well and it prints the attributes correctly as below:
{'enrollmentId': None, 'enrollmentReference': None}

I have been been wrapping my head around this for 2 days now with no luck.
Not able to understand why the class name is prefixed to attributes. I need to serialize the Enrollment object to JSON.

A: In a class definition, Python transforms __x into _classname__x.  This is called name mangling.  Its purpose is to support class local references so that subclasses don't unintentionally break the internal logic of the parent class.

A: Cause
This is due to Python's name mangling of class attribute names that start with __ and are suffixed with at most a single _. This suggests a stricter privacy for these attributes.
Note: This is still a heuristic and shouldn't be counted on for access prevention.
From the docs:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

class A:
    def __foo_(self): pass

print(vars(A))

outputs
{'__module__': '__main__', '_A__foo_': <function A.__foo_ at 0x1118c2488>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

Notice that __foo_ has been mangled into _A__foo_.
Uses
Why might this be useful? Well the example from the docs is pretty compelling:

Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example:

class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)

tldr
Read the docs on name mangling.


Q: Laravel: groupBy to nested json I have an end point the current response is as below, when we query with groupBy() it returns only one row, but how to get an nested json with hidden grouped values.
//controller

    public function products()
    {
        $get_products = Product::groupBy('name')
                               ->get();

        $data = [
            'data' => $get_products
        ];

        return Response::json(
            $data_with_status = array_merge($this->respondSuccess('query successfull'), $data)
        );
    }

//json response

    {
        "status_code": 200,
        "status_message": "query successfull",
        "data": [
            {
                "id": 1,
                "name": "onion",
                "proportion": "500 gm",
                "mrp": "25",
                "price": "22",
                "status": "1"
            }
        ]
    }

The expected result is as below, is there a query to achieve this,
{
    "status_code": 200,
    "status_message": "query successfull",
    "data": [
        {
            "id": 1,
            "name": "onion",
            "proportion": {
                "0": "500 gm",
                "1":  "1 kg",
            }
            "mrp": "25",
            "price": "22",
            "status": "1"
        },
        {
            "id": 2,
            "name": "tomato",
            "proportion": "500 gm"
            "mrp": "20",
            "price": "15",
            "status": "1"
        }
    ]
}

The Database schema is as below
Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('proportion');
    $table->string('mrp');
    $table->string('price');
    $table->enum('status', ['available','unavailable']);
    $table->timestamps();
    $table->softDeletes();
});

Sample data to group By from products table
id  name      proportion  mrp  price  status
1   onion      500 gm     25    22     1
2   onion      1 kg       50    44     1
3   tomato     500 gm     20    15     1

if product name is same meaning if a product have multiple proportion i want to group the products and merge the proportions in a json as shown in the above expected json result.
thank you

A: Use group_cancat() -
$get_products = Product::select('id','name','mrp','price','status',DB::raw('group_concat(proportion)'))
               ->groupBy('name')->get();


Q: The wiki editor generates a link "Template:Multiple Image" (to a page that does not exist) when I try to use the multiple image template I am editing a wiki and I want to insert multiple images thanks to the {{multiple image}} template. Here is my code:
{{multiple image
| footer = foo
| image1 = foo1.png
| caption1 = foo 1
| image2 = foo2.jpg
| caption2 = foo 2
}}

However this code generates a link Template:Multiple Image to a page that does not exist.
I obviously read the wiki documentation and looked for an answer on the web and on stackoverflow but I could find nothing about this bug. What am I doing wrong ?


Q: Gives me this error in gplus-api using JS Hello i just started learning gplus-api signin using javascript but i came across a error that says this Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
 This is my code i have referred to this site but didn;t help me! https://developers.google.com/+/web/signin/javascript-flow
My code
<!DOCTYPE HTML>
 <html>
   <head></head>
 <body>
    <script src="https://apis.google.com/js/client:platform.js" async defer></script>

    <meta name="google-signin-clientid" content="MY_CLIENT_ID.apps.googleusercontent.com">
    <meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
    <meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" />
    <meta name="google-signin-cookiepolicy" content="single_host_origin" />

  <script type="text/javascript">
    (function(){
      var po = document.createElement('script');
      po.type = "text/javascript";
      po.async = true;
      po.src = "https://apis.google.com/js/client:plusone.js";
      var s = document.getElementByTagName('script');
      s.parentNode.insertBefore(po,s);
  });

 function render() {

  // Additional params including the callback, the rest of the params will
  // come from the page-level configuration.
   var additionalParams = {
     'callback': signinCallback
  };

  // Attach a click listener to a button to trigger the flow.
   var signinButton = document.getElementById('signinButton');
   signinButton.addEventListener('click', function() {
       gapi.auth.signIn(additionalParams); // Will use page level configuration
    });
 }

  function signinCallback(authResult) {
      if (authResult['status']['signed_in']) {
   // Update the app to reflect a signed in user
   // Hide the sign-in button now that the user is authorized, for   example:
      document.getElementById('signinButton').setAttribute('style',             'display: none');
    } else {
    // Update the app to reflect a signed out user
    // Possible error values:
   //   "user_signed_out" - User is signed-out
   //   "access_denied" - User denied access to your app
   //   "immediate_failed" - Could not automatically log in the user
   console.log('Sign-in state: ' + authResult['error']);
   }
  }
 </script>
  <button id="signinButton">Sign in with Google</button>
  </body>
  </html>

my js origin is http://localhost:8080, also when i try to load this url it gives me 404 error
please help to solve me this error!

A: You must run a web server (even locally) when working with Google+ Sign in. A simple example is to run Python with your port set to 8080:
python -m SimpleHTTPServer 8080

You can also configure / run Apache or another server for local testing.


Q: Where can I register for WNS in Windows Developer Center I want to know how to enable Windows Notification Services for UWP apps.

A: The steps to enable WNS for your UWP app have changed, but the documentation has not yet been updated.
To enable WNS:

*

*Register for a developer account at developer.microsoft.com

*Create a new app - you can do this through Visual Studio by right clicking your UWP app > Store > Associate app with store

*In Microsoft Developer Center, select your app and go to App Management > WNS/MPNS. Follow the link to Live Services Site

*Here you can find your app secret and Package SID required to enable WNS


Q: How to join/merge two generators output using python I have two generators g1 and g2
for line in g1:
    print line[0]

[a, a, a]
[b, b, b]
[c, c, c]
for line1 in g2:
    print line1[0]

[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
for line in itertools.chain(g1, g2):
    print line[0]

[a, a, a]
[b, b, b]
[c, c, c]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]

How
do I get the output like:
[a, a, a],[1, 1, 1]
[b, b, b],[2, 2, 2]
[c, c, c],[3, 3, 3]
or
[a, a, a, 1, 1, 1]
[b, b, b, 2, 2, 2]
[c, c, c, 3, 3, 3]

Thank You for Your help.

A: You can use itertools.izip for example
g1=([s]*3 for s in string.ascii_lowercase)
g2=([s]*3 for s in string.ascii_uppercase)
g=itertools.izip(g1,g2)

This will ensure the resultant is also a generator.
If you prefer to use the second here is how you can do it
g1=([s]*3 for s in string.ascii_lowercase)
g2=([s]*3 for s in string.ascii_uppercase)
g=(x+y for x,y in itertools.izip(g1,g2))

A: You can get pairs of things (your first request) using zip(g1, g2). You can join them (your second request) by doing [a + b for a, b in zip(g1, g2)].
Almost equivalently, you can use map. Use map(None, g1, g2) to produce a list of pairs, and map(lambda x, y: x + y, g1, g2) to join the pairs together.
In your examples, your generators are producing a list or tuple each time, of which you're only interested in the first element. I'd just generate the thing you need, or preprocess them before zipping or mapping them. For example:
g1 = (g[0] for g in g1)
g2 = (g[0] for g in g2)

Alternatively, you can apply [0] in the map. Here's the two cases:
map(lambda x, y: (x[0], y[0]), g1, g2)
map(lambda x, y: x[0] + y[0], g1, g2)

A: Let's say you have g1 and g2 :
g1 = [
    [['a', 'a', 'a'], ['e', 'e'], ['f', 'g']],
    [['b', 'b', 'b'], ['e', 'e'], ['f', 'g']],
    [['c', 'c', 'c'], ['e', 'e'], ['f', 'g']],
]

g2 = [
    [[1, 1, 1], ['t', 'q'], ['h', 't']],
    [[2, 2, 2], ['r', 'a'], ['l', 'o']],
    [[3, 3, 3], ['x', 'w'], ['z', 'p']],
]

To get that :
[a, a, a],[1, 1, 1]
[b, b, b],[2, 2, 2]
[c, c, c],[3, 3, 3]

You can do that :
result1 = map(lambda a, b: (a[0], b[0]) , g1, g2)
# Which is like this :
[(['a', 'a', 'a'], [1, 1, 1]),
 (['b', 'b', 'b'], [2, 2, 2]),
 (['c', 'c', 'c'], [3, 3, 3])]

And for the second :
[a, a, a, 1, 1, 1]
[b, b, b, 2, 2, 2]
[c, c, c, 3, 3, 3]

result2 = map(lambda a, b: a[0]+b[0] , g1, g2)
# Which is like that :
[['a', 'a', 'a', 1, 1, 1],
 ['b', 'b', 'b', 2, 2, 2],
 ['c', 'c', 'c', 3, 3, 3]]

A: first case: use
for x, y in zip(g1, g2):
    print(x[0], y[0])

second case: use
for x, y in zip(g1, g2):
    print(x[0] + y[0])

You can of course use itertools.izip for the generator version. You get the generator automatically if you use zip in Python 3 and greater.


Q: graphQl - return all in db I'm really new to graphQL
I have a simple graphQL schema here
const graphql = require('graphql');
const _ = require('lodash');

const {
  GraphQLObjectType,
  GraphQLString,
  GraphQLSchema,
  GraphQLID
} = graphql

const books = [
  { name: "book 1", genre: "book-1", id: "1" },
  { name: "book 2", genre: "book-2", id: "2" },
  { name: "book 3", genre: "book-3", id: "3" }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    genre: { type: GraphQLString }
  })
})

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: { id: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(books, { id: args.id })
      }
    }
  }
})

module.exports = new GraphQLSchema({
  query: RootQuery
})

I can return one book using the id
const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: { id: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(books, { id: args.id })
      }
    }
  }
})

How would I return all the books, I was thinking something like:
const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: {},
      resolve(parent, args) {
        return _.find(books, {})
      }
    }
  }
})

A: const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: { displayall: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(books, { displayall: args.displayall })
      }
    }
    books:{
        type: new GraphQLList(BookType),
          resolve(parent, args) {
            return books
          }
        }
  }
})


Q: probability, 2 chips drawn have either same number or color I've viewed similar problems to this, but I'm not understanding the logic to the question and answers behind them.
There are 5 red chips (each numbered 1, 2, 3, 4, & 5), and 3 blue chips (each numbered 1, 2, 3). You draw two chips at random, and don't replace them after drawing each of the two chips.
What is the probability the two chips drawn have either the same number or same color?
Can you help me figure the correct answer as well as the logic of it?
Thanks in advance!

A: $\newcommand{\R}[1]{\color{red}{#1}}\newcommand{\B}[1]{\color{blue}{#1}}$ We shall consider the following:
$$\Omega = \{\R1,\R2,\R3,\R4,\R5,\B1,\B2,\B3\}$$
The number of ways to draw two coins from this is $\binom{|\Omega|}2 = \binom82 = 28$.
Let $A := \{(a,b) | \text{color}(a) = \text{color}(b)\}$. Then
$$A = \{ (\R1, \R2), \ldots, (\R4,\R5), (\B1, \B2), \ldots\}$$
$|A|$ is given by $\binom52 + \binom32 = 10 + 3 = 13$.
Now for $B:=\{(a,b) | \text{number}(a) = \text{number}(b)\}$.
$$B = \{(\R1, \B1), (\R2, \B2), (\R3, \B3)\}$$
$|B| = 3$ can be seen easily. Now $A\cap B = \emptyset$ from earlier considerations, so that Your total set of admissible combinations is $P = A\cup B$ and $|P| = |A| + |B| = 13 + 3 = 16$
Finally the probability is given by
$$p = \frac{|P|}{|\Omega|} = \frac{16}{28} = \frac47$$
Note that I use braces ($(,)$) for inner sets for improved readability.

A: If Red 5 is one of the two chosen tokens, there are seven possibilites for the other chip.  4 of them have the same color, 3 have neither the same color nor number.
If Red 5 is not one of the two tokens and Red 4 is, then there are 6 possibilities for choosing the other chip.  3 have the same color, and 3 have neither the same color nor number.
If neither Red 4 nor Red 5 are selected, then both tokens must be from Red 1 to 3 and Blue 1 to 3.  No matter which token is chosen first, 2 of the remaining 5 will share a color, 1 will share a number, and 2 will share neither a color nor a number.  Since there are $\binom{6}{2}$ ways to chose two tokens out of 6, $\frac{2}{5}\binom62 = \frac25 15 = 6$ will have neither rank nor color match, so $9$ will have one characteristic match.
Adding it all up, there are $7 + 6 + \binom{6}{2} = 28$ ways to choose 2 out of 8 tokens ($\binom{8}{2} = 28$ also), and $4 + 3 + 9 = 16$ will have a match, and $3 + 3 + 6 = 12$ will not.  So the probability that a characteristic will match between the tokens is $\frac{16}{28} = \frac47$.


Q: Enforce order of discord.js slash commands (using rest api) I am creating slash commands (without the slash builder), and when loading the slash commands, the order of which the options can be choosen from can be varied.
I want the user to have to specify the options in a set order, because each option depends on it.
I have figured out that if I set the option to required, it enforces the order by which its set in the configuration.
this.options = [{
        name: "first option",
        description: "first argument",
        type: 3,
        choices: [{
            // ...
        }],
        required: true
    },
    {
        name: "second option",
        description: "second argument",
        type: 3,
        choices: [{
            // ...
        }],
        required: true
    }
]

The code above would set the order of the options from 1 to 2 and so on.
this.options = [{
        name: "first option",
        description: "first argument",
        type: 3,
        choices: [{
            // ...
        }],
        required: false
    },
    {
        name: "second option",
        description: "second argument",
        type: 3,
        choices: [{
            // ...
        }],
        required: false
    }
]

Now, the order can be choosen freely however the user wants to.
Can I enforce the order even tho the options are not required?


Q: How to create a hash map in java script and send the hash map to java action class I have text boxes like which will have some values and i would like to create a hash map with no duplicates and send that hash map to action class.
    <input type="text" name="test1" value="test" />
    <input type="text" name="test2" value="test2" />

Like the above there will be N number of text boxes and create a hash map key as name of the text box and value as the value of the text box
would some one help me as how to do this please.


Q: Losing data in dictionary I have 2 lists that I am merging together like this, is there a way to merge without losing data because I have duplicates in the code?
new = dict(zip(sortedPrimes, a))

both sortedPrimes and 'a' are lists with 1062 elements when I use len(). However when I zip them together like this when I print len(new) I get 336. This hasn't happened before, where is the data going?
Rest of the code:
def rwh_primes(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

numbers = rwh_primes(10000)

a = [x for x in numbers if x > 1000]

final = []
sortedPrimes = []
for x in a:
    sortedPrimes.append(''.join(sorted(str(x))))

lisp = [x for n, x in enumerate(sortedPrimes) if x in sortedPrimes[:n]]
new = dict(zip(sortedPrimes, a))

A: print(len(set(sortedPrimes))) # Count of unique keys: 336

Dictionaries hash values to keys. Those key aren't duplicated. There's 336 unique items in sortedPrimes so there's 336 keys in new

A: You have a situation where one key is mapping to multiple values. In that case, one reasonable data structure is a dict of lists:
import collections

d = collections.defaultdict(list)
for v1, v2 in zip(sortedPrimes, a):
    d[v1].append(v2)

for k in sorted(d):
    print k, d[k]

# Output
0013 [3001]
0014 [4001]
0017 [7001]
0019 [1009, 9001]
0023 [2003]
0034 [4003]
0035 [5003]
0047 [4007]
0059 [5009]
0067 [6007]
0079 [9007]
0089 [8009]
0112 [1021, 1201, 2011]
0113 [1013, 1031, 1103, 1301, 3011]
0115 [1051, 5011, 5101]
etc. for all 336 keys ...


Q: Strategies for multithreaded singleton object in Rails I have a compelling use case where notifications happen in realtime at the server level. I would like to push these events out over a websocket using Rails' ActionCable. How Can I reliably maintain a long-lived singleton object to react to and push server-level events?

*

*I prototyped a Rails app using an object instantiated from a file in /app/lib that mixes in the Singleton module. Even with class caching, this was instantiated multiple times and occasionally garbage collected despite open sockets.

*Marking the event producer's initialize method private and writing a class-level instance method that checks Thread.main[:event_provider] for an instance works 95% in development, but I worry about what I don't know that I don't know about production. Very occasionally I get exceptions like "Expected x_y.rb to define constant XY" exceptions, which make me think there's a problem to this approach.

*The production server will ultimately serve a very small number of clients in an environment that demands 100% uptime. I can choose a server stack that makes sense.
I'm hoping someone with knowledge of Rack and/or ActionCable can comment on reliable ways to serve events to a Rails application from within the server.

A: As of now, the strategy I am undertaking is to instantiate a singleton object early in the boot process and then use it to maintain threads. Threadsafe practices are obviously needed for this.
The file application.rb defines MyApp::Application. At this point I declare an accessor my_thing_manager, require my_thing_manager and set self.my_thing_manager = MyThingManager.instance.
class MyThingManager
    def instance
        return Thread.main[:thing_manager] unless Thread.main[:thing_manager].nil?
        Thread.main[:thing_manager] = self.new
    end

    private

    def initialize
    end
end

This approach works in a single multithreaded process but does not work in a clustered production environment. For my requirements that is completely acceptable. For a multi-process app, one could utilize hooks in e.g. Puma after_worker_fork or Unicorn's after_fork to manage a subscription to something like Redis pubsub. This will be a requirement for an upcoming project so I expect to develop this strategy further.


Q: Illegal instance declaration / Overlapping instances Given class X and Y, what's the most idiomatic approach to creating instances of each other's class? e.g. -
instance (X a) => Y a where ...
instance (Y a) => X a where ...

I'd like to avoid extensions.  Also, I am aware that this could cause some nasty infinite recursion, so I'm open to a completely different approach to accomplish the same thing and stay relatively DRY.  Below gives some context as to the exact problem I am having -
data Dealer = Dealer Hand
data Player = Player Hand Cash

class HasPoints a where
    getPoints :: a -> Int

class (HasPoints a) => CardPlayer a where
    getHand :: a -> Hand

    viewHand :: a -> TurnIsComplete -> Hand

    hasBlackjack :: a -> Bool
    hasBlackjack player = getPoints player == 21 &&
                          (length . getCards . getHand) player == 2

    busts :: a -> Bool
    busts player = getPoints player > 21

I'd like to do this -
instance (CardPlayer a) => HasPoints a where
    getPoints = getPoints . getHand

But it seems I must do this -
instance HasPoints Dealer where
    getPoints = getPoints . getHand

instance HasPoints Player where
    getPoints = getPoints . getHand

EDIT
Seems my favorite approach is to keep the HasPoints typeclass and implement CardPlayer as data instead.
data CardPlayer = Dealer Hand | Player Hand Cash

instance HasPoints CardPlayer where
    getPoints = getPoints . getHand

getCash :: CardPlayer -> Maybe Cash
getHand :: CardPlayer -> Hand
viewHand :: CardPlayer -> TurnIsComplete -> Hand
hasBlackjack :: CardPlayer -> Bool
busts :: CardPlayer -> Bool

-- I wanted HasPoints to be polymorphic
-- so it could handle Card, Hand, and CardPlayer

instance HasPoints Hand where
    getPoints Hand { getCards = [] } = 0

    getPoints hand = if base > 21 && numAces > 0
                     then maximum $ filter (<=21) possibleScores
                     else base
      where base = sum $ map getPoints $ getCards hand
            numAces = length $ filter ((Ace==) . rank) $ getCards hand
            possibleScores = map ((base-) . (*10)) [1..numAces]

instance HasPoints Card where
    -- You get the point

A:
Given class X and Y, what's the most idiomatic approach to creating instances of each other's class?

The most idiomatic approach, given your example code, is to not use type classes in the first place when they're not doing anything useful. Consider the types of the class functions:
class HasPoints a where
    getPoints :: a -> Int

class (HasPoints a) => CardPlayer a where
    getHand :: a -> Hand
    viewHand :: a -> TurnIsComplete -> Hand
    hasBlackjack :: a -> Bool
    busts :: a -> Bool

What do they have in common? They all take exactly one value of the class parameter type as their first argument, so given such a value we can apply each function to it and get all the same information without needing to bother with a class constraint.
So if you want a nice, idiomatic DRY approach, consider this:
data CardPlayer a = CardPlayer
    { playerPoints :: Int
    , hand :: Hand
    , viewHand :: TurnIsComplete -> Hand
    , hasBlackjack :: Bool
    , busts :: Bool
    , player :: a
    }

data Dealer = Dealer
data Player = Player Cash

In this version, the types CardPlayer Player and CardPlayer Dealer are equivalent to the Player and Dealer types you had. The player record field here is used to get the data specialized to the kind of player, and functions that would have been polymorphic with a class constraint in yours can simply operate on values of type CardPlayer a.
Though perhaps it would make more sense for hasBlackjack and busts to be regular functions (like your default implementations), unless you really need to model players who are immune to the standard rules of Blackjack.
From this version, you can now define a HasPoints class alone if you have very different types that should be instances of it, though I'm skeptical of the utility of that, or you can apply the same transformation to get another layer:
data HasPoints a = HasPoints
    { points :: Int
    , pointOwner :: a
    }

However, this approach quickly becomes unwieldy the further you nest specializations like this.
I would suggest droping HasPoints entirely. It only has one function, which just extracts an Int, so any code that handles HasPoints instances generically might as well just use Ints and be done with it.

A: In general, it's impossible to declare all instances of a class to also be instances of another class without making type checking undecidable. So your proposed definition will only work with UndecidableInstances enabled:
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

instance (CardPlayer a) => HasPoints a where
    getPoints = getPoints . getHand

Although it's possible to go that route, I'd suggest refactoring the code as follows instead:
data Hand = ...

handPoints :: Hand -> Int
handPoints = ...

data Dealer = Dealer Hand
data Player = Player Hand Cash

class CardPlayer a where
  getHand :: a -> Hand
  ...

instance CardPlayer Dealer where ...
instance CardPlayer Player where ...

playerPoints :: (CardPlayer a) => a -> Int
playerPoints = handPoints . getHand


Q: Why should cocos2d-iphone users avoid using the @2x file extension? Cocos2d-iphone uses the -hd extension for Retina images (and other assets). The cocos2d Retina guide speaks only vaguely of "some incompatibilities" regarding @2x:

Apple uses the ”@2x” suffix, but cocos2d doesn't use that extension
  because of some incompatibilities. Instead, cocos2d has its own
  suffix: ”-hd”.
WARNING: It is NOT recommend to use the ”@2x” suffix. Apple treats
  those images in a special way which might cause bugs in your cocos2d
  application.

Great. I feel well informed.
Through a 2-year old bug report regarding @2x I got the link to a forum thread that supposedly explains the issues with @2x. However, it does not. The only hints I found in there is that there are iOS (4.0/4.1) bugs regarding @2x which I suppose are no longer relevant. It's possible that I might have missed some crucial aspect (there was some talk about caching or repeat loading issues) - the thread is very long after all.
I'd like to know what specific issues might a cocos2d developer encounter if (s)he is using the @2x suffix for images instead of -hd?
Please give concrete examples of things that might go or actually will be wrong.

A: It seems as if this has a historic background.
What makes using -hd graphics still worthwhile is that loading them doesn't rely on Apple functionality but is rather done in framework code. So -hd can be loaded for iPads in iPhone Simulator mode and make use of the higher resolution pictures in 2x mode.
Other than that I couldn't find any more reasons to not use @2x when I was looking into this a week ago.
In case you want all the details it is probably best to drop riq an email.

A: This seems to be the main reason from this link: http://www.cocos2d-iphone.org/forum/topic/12026
Specifically this post by riq:

I don't know if initWithContentsOfFile was fixed, but in 4.0 it was broken and it wasn't working with @2x, ~iphone extensions.
  imageNamed caches all the loaded files so it consumes much more memory than initWithContentsOfFile
  Also the @2x extension does something (I don't know exactly what) but it doesn't work OK with cocos2d.

Another good point: Back when the iPhone 4 was just released with the retina display, I am sure some users of Cocos2D were using an older version of it so when the user was using the retina display on a version of Cocos2D that didn't support it, things were twice as large as they should've been. Again this is now fixed to most unless you are using a VERY early version of Cocos2D.
Overview, so it seems that the main issue was with initWithContentsOfFile from iOS 4 but they have fixed this since because I use that exact API with Cocos2D 2.0-rc2 in my app and I do not have any issues whatsoever. I use all Apple specified extensions for images and everything works jolly good! :)


Q: Getting required width of an overflowing span in JS

  Lorem ipsum...

Hello interwebs,
I'm trying to get the width the innerPart would require to be fully displayed via JS.
Tried using document.getElementById("innerPart").width; but it is just returning null

A: Use document.getElementById("innerPart").offsetWidth
See this answer
If you wanted the width property it's off the style property. E.g. document.getElementById("innerPart").style.width
The difference being that offsetWidth is a computed property, it takes into account borders and padding whereas width doesn't. You may find that width is null and I'm assuming that is true if the width hasn't been specifically set by you.


Q: UITableView Transparent BackGround I got this code :
UIViewController *nextQuestionView = [[QuizzQuestionViewController alloc]init];
    nextQuestionView.view.backgroundColor=[UIColor colorWithRed:0.44 green:0.44 blue:0.41 alpha:1];
    [self.navigationController pushViewController:nextQuestionView animated:YES];
    NSLog(@"gotonextQuestion");
    [nextQuestionView newQuestion];
    [nextQuestionView release];

And i want to remove the black corner.
Thanks.


Q: Converting 12V capacitors from parallel to series: do they need to be rated for 250V? I have designed a DC-to-DC voltage multiplier. It works by first loading 21 capacitors in parallel with +12VDC and then switching them to series using my homemade 42 pole relay. The output would be about 250 volts.
The question is, should all the capacitors be rated for 250 volts?
Is the voltage through one capacitor 12 or 250V?

A: If the capacitors are close to the same value they need only be rated at somewhat more than 12V. It's common to do this with Cockroft-Walton voltage multipliers (you will be avoiding the series diode drops by using mechanical contacts).
If you have quite different values, then the voltage can distribute unevenly when the output discharges (the lower value capacitors would have more voltage across them).


Q: Correct way to pause a Python program I've been using the input function as a way to pause my scripts:
print("something")
wait = input("Press Enter to continue.")
print("something")

Is there a formal way to do this?

A: I have had a similar question and I was using signal:
import signal

def signal_handler(signal_number, frame):
    print "Proceed ..."

signal.signal(signal.SIGINT, signal_handler)
signal.pause()

So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.

A: print ("This is how you pause")

input()

A: I use the following for Python 2 and Python 3 to pause code execution until user presses Enter
import six

if six.PY2:
    raw_input("Press the <Enter> key to continue...")
else:
    input("Press the <Enter> key to continue...")

A: As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:
Python 3.x:
input('Press <ENTER> to continue')

Python 2.x:
raw_input('Press <ENTER> to continue')

For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on
Python 2.x) to prompt the user, rather than a time delay. Fast readers
won't want to wait for a delay, slow readers might want more time on
the delay, someone might be interrupted while reading it and want a
lot more time, etc. Also, if someone uses the program a lot, he/she
may become used to how it works and not need to even read the long
text. It's just friendlier to let the user control how long the block
of text is displayed for reading.

Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard :)

A: Very simple:
raw_input("Press Enter to continue ...")
print("Doing something...")

A: For Windows only, use:
import os
os.system("pause")

A: By this method, you can resume your program just by pressing any specified key you've specified that:
import keyboard
while True:
    key = keyboard.read_key()
    if key == 'space':  # You can put any key you like instead of 'space'
        break

The same method, but in another way:
import keyboard
while True:
    if keyboard.is_pressed('space'):  # The same. you can put any key you like instead of 'space'
        break

Note: you can install the keyboard module simply by writing this in you shell or cmd:
pip install keyboard

A: cross-platform way; works everywhere
import os, sys

if sys.platform == 'win32':
    os.system('pause')
else:
    input('Press any key to continue...')

A: It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5.5)    # Pause 5.5 seconds
print("something")

A: So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,
def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:
import os
import system

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

print("Think about what you ate for dinner last night...")
pause()

Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.
NOTE: For Python 3, you will need to use input as opposed to raw_input

A: I work with non-programmers who like a simple solution:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())

This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:
Paused. Press ^D (Ctrl+D) to continue.
>>>
The Python Debugger is also a good way to pause.
import pdb
pdb.set_trace() # Python 2

or
breakpoint() # Python 3

A: I assume you want to pause without input.
Use:
time.sleep(seconds)

A: I think I like this solution:
import getpass
getpass.getpass("Press Enter to Continue")

It hides whatever the user types in, which helps clarify that input is not used here.
But be mindful on the OS X platform. It displays a key which may be confusing.

Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?

A: user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke).
By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer.
import readchar
readchar.readkey()

A: I think that the best way to stop the execution is the time.sleep() function.
If you need to suspend the execution only in certain cases you can simply implement an if statement like this:
if somethinghappen:
    time.sleep(seconds)

You can leave the else branch empty.

A: For cross Python 2/3 compatibility, you can use input via the six library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )


Q: Flutter : /opt/..../FETCH_HEAD exists in filesystem Arch While I'm updating and installing some packages on Arch Linux:
sudo pacman -Syu && sudo pacman -S --needed \
webkit2gtk \
base-devel \
curl \
wget \...

I got following error:
error: failed to commit transaction (conflicting files)
flutter: /opt/flutter/.git/FETCH_HEAD exists in filesystem
Errors occurred, no packages were upgraded.

A: Fixed with sudo rm -rf /opt/flutter/.git/FETCH_HEAD


Q: Run a function in a seperate python thread (Python 3.8.3)
I am using two python threads right now, one that has a while True loop
import threading
def threadOne():
    while True:
        do(thing)
    print('loop ended!')
t1=threading.Thread(threadOne)
t1.start()

And another that checks for a ctrl+r input. When recieved, I need the second thread to tell the first thread to break from the while loop. Is there a way to do this?
Note that I cannot change the loop to 'while Break == False' as do(thing) waits for user input, but i need this to be interrupted.

A: The recommended way is to use threading.event (You can combine this with event.wait if you want to sleep in that thread too however as you are waiting for a user event, probably dont need that).
import threading

e = threading.Event()
def thread_one():
    while True:
        if e.is_set():
            break
        print("do something")
    print('loop ended!')

t1=threading.Thread(target=thread_one)
t1.start()
# and in other thread:
import time
time.sleep(0.0001)  # just to show thread_one keeps printing
                    # do something for little bit and then it break
e.set()

EDIT: To interrupt the thread while it's waiting for user input you can send SIGINT to that thread and and it will raise KeyboardInterrupt which you can then handle. Unfortunate limitation of python, including python3, is that signals to all threads are handled in the main thread so you need to wait for the user input in the main thread:
import threading
import sys
import os
import signal
import time

def thread_one():
    time.sleep(10)
    os.kill(os.getpid(), signal.SIGINT)

t1=threading.Thread(target=thread_one)
t1.start()

while True:
    try:
        print("waiting: ")
        sys.stdin.readline()
    except KeyboardInterrupt:
        break
print("loop ended")


Q: SEO Friendly URLs Rewrite Using Htaccess And Mod_Rewrite I have used below RewriteRule in .htacces file then it is working as /page/NDT:REBGEARPOSGM-8630342
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^page/([A-Za-z0-9\-:]+$)$ page.php?partid=$1
</IfModule>

But I want work as /page/NDT:REBGEARPOSGM-8630342.html. For this I have used below RewriteRule and it is giving error 404 .
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^page/([A-Za-z0-9\-:]+$)\.html page.php?partid=$1
</IfModule>

Any one please assist where I did wrong or any other way to do this.  Thanks in advance.

A: You have a misplaced $ anchor in your regex. Use this rule:
<IfModule mod_rewrite.c>

    Options -MultiViews
    RewriteEngine on
    RewriteRule ^page/([a-z0-9:-]+)\.html$ page.php?partid=$1 [L,QSA,NC]

</IfModule>


Q: Operands could not be broadcast together with shapes data = pd.read_csv('./Book1.csv')
# Read the edgelist of the Wiki Talk network
G = nx.from_pandas_edgelist(data, data.columns[0], data.columns[1])
G = G.subgraph(max(nx.connected_components(G), key=len))

ic_seed_set = np.random.choice(G.nodes(), ic_seed_set_size)
Determine the model parameter
ic_threshold = 0.4
g = Graph([[u,v] for (u,v) in G.edges])
def IC(g,S,ic_threshold,ic_num_steps):
"""
Input:  graph object, set of seed nodes, propagation probability
and the number of Monte-Carlo simulations
Output: average number of nodes influenced by the seed nodes
"""
# Loop over the Monte-Carlo Simulations
spread = []
for i in range(ic_num_steps):

    # Simulate propagation process
    new_active, A = S[:], S[:]
    for i in range(len(new_active)) :

        # For each newly active node, find its neighbors that become activated
        new_ones = []
        for node in new_active:

            # Determine neighbors that become infected
            np.random.seed(i)
            success = np.random.uniform(0,1,len(g.neighbors(node,mode="out"))) < ic_threshold
            new_ones += list(np.extract(success, g.neighbors(node,mode="out")))

        new_active = list(set(new_ones) - set(A))

        # Add newly activated nodes to the set of activated nodes
        A = A + new_active

    spread.append(len(A))

return(np.mean(spread))

modelpropagation =IC(g,ic_seed_set,ic_threshold,ic_num_steps)

i expected list of integer
but in this line >>>   A = A + new_active

<ipython-input-24-fc67faf2ae99> in IC(g, S, ic_threshold, ic_num_steps)
     61
     62             # Add newly activated nodes to the set of activated nodes
---> 63             A = A + new_active
     64
     65         spread.append(len(A))

ValueError: operands could not be broadcast together with shapes (5,) (492,)


Q: Limiting behavior of Kazdan-Warner equations It's a well known result by Kazdan and Warner that on a closed Riemannian manifold the pde:
\begin{align*}
\Delta f+ge^f=c
\end{align*}
has a unique solution for $g\geq 0,$ and $c$ a positive constant. So, we can replace $c$ by $c+t$ and for each $t\in(0,\infty)$ we would have a different solution for $f$. I am looking for the limiting behaviour of $f$ when we let $t\rightarrow\infty$. Any idea or reference is most welcome.


Q: reorder x-axis with heatmap in R I am used to using ggplot2, so I have only used fct_inorder() to reorder my axes. It should be Gate 0 - 3 then Full. How do you do this with a base function like heatmap? df and code below. Thank you!
Wizard_heatmap <- structure(list(Response = c("LIZARD", "LIZARD", "LIZARD", "NR",
                                              "NR", "WAITER", "WEEKEND", "WHALE", "WHEELCHAIR", "WHIP", "WHISKEY",
                                              "WHISTLE", "WHISTLE", "WHISTLE", "WIND", "WINDMILL", "WINDOW",
                                              "WINDOW", "WINTER", "WISDOM", "WISDOM", "WIZARD", "WIZARD", "WIZARD",
                                              "WIZARD", "WOMEN", "WOOD", "WOODCHIP"),
                                 Target = c("WIZARD","WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD",
                                            "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD",
                                            "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD",
                                            "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD"),
                                 Gate = c("Full", "Gate 2", "Gate 3", "Gate 0", "Gate 1",
                                          "Gate 0", "Gate 1", "Gate 0", "Gate 0", "Gate 0", "Gate 1",
                                          "Gate 0", "Gate 1", "Gate 2", "Gate 0", "Gate 0", "Gate 0",
                                          "Gate 1", "Gate 0", "Gate 1", "Gate 2", "Full", "Gate 1",
                                          "Gate 2", "Gate 3", "Gate 0", "Gate 0", "Gate 0"),
                                 n = c(1, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 7,
                                       1, 15, 1, 12, 14, 1, 1, 1)), row.names = c(NA, -28L), class = c("tbl_df", "tbl", "data.frame"))

heatmap(with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate)))))

A: I wonder if, given your data, you are not interested in the dendrogram and are just looking for a standard heatmap? If do, then perhaps using ggplot would give you the control you need?
m <- with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate))))

for(i in seq(nrow(Wizard_heatmap))) {
  m[Wizard_heatmap$Response[i], Wizard_heatmap$Gate[i]] <- Wizard_heatmap$n[i]
}

df <- setNames(as.data.frame(as.table(m)), c("Response", "Gate", "n"))

library(ggplot2)

ggplot(df, aes(Gate, Response, fill = n)) +
  geom_tile(color = "gray") +
  theme_minimal() +
  scale_fill_gradientn(colours = c("red4", "red", "orange", "yellow", "white"))


Q: Trying to compile xf86drm.h example On this page https://raw.githubusercontent.com/dvdhrm/docs/master/drm-howto/modeset.c someone has published an example on how to properly use the drm api.
I downloaded the source file compiled it with gcc -I/usr/include/drm/ modeset.h -o modeset, marked it as executeable chmod +x modeset and launched it ./modeset
Output:
michael@lord:~/Documents/cpp/modeset$ ./modeset
./modeset: line 1: $'gpchC014\310\b\032\231\253\267+\277\331\022\225I\021': command not found
./modeset: line 17: syntax error near unexpected token `$'\375?\250\001\177\001\001''
./modeset: line 17: `ø?¨
                              ø?¨
                                  ø?¨ø?¨0ø?¨2ø?¨4ø?¨6ø?¨8ø?¨9ø?¨:ø?¨;ø?¨<ø?¨=ø?¨>ø?¨Pø?¨Rø?¨Tø?¨Vø?¨Xø?¨Zø?¨\ø?¨^ø?¨`ø?¨bø?¨dø?¨fø?¨hø?¨jø?¨lø?¨nø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ ø?¨¢ø?¨¤ø?¨¦ø?¨¨ø?¨ªø?¨¬ø?¨®ø?¨°ø?¨±ø?¨²ø?¨³ø?¨´ø?¨µø?¨¶ø?¨·ø?¨¸ø?¨¹ø?¨ºø?¨»ø?¨¼ø?¨½ø?¨¾ø?¨¿ø?¨ðø?¨òø?¨ôø?¨öø?¨øø?¨úø?¨üø?¨þø?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨Aù?¨Cù?¨Eù?¨Gù?¨Iù?¨Kù?¨Mù?¨Où?¨aù?¨cù?¨eù?¨gù?¨iù?¨kù?¨mù?¨où?¨qù?¨sù?¨uù?¨wù?¨yù?¨{ù?¨}ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨Áù?¨Ãù?¨Åù?¨Çù?¨Éù?¨Ëù?¨Íù?¨Ïù?¨Ñù?¨Óù?¨Õù?¨×ù?¨Ùù?¨Ûù?¨Ýù?¨ßù?¨ñù?¨óù?¨õù?¨÷ù?¨ùù?¨ûù?¨ýù?¨ÿù?¨ú?¨ú?¨ú?¨ú?¨   ú?¨
ú?¨ú?¨1ú?¨3ú?¨5ú?¨7ú?¨9ú?¨;ú?¨=ú?¨?ú?¨Qú?¨Sú?¨Uú?¨Wú?¨Yú?¨[ú?¨]ú?¨_ú?¨qú?¨sú?¨uú?¨wú?¨yú?¨{ú?¨}ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨¡ú?¨¢ú?¨£ú?¨¤ú?¨¦ú?¨¨ú?¨ªú?¨¬ú?¨®ú?¨Àú?¨Âú?¨Äú?¨Æú?¨Èú?¨Êú?¨Ìú?¨Îú?¨ðú?¨òú?¨ôú?¨öú?¨øú?¨úú?¨üú?¨þú?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨ û?¨"û?¨$û?¨&û?¨(û?¨*û?¨,û?¨.û?¨Pû?¨Rû?¨Tû?¨Vû?¨Xû?¨Zû?¨\û?¨^û?¨`û?¨bû?¨dû?¨fû?¨hû?¨jû?¨lû?¨nû?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨Ðû?¨Òû?¨Ôû?¨Öû?¨Øû?¨Úû?¨Üû?¨Þû?¨àû?¨âû?¨äû?¨æû?¨èû?¨êû?¨ìû?¨îû?¨ðû?¨òû?¨ôû?¨öû?¨øû?¨úû?¨üû?¨þû?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨Pü?¨Rü?¨Tü?¨Vü?¨Xü?¨Zü?¨\ü?¨^ü?¨pü?¨rü?¨tü?¨vü?¨xü?¨zü?¨|ü?¨~ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨°ü?¨²ü?¨´ü?¨¶ü?¨¸ü?¨ºü?¨¼ü?¨½ü?¨¾ü?¨¿ü?¨Ðü?¨Ñü?¨Òü?¨Óü?¨Ôü?¨Õü?¨Öü?¨×ü?¨Øü?¨Ùü?¨Úü?¨Ûü?¨Üü?¨Ýü?¨Þü?¨ßü?¨àü?¨áü?¨âü?¨ãü?¨äü?¨æü?¨èü?¨éü?¨ëü?¨ìü?¨íü?¨îü?¨ïü?¨ ý?¨"ý?¨$ý?¨%ý?¨&ý?¨'ý?¨(ý?¨)ý?¨*ý?¨+ý?¨,ý?¨-ý?¨.ý?¨/ý?¨@ý?¨Aý?¨Bý?¨Dý?¨Fý?¨Gý?¨Hý?¨Iý?¨Jý?¨Lý?¨Ný?¨pý?¨rý?¨tý?¨vý?¨xý?¨yý?¨zý?¨{ý?¨|ý?¨~ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨¡ý?¨£ý?¨¥ý?¨§ý?¨©ý?¨«ý?¨¬ý?¨ý?¨®ý?¨Àý?¨Âý?¨Äý?¨Æý?¨Èý?¨Êý?¨Ìý?¨Îý?¨ðý?¨òý?¨ôý?¨öý?¨÷ý?¨øý?¨ùý?¨úý?¨ûý?¨üý?¨ýý?¨ÿý?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨?¨þ?¨þ?¨þ?¨ þ?¨"þ?¨#þ?¨$þ?¨%þ?¨&þ?¨(þ?¨*þ?¨+þ?¨,þ?¨-þ?¨.þ?¨/þ?¨@þ?¨Aþ?¨Bþ?¨Cþ?¨Eþ?¨ß@¨@¨@¨@¨@¨@¨@¨@¨@¨@¨Þ@¨ @¨Gþ?¨Hþ?¨Jþ?¨Lþ?¨Nþ?¨`þ?¨bþ?¨dþ?¨fþ?¨hþ?¨jþ?¨lþ?¨nþ?¨ þ?¨¢þ?¨¤þ?¨¦þ?¨¨þ?¨ªþ?¨¬þ?¨þ?¨®þ?¨¯þ?¨'
^[[?1;2c^[[?1;2c

I do not understand this low level framebuffer example so I am a bit lost right now. The web is also not revealing any docs. Some basic hints about what's happening here would be enough.
I am also using xorg server.

A: The file you are invoking seems not to be a valid ELF executable, bash tries to process it as a bash script and fails. You can check for sure by using file command, e.g. file modeset.
Check for the errors during your GCC build. Note that you try to compile modeset.h, not modeset.c.


Q: PostgreSQL Database Performance issue I have performance issue with PostgreSQL Database. These are excerpted related tables:
CREATE TABLE public.patient (
    patient_id serial4 NOT NULL,
    user_id int4 NULL,
    cid varchar(13) NULL,
    firstname varchar(100) NULL,
    lastname varchar(100) NULL,
    is_active bool NULL,
    CONSTRAINT patient_pkey PRIMARY KEY (patient_id),
    CONSTRAINT unique_cid UNIQUE (cid)
);
CREATE INDEX patient_is_active_idx ON public.patient USING btree (is_active);

CREATE TABLE public.pat_consent_in (
    consent_in_id int4 NOT NULL DEFAULT nextval('pat_consent_in_consentin_id_seq'::regclass),
    patient_id int4 NULL,
    consent_date timestamp NULL,
    mdp_id int4 NULL,
    CONSTRAINT pat_consent_in_pkey PRIMARY KEY (consent_in_id),
    CONSTRAINT unique_patient_id_mdp_id UNIQUE (patient_id, mdp_id)
);
CREATE INDEX pat_consent_in_consent_lastupdate_date_idx ON public.pat_consent_in USING btree (consent_lastupdate_date);
CREATE INDEX pat_consent_in_mdp_id_idx ON public.pat_consent_in USING btree (mdp_id);
CREATE INDEX pat_consent_in_patient_id_idx ON public.pat_consent_in USING btree (patient_id);

-- public.pat_consent_in foreign keys

ALTER TABLE public.pat_consent_in ADD CONSTRAINT pat_consent_in_patient_id_fkey FOREIGN KEY (patient_id) REFERENCES public.patient(patient_id);

These are the sizes of tables:

*

*patient

*

*pat_consent_in

I face the problem of performance that it takes like forever to execute the paging query:
SELECT
    pat_consent_in.consent_in_id,
    patient.cid,
    pat_consent_in.is_active,
    pat_consent_in.consent_date,
    pat_consent_in.consent_lastupdate_date
FROM pat_consent_in
JOIN patient
    ON patient.patient_id = pat_consent_in.patient_id
WHERE pat_consent_in.mdp_id = :mdp_id_1
    AND patient.is_active
ORDER BY pat_consent_in.consent_in_id ASC
LIMIT :param_1 OFFSET :param_2

What should I do for the sake of performance improvement? Any suggestions are welcome.
EDIT
This is the execution plan result of statement:
EXPLAIN ANALYZE SELECT
    pat_consent_in.consent_in_id,
    patient.cid,
    pat_consent_in.is_active,
    pat_consent_in.consent_date,
    pat_consent_in.consent_lastupdate_date
FROM pat_consent_in
JOIN patient
    ON patient.patient_id = pat_consent_in.patient_id
WHERE pat_consent_in.mdp_id = 1200
    AND patient.is_active
ORDER BY pat_consent_in.consent_in_id ASC
LIMIT 10 OFFSET 100000;

QUERY PLAN                                                                                |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Limit  (cost=381243.33..381244.50 rows=10 width=34) (actual time=274958.456..275089.239 rows=10 loops=1)                                                               |
  ->  Gather Merge  (cost=369575.85..419418.63 rows=427194 width=34) (actual time=274901.889..275082.974 rows=100010 loops=1)                                          |
        Workers Planned: 2                                                                                |
        Workers Launched: 2                                                                                |
        ->  Sort  (cost=368575.83..369109.82 rows=213597 width=34) (actual time=274880.599..274891.061 rows=33834 loops=3)                                             |
              Sort Key: pat_consent_in.consent_in_id                                                                                |
              Sort Method: external merge  Disk: 8520kB                                                                                |
              Worker 0:  Sort Method: external merge  Disk: 8336kB                                                                                |
              Worker 1:  Sort Method: external merge  Disk: 8384kB                                                                                |
              ->  Nested Loop  (cost=0.57..342824.75 rows=213597 width=34) (actual time=3.990..274169.723 rows=171417 loops=3)                                         |
                    ->  Parallel Seq Scan on patient  (cost=0.00..25071.72 rows=214272 width=17) (actual time=0.092..523.227 rows=171417 loops=3)                      |
                          Filter: is_active                                                                                |
                          Rows Removed by Filter: 1                                                                                |
                    ->  Index Scan using unique_patient_id_mdp_id on pat_consent_in  (cost=0.57..16.05 rows=17 width=25) (actual time=1.591..1.591 rows=1 loops=514250)|
                          Index Cond: ((patient_id = patient.patient_id) AND (mdp_id = 1200))                                                                          |
Planning Time: 1.798 ms                                                                                |
Execution Time: 275093.673 ms                                                                                |


Q: How to set-up a favicon? I am trying to do a very simple preliminary exercise to setting up a website which is creating a favicon.
This is the code I am using:
<!DOCTYPE html >
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</head>
</html>

But it is not working - can anyone please assist?
I've saved the file favicon.ico on the same level as my html file (on a subdirectory).
Many thanks

A: With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming.
You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device.
You should have a look at
http://realfavicongenerator.net/
to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time).
One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) :
<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="mstile-144x144.png">
<meta name="msapplication-config" content="browserconfig.xml">

In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines:
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">

A: Below given some information about fav Icon
What Is FavIcon?
   FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure.

How It Works ?
   Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference.
               <link rel="icon" href="favicon.ico" type="image/ico"/>
               <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>

Some browser expect one (rel="icon") Some other browser expect other  rel="shortcut icon"
   Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.
   We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages

A: you could take a look at the w3 how to, i think you will find it helpful
your link tag attribute should be rel="icon"

A: I use this on my site and it works great.
<link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"/>

A: There is a very simple method to set a favicon, which had been around for a long time AFAIK.
Place the favicon.ico file in the default location.
i.e
http://www.yoursite.com/favicon.ico

This works in almost every browser without a <link> tag.
However, this works only if it is an *.ico file. PNGs and other formats still have to be linked with a <link> tag

A: <!DOCTYPE html
      PUBLIC "-//W3C//DTD HTML 4.01//EN"
      "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
      type="image/png"
      href="http://example.com/myicon.png">
</head>
<body>
...
</body>
</html>

rel="shortcut icon" should be rel="icon"
Source: W3C

A: From experience of my favicon.ico not appearing, I am sharing my experience. You can't get it to show until you put your website on a host, therefore, try put it on a localhost using XAMPP - http://www.apachefriends.org/en/xampp.html. This is how the favicon appears and like others recommended, change:
rel="shortcut icon"
to
rel="icon"
Also this way .png favicons can be used for slickness.

A: <head>
    <link rel="shortcut icon" href="favicon.ico">
</head>

A: In my site, I use this:
<!-- for FF, Chrome, Opera -->
<link rel="icon" type="image/png" href="/assets/favicons/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-32x32.png" sizes="32x32">

<!-- for IE -->
<link rel="icon" type="image/x-icon" href="/assets/favicons/favicon.ico" >
<link rel="shortcut icon" type="image/x-icon" href="/assets/favicons/favicon.ico"/>

To simplify your life, use this favicons generator http://realfavicongenerator.net

A: This method is recommended
<link rel="icon"
  type="image/png"
  href="/somewhere/myicon.png" />

A: Try put this in the head of the document:
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>

A: I use this https://realfavicongenerator.net/ to generate all the possible favicons scenarios and it is free.


Q: Google Sheets SUMIFS where multiple criteria is returning 0 I am struggling to workout the correct Google Sheets formula to achieve the following.
In the sheet Profile below, column Purchased_Classes, I want to SUMIF the Qty in sheet Purchased_Completed, Where the Email matches and Item contains the text "Class"
I have tried this but the results is returning 0
Here is a link to a sample google sheet.
={"Purchased_Classes";ARRAYFORMULA(IF(ISBLANK(A2:A),"",SUMIFS(Purchases_Completed!H2:H,Purchases_Completed!B2:B,A2:A,ISNUMBER(SEARCH("Class",Purchases_Completed!C2:C)), TRUE)))}

.
Profile

Purchases_Completed

A: You could try and create an empty sheet with the following formula:
=QUERY(Purchases_Completed!A2:H, "SELECT B, SUM(H) WHERE C LIKE '%Class%' GROUP BY B LABEL B 'Email', SUM(H) 'Purchased_Classes'")

This formula uses QUERY and it calculates the sum of your items which contain the 'Class' keyword for each user.
Here is the result using the query:

You can learn more about the Google Query Language here.


Q: Optimal Control Problem with Fraction Objective $\mu$ and $\lambda$ are two positive constants and $\mu > \lambda$. $c$ and $b$ are two positive constants and $c < b$. How to solve the following optimization problem?
\begin{align}
\max_{T\ge 0, H_t} & \, \frac{W_0}{M_0} \\
s.t. & \, \frac{dW_t}{dt} = \mu W_t - \mu H_t, H_t \ge W_t + c, W_T = 0. \\
     & \frac{dM_t}{dt} = \lambda M_t - \lambda H_t, H_t \ge M_t + b, M_T = 0.
\end{align}

A: Using a state space formulation with the state vector, $x_t$, as $\begin{bmatrix} W_t \\ M_t \end{bmatrix}$ and $H_t$ as the input, $u_t$,
$$\begin{bmatrix}
\dot{W_t} \\
\dot{M_t} \\
\end{bmatrix} = \begin{bmatrix} \mu & 0 \\ 0 & \lambda \end{bmatrix} \begin{bmatrix} W_t \\ M_t \end{bmatrix} + \begin{bmatrix} -\mu \\ -\lambda \end{bmatrix} H_t \\
\dot{x}_t = Ax_t + Bu_t$$
Taking its Laplace transform,
$$sX(s) - x_0 = AX(s) + BU(s) \\
X(s)(sI - A) = BU(s) + x_0 \\
X(s) = (sI - A)^{-1}(BU(s) + x_0) \\
x_t = \mathcal{L}^{-1}[(sI-A)^{-1}(BU(s) + x_0)] \\
\begin{bmatrix} W_t \\ M_t \end{bmatrix} =  \begin{bmatrix} -\mu e^{\mu t}* H_t + e^{\mu t}W_0 \\ -\lambda e^{\lambda t}*H_t + e^{\lambda t}M_0
\end{bmatrix}$$
A little algebra gives us
$$W_0 = (W_t  + \mu e^{\mu t} * H_t )e^{-\mu t}\\
M_0 = (M_t + \lambda e^{\lambda t} * H_t )e^{-\lambda t}
$$
Using $W_T = M_T = 0$, we get
$$W_0 = (\mu e^{\mu T} * H_T) e^{-\mu T} \\
M_0 = (\lambda e^{\lambda T} * H_T) e^{-\lambda T}$$
Since $e^{\mu T}, e^{\lambda T}$ and $H_T$ are constants for a particular $T$, their convolution w.r.t time yields $te^{\mu T}H_T $ and $te^{\lambda t}H_T $.
Therefore, the objective function becomes $\frac{W_0}{M_0} = \frac{\mu}{\lambda}$, which is independent of $T, H_t$.


Q: How to properly manage objects when using StreamWriter/Reader with TcpClient? I'm developing software that communicates with external hardware via ethernet (TCP), and I'm experiencing difficulties regarding the object management (StreamWriter/-Reader and TcpClient). There will be frequent/continual communication between the computer and the hardware, which includes various commands.
My questions are:

*

*When using TcpClient - does the connection/stream close or otherwise "reset" upon creating a new instance of TcpClient, for use in various classes - communicating with the same device? Or does it not matter unless I explicitly say .Close()?

*How do I use StreamWriter/-Reader properly when two whole classes use both objects? Global declaration, or declarations for every method?

*How does StreamReader.ReadLine() work? I have a peculiar case where it returns an "old" message, rather than the slightly newer it should. How can I properly use StreamReader such that each command will get their respective replies?


Q: Logitech wireless keyboard won't type anything I have a Logitech K800 wireless keyboard and Performance MX mouse running off of the same Unifying Receiver on Windows 10. All of a sudden, the keyboard doesn't type anything.  The function keys work (I can mute, change volume, etc), but I can't input any numbers or letters.
The mouse still works just fine. The keyboard pairs correctly using the Unifying software and when I press a key on it, the icon lights up that the computer received input, but nothing happens.
I tried using the keyboard on another computer and it works just fine, so it must be a Windows issue. Strangely enough, my spare Mac corded keyboard works just fine (and that's what I'm using to type this)...
Searching for this issue and trying the few suggestions doesn't yield any success. Many recommend updating the device driver from the Device Manager, but the only keyboard listed is the corded Mac keyboard. Plugging the Unifying Receiver into different USB ports also doesn't change anything, nor does simply rebooting the machine.
What could possibly be causing this?

A: I found a solution that worked for me. Go to control panel - ease of access - make keyboard easer to use, then turn off "turn on filter keys"

A: For others with this problem, changing the Filter Keys option didn't make the keyboard work for myself.
However, after getting the keyboard to a state where the Function keys would work (such as muting the sound and so on) I restarted my computer with everything connected to it.  After the restart, the keyboard worked as expected

A:
"I found a solution that worked for me. Go to control panel - ease of access - make keyboard easer to use, then turn off "turn on filter keys"

I had the exact opposite be my solution. After uninstalling/reinstalling the software and turning off filter keys, it ended up working for me.

A: I had the same problem with my K800. It was paired fine, but I took my laptop home from work and paired it with a different mouse and when I came back to work the keyboard wouldn't work. The mouse worked fine and the keyboard would pair but not type anything. This was fixed by changing the USB port the Unifying Receiver was plugged into.

A: I had the same problem with a K750 and Performance MX: mouse worked fine, keyboard would seem to pair but no characters would make it to the computer.  I tried the Filter Keys solution recommended here.  No joy.
Finally, I unpaired the mouse and paired the keyboard.  The keyboard started working.  Then I tried to re-pair the mouse and it initially exhibited the same bad behavior that the keyboard had: it would pair but no mouse activity was getting to the computer.
Leaving the keyboard paired I exited and restarted the Unify software and tried to pair the mouse again from the Advanced screen and it immediately paired and started working.  Now everything is good again.

A: Had the exact same problem with my K750. Seemed to be paired fine, and all the function keys were working, but nothing else.
Looks like this is a Windows issue. I suspect that I had something sitting on a keyboard key, and Windows automatically started to filter all that input. I tried unpairing and repairing with no success, but toggling the Windows Keyboard filter worked like a charm.

A: Logitech MK700/MK710 Wireless Keyboard. Detected, paired, wouldn't type.

*

*Uninstalled the "Logitech G Hub" application,

*Used "Logitech Unifying Software" to detect the keyboard again.

Typing this answer on it right now.
What gave it away:

*

*Logitech Unifying Software > Advanced View > Pair A New Device. The keyboard would be added briefly, then disappear again.

*Windows Device Manager > Keyboards > HID Keyboard Device > Properties > Location. Would display "Logitech G Hub Virtual Device".

With Logitech G Hub uninstalled, Logitech Unifying Software finally added the keyboard permanently and Windows Device Manager now displays a different Location: "Logitech USB Input Device".

A: I fixed this issue by taking the following steps:

*

*I uninstalled the keyboard from the devices under Device Manager

*I rebooted

and the keyboard was reinstalled with the same driver.
Now it is typing fine.


Q: Display more than 5 messages in TileUpdater I use in my application ScheduledTileNotifications and push 10 until 20 messages in the TileUpdateManager. But on the metro there are only 5 messages active. What can I do to display more than 5 notifications in the metro-Tile?
string tileXmlString = "<tile>"
       + "<visual>"
       + "<binding template='TileWideSmallImageAndText03' branding='name'>"
       + "<image id='1' src='ms-appx:///Assets/icons/cube_for_kachel.png'/>"
       + "<text id='1'>" + longSubject + "\n" + message.title + "</text>"
       + "</binding>"
       + "<binding template='TileSquareText04' branding='name'>"
       + "<text id='1'>" + shortSubject + "\n" + message.title + "</text>"
       + "</binding>"
       + "</visual>"
       + "</tile>";

XmlDocument tileXml = new XmlDocument();
tileXml.LoadXml(tileXmlString);
ScheduledTileNotification sceduleNotification = new ScheduledTileNotification(tileXml, DateTime.Now.AddSeconds(15));
TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
TileUpdateManager.CreateTileUpdaterForApplication().AddToSchedule(sceduleNotification);

When I set the EnableNotificationQueue to true, five of my notification run in a circle. When I set it to false, my notification don´t run in a circle. But I have 10 until 20 Notifications, which should run in a circle. Do you think it is possible.
When I use the AddToSchedule method an push 10 Notifications, each notification will show for one time.

A: The problem is related to the use of the EnableNotificationQueue method. In fact, as you can read at http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.notifications.tileupdater.enablenotificationqueue:

When queuing is enabled, a maximum of five tile notifications can
  automatically cycle on the tile.

Try to pass false to this method.
According to the documentation, you can schedule up to 4096 notifications. Reref to http://hansstan.wordpress.com/2012/09/02/windows-8-advanced-tile-badge-topics/ for a working example.


Q: prevent jsTree from expanding the nodes after you select them programmatically Is there a way to select a node without expanding nodes?  Every time I call the method to select a node, it will call the changed.jstree event and expand the nodes.  I want to select a node without expanding the nodes.
$('#jstree').jstree(true).select_node('info');

$('#jstree').on("changed.jstree", function (e, data) {

});

UPDATE:
I also tried the below method to select a node and it still expanded the nodes:
 $('#jstree').jstree().select_node('info', false,true)

A: I figured it out.  You call the below method to check the default options and the boolean below to true to set the prevent_open.
$('#jstree').on('ready.jstree', function (e, data) {
data.instance.select_node(['info'], false, true);
});

 //$('#jstree').jstree().select_node('info', false,true)


Q: How to paste source code to vim without error format? When I copy a python code, and paste to vim. the indents are all error.
but I paste into emacs or gedit, it is right.
that is difficult to describle, let's see the screenshot.
Notice:the blue and yellow line is just use the "indent guides plugin".

This is the source code example:
import threading
import time
class timer(threading.Thread): #The timer class is derived from the class threading.Thread
    def __init__(self, num, interval):
        threading.Thread.__init__(self)
        self.thread_num = num
        self.interval = interval
        self.thread_stop = False

    def run(self): #Overwrite run() method, put what you want the thread do here
        while not self.thread_stop:
            print 'Thread Object(%d), Time:%s/n' %(self.thread_num, time.ctime())
            time.sleep(self.interval)
    def stop(self):
        self.thread_stop = True

def test():
    thread1 = timer(1, 1)
    thread2 = timer(2, 2)
    thread1.start()
    thread2.start()
    time.sleep(10)
    thread1.stop()
    thread2.stop()
    return

if __name__ == '__main__':
    test()

A: Automatic indenting kicked in.
The easiest way to disable it is: :set paste

:help paste

'paste'                 boolean (default off)
                        global
                        {not in Vi}
    Put Vim in Paste mode.  This is useful if you want to cut or copy
    some text from one window and paste it in Vim.  This will avoid
    unexpected effects.
    Setting this option is useful when using Vim in a terminal, where Vim
    cannot distinguish between typed text and pasted text.  In the GUI, Vim
    knows about pasting and will mostly do the right thing without 'paste'
    being set.  The same is true for a terminal where Vim handles the
    mouse clicks itself.

A: Karoly's answer is correct regarding the paste option.
You can then add a mapping in your .vimrc to quickly enable/disable 'paste' option:
For example, I use
set pastetoggle=<F10>

A: You can also let vim handle the situation automatically for you.
With the following in your ~\.vimrc
let &t_SI .= "\<Esc>[?2004h"
let &t_EI .= "\<Esc>[?2004l"

inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()

function! XTermPasteBegin()
  set pastetoggle=<Esc>[201~
  set paste
  return ""
endfunction

you can paste freely without worrying about the auto-indentions.
If you work in tmux, then you have to write instead the following
function! WrapForTmux(s)
  if !exists('$TMUX')
    return a:s
  endif

  let tmux_start = "\<Esc>Ptmux;"
  let tmux_end = "\<Esc>\\"

  return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
endfunction

let &t_SI .= WrapForTmux("\<Esc>[?2004h")
let &t_EI .= WrapForTmux("\<Esc>[?2004l")

function! XTermPasteBegin()
  set pastetoggle=<Esc>[201~
  set paste
  return ""
endfunction

inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()

The source is Coderwall if you would like to read more.


Q: What's the best way to manage multiple dependent projects in Git or Mercurial? I have a dozen Java projects that depend on each other, and I frequently make changes that cross-cut all of them. However, many of the projects are libraries that could be used independently of each other as well.
Right now I use mercurial subrepos, which works well except that very few third-party tools support it - it's hard to set up code review tools, continuous integration, etc.
What's the best way to address this situation? Split everything into separate projects and build separate JARs? Migrate to git and use git subrepositories? Check everything in to a single repo and accept that I have to check out everything to use anything? Something else?

A: I would say the best way to do it would be to cut your dependencies so that they can reference as external jars. This way when you make potentially breaking changes you don't necessarily have to fix the affected areas straight away. Since they depend on a previously built jar it allows you to properly isolate your coding. If you use something like Maven to manage your dependencies you will also benefit from the ability to more easily keep track of the different versions of your jars.

A: If the subprojects are sufficiently autonomous, I would advise setting them up as separate maven projects with separate VCS repos.
This will give you the modularity you need paired with a working dependency management.