text:
Q: Trying to replace "x" with a Remove text on Woocommerce cart I am using WordMart theme and Woocommerce and I am trying to change the X to remove an item from the cart into the word Remove or maybe a fontawesome Garbage icon. Everything I try does not work
I have tried doing it via content in CSS and changing the × in the Woocommerce PHP code, with no luck.

<?php

echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(

'×',

esc_url( wc_get_cart_remove_url( $cart_item_key ) ),

__( 'Remove this item', 'woocommerce' ),

esc_attr( $product_id ),

esc_attr( $_product->get_sku() )

), $cart_item_key );
?>

I just expect for the X to be the word Remove in the simplest form, the not simple form would be a garbage icon.

A: You can consider the following CSS to replace the x with any content you want:
.woocommerce-cart a.remove {
   visibility:hidden!important; /*hide everything*/
   width:auto!important; /*make sure to have the need width for "remove" */
}

.woocommerce-cart a.remove:before {
   content: "Remove";
   visibility:visible;
}


text:
Q: Shopify does not redirect to admin page after installation I'm currently building a private app for Shopify. I've successfully passed the authorization step and get an appropriate response for it.
However, unlike other apps that I've seen, I'm not redirected to the Shopify's admin panel followed by my response page in the frame.
Instead, the redirection happens directly to my ngrok-generated address.

A: If you'd like to load your app within the Shopify admin then you can implement the Embedded App SDK.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Model count = null I'm rewriting this question:
I have 2 models.  Entry and Topic.
public class Entry
{
    public int EntryId { get; set; }
    public int UserId { get; set; }
    public int TopicId { get; set; }

    public String EntryQuestion { get; set; }
    public String EntryAnswer { get; set; }
    public int EntryReview { get; set; }
    public String QuestionValidationURL { get; set; }

    public virtual ICollection<Topic> TopicList { get; set; }
}

public class Topic
{
    public int TopicId { get; set; }
    public String TopicName { get; set; }
}

I followed an example on ASP.Net/MVC to set up my models this way.
What I would like to do is for every entry item I have a TopicId, but then I'd like to convert that to a TopicName by accessing my TopicList.
My question is, how do I load TopicList?
In the examples I'm following I'm seeing something about LazyLoading and EagerLoading, but it doesn't seem to be working.
I tried doing the following from my Entry controller:
    db.Entries.Include(x => x.TopicList).Load();

But that still gives me a TopicList of 0 (which is better than null)
How can I do this?
In my view I'm binding to the Entries like this:
@model IEnumerable<projectInterview.Models.Entry>

I would like to access the TopicList here:
@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.TopicId)

        ...

I'd like to use the TopicId in this loop and display the TopicName  that is part of the object in the collection.

A: I'm assuming you're following an Entity Framework example. You're trying to create a one-to-many relationship, as far as I can tell, although I'm unsure about which end is which.
In the general case, to establish a one-to-many relationship, you have to do something like this:
public class One
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<Many> Many { get; set; }
}

public class Many
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("One")]
    public int OneId { get; set; }
    public virtual One One { get; set; }
}

If what you're trying to do is have one Entry relating to many Topic objects, then you're almost there but you're lacking something.
For the ICollection<Topic> to actually contain anything, the (many) Topic objects need to have a foreign key to the (one) Entry. (It also doesn't hurt to explicitly mark the primary key on both sides, rather than relying on the EF conventions.)
public class Topic
{
    [Key]
    public int TopicId { get; set; }
    public String TopicName { get; set; }

    [ForeignKey("Entry")]
    public int EntryId { get; set; }
    public virtual Entry Entry { get; set; }
}

public class Entry
{
    [Key]
    public int EntryId { get; set; }

    public int UserId { get; set; }
    public int TopicId { get; set; }

    public String EntryQuestion { get; set; }
    public String EntryAnswer { get; set; }
    public int EntryReview { get; set; }
    public String QuestionValidationURL { get; set; }

    public virtual ICollection<Topic> TopicList { get; set; }
}

Now TopicList should be an actual and populated collection, without the need to do an Include.

If, on the other hand, you want one Topic relating to many Entry objects, then you have it a little backwards. The correct way would be:
public class Topic
{
    [Key]
    public int TopicId { get; set; }

    public String TopicName { get; set; }

    public virtual ICollection <Entry> Entries { get; set; }
}

public class Entry
{
    [Key]
    public int EntryId { get; set; }

    public int UserId { get; set; }

    public String EntryQuestion { get; set; }
    public String EntryAnswer { get; set; }
    public int EntryReview { get; set; }
    public String QuestionValidationURL { get; set; }

    [ForeignKey("Topic")]
    public int TopicId { get; set; }
    public virtual Topic Topic { get; set; }
}

In this case, you may or may not use db.Entries.Include(x => x.Topic) depending on whether you want them loaded all at once or one-by-one on demand. Regardless of what you choose, the following expression should return the proper value:
myEntry.Topic.TopicName

A: If I understand you correctly you have added the list of Topics to the Entry just to get the name of the topic when displaying the entry.  The best way to do this is to actually have a Topic property in your entry model. So your model would look like this:
public class Entry
{
    public int EntryId { get; set; }
    public int UserId { get; set; }
    public int TopicId { get; set; }
    public String EntryQuestion { get; set; }
    public String EntryAnswer { get; set; }
    public int EntryReview { get; set; }
    public String QuestionValidationURL { get; set; }
    //Change this.....
    public virtual Topic Topic { get; set; }
}

Then in your view you would use (assuming the Model is an IEnumerable):
@foreach (var item in Model) {

        @Html.DisplayFor(modelItem => modelItem.Topic.TopicName )

    ...

This link has a great example of how to do this:
http://weblogs.asp.net/manavi/archive/2011/03/28/associations-in-ef-4-1-code-first-part-2-complex-types.aspx

A: In my opinion problem is with casting. In view you have IEnumerable<projectInterview.Models.Entry> while Topics is ICollection<Topic>, which is a collection of different type

A: Topics = null means there are no Topics in the list to iterate over. How do you fill them? Your view expects IEnumerable how do you cast your topics to the entries?
Based on the original question I've added a small working example, maybe it helps you to find your bug.
Controller:
public class TestController : Controller
{
    public ActionResult Index()
    {
        var viewModel = new ViewModel()
        {
            Topics = new List<Topic>()
        };

        viewModel.Topics.Add(new Topic() { header = "test" });
        viewModel.Topics.Add(new Topic() { header = "test2" });

        return View(viewModel);
    }

}

Model:
public class ViewModel
{
    public virtual ICollection<Topic> Topics { get; set; }

    public int getCount()
    {
        return Topics.Count;
    }
}

public class Topic
{
    public string header { get; set; }
}

View:
@model testProject.Models.ViewModel
@{
   ViewBag.Title = "Index";
}

Index

@Model.getCount()

@foreach(var item in Model.Topics)
{

@item.header

}

Output:
Index
2
test
test2

A: It seems that you are not initializing your Topics anywhere in the code. If the collection is null it means it is not initialized. If you instantiate it with
ICollection<Topic> Topics = new List<Topic>();

Once initialized you should receive zero when calling Topics.Count. If you do not make a call to a database it will stay zero.
In your case check whether you are instantiating the Topics.


text:
Q: Scenekit shape between 4 points Given that the route I was taking in a previous question:
ARKit - place a SCNPlane between 2 vector points on a plane in Swift 3
...seems to be flawed, I'm looking at other options. I can draw a line between 2 nodes, I can then create nodes above those, effectively in a square but even if I draw lines between them all, I can't make that into a shape. Is it possible in Scenekit to draw a shape (square) where each of the 4 corners joins to a node.
I can create a plane, position it on a node, transform the pivot and then rotate but it doesn't always work but SCNGeometry lines do.
Thanks

A: So the answer, at least my solution is to use SCNGeometry triangles. I wanted a square (rather than a cube) to act as a wall in Augmented Reality so I simply built 2 triangles using the 4 nodes that mapped the 4 corners of a wall.
The class to build the triangle:
extension SCNGeometry {

    class func triangleFrom(vector1: SCNVector3, vector2: SCNVector3, vector3: SCNVector3) -> SCNGeometry {

        let indices: [Int32] = [0, 1, 2]

        let source = SCNGeometrySource(vertices: [vector1, vector2, vector3])

        let element = SCNGeometryElement(indices: indices, primitiveType: .triangles)

        return SCNGeometry(sources: [source], elements: [element])
    }
}

The points for the 2 triangles are [p1, p2, p4] and [p1, p3, p4] called using the following:
let thirdPoint = firstPoint.clone()
thirdPoint.position = SCNVector3Make(thirdPoint.position.x,
thirdPoint.position.y + Float(1.5), thirdPoint.position.z)
sceneView.scene.rootNode.addChildNode(thirdPoint)

let fourthPoint = secondPoint.clone()
fourthPoint.position = SCNVector3Make(fourthPoint.position.x,
fourthPoint.position.y + Float(1.5), fourthPoint.position.z)
sceneView.scene.rootNode.addChildNode(fourthPoint)

let triangle = SCNGeometry.triangleFrom(vector1: firstPoint.position, vector2: secondPoint.position, vector3: fourthPoint.position)
let triangleNode = SCNNode(geometry: triangle)
triangleNode.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
triangleNode.geometry?.firstMaterial?.isDoubleSided = true
sceneView.scene.rootNode.addChildNode(triangleNode)

let triangle2 = SCNGeometry.triangleFrom(vector1: firstPoint.position, vector2: thirdPoint.position, vector3: fourthPoint.position)
let triangle2Node = SCNNode(geometry: triangle2)
triangle2Node.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
triangle2Node.geometry?.firstMaterial?.isDoubleSided = true
sceneView.scene.rootNode.addChildNode(triangle2Node)

This is all based on creating 2 initial nodes by selecting the bottom 2 points of a wall in ARKit.
Hope that makes sense to anybody else searching for a similar answer.
EDIT: Adding a Material
Here's a slightly different extension and the code to add a material to it, the end result of a wall remains the same:
extension SCNGeometry {

    class func Quad() -> SCNGeometry {

        let verticesPosition = [
            SCNVector3(x: -0.242548823, y: -0.188490361, z: -0.0887458622),
            SCNVector3(x: -0.129298389, y: -0.188490361, z: -0.0820985138),
            SCNVector3(x: -0.129298389, y: 0.2, z: -0.0820985138),
            SCNVector3(x: -0.242548823, y: 0.2, z: -0.0887458622)
        ]

        let textureCord = [
            CGPoint(x: 1, y: 1),
            CGPoint(x: 0, y: 1),
            CGPoint(x: 0, y: 0),
            CGPoint(x: 1, y: 0),
        ]

        let indices: [CInt] = [
            0, 2, 3,
            0, 1, 2
        ]

        let vertexSource = SCNGeometrySource(vertices: verticesPosition)
        let srcTex = SCNGeometrySource(textureCoordinates: textureCord)
        let date = NSData(bytes: indices, length: MemoryLayout<CInt>.size * indices.count)

        let scngeometry = SCNGeometryElement(data: date as Data,
primitiveType: SCNGeometryPrimitiveType.triangles, primitiveCount: 2,
bytesPerIndex: MemoryLayout<CInt>.size)

        let geometry = SCNGeometry(sources: [vertexSource,srcTex],
elements: [scngeometry])

        return geometry

    }

}

Then simply call it in viewDidLoad() and apply a material
let scene = SCNScene()

let quad = SCNGeometry.Quad()

let (min, max) = quad.boundingBox

let width = CGFloat(max.x - min.x)
let height = CGFloat(max.y - min.y)

quad.firstMaterial?.diffuse.contents = UIImage(named: "wallpaper.jpg")
quad.firstMaterial?.diffuse.contentsTransform = SCNMatrix4MakeScale(Float(width), Float(height), 1)
quad.firstMaterial?.diffuse.wrapS = SCNWrapMode.repeat
quad.firstMaterial?.diffuse.wrapT = SCNWrapMode.repeat

let node = SCNNode()
node.geometry = quad
scene.rootNode.addChildNode(node)

sceneView.scene = scene


text:
Q: What symbol and variable really represent when I use them in nasm? What does the line : "d: db 'hey',0xa" represent.
I know d is a symbol but what does it mean when I use it like that: "mov eax, d"? Do I put the value or the address into eax? What does the symbol represent when I use it?
Secondly, to write output we must fill the ecx register with the pointer to the value, normally like this : "mov ecx, [v1]". But why do I have to put the bracket? Can't I just mov the value of the address in ecx?


text:
Q: Socket timeout when trying to create a new vue project with vue-cli I'm getting an error when I create a new Vue project using vue-cli. Each time the create fails on a "Socket timeout" but a different request? I updated node using nvm and installed the latest vue-cli.
Terminal shows this:
Vue CLI v4.5.9
✨  Creating project in /Users/me/Documents/GitHub/myproject.
  Initializing git repository...
⚙  Installing CLI plugins. This might take a while...

npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! request to https://registry.npm.taobao.org/cosmiconfig failed, reason: Socket timeout

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2020-12-07T11_02_37_391Z-debug.log
 ERROR  command failed: npm install --loglevel error --legacy-peer-deps

The create tends to fail around the log file is around line 4900. These are the last lines in the log file:
4875 timing idealTree:node_modules/webpack-dev-server/node_modules/anymatch/node_modules/normalize-path Completed in 0ms
4876 timing idealTree:buildDeps Completed in 164233ms
4877 timing idealTree:fixDepFlags Completed in 10ms
4878 timing idealTree Completed in 164265ms
4879 timing command:install Completed in 164269ms
4880 verbose type system
4881 verbose stack FetchError: request to https://registry.npm.taobao.org/cosmiconfig failed, reason: Socket timeout
4881 verbose stack     at ClientRequest.<anonymous> (/Users/me/.nvm/versions/node/v15.3.0/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:97:14)
4881 verbose stack     at ClientRequest.emit (node:events:376:20)
4881 verbose stack     at TLSSocket.socketErrorListener (node:_http_client:490:9)
4881 verbose stack     at TLSSocket.emit (node:events:388:22)
4881 verbose stack     at emitErrorNT (node:internal/streams/destroy:188:8)
4881 verbose stack     at emitErrorCloseNT (node:internal/streams/destroy:153:3)
4881 verbose stack     at processTicksAndRejections (node:internal/process/task_queues:80:21)
4882 verbose cwd /Users/me/Documents/GitHub/myproject
4883 verbose Darwin 19.6.0
4884 verbose argv "/Users/me/.nvm/versions/node/v15.3.0/bin/node" "/Users/me/.nvm/versions/node/v15.3.0/bin/npm" "install" "--loglevel" "error" "--legacy-peer-deps"
4885 verbose node v15.3.0
4886 verbose npm  v7.0.14
4887 error code ERR_SOCKET_TIMEOUT
4888 error errno ERR_SOCKET_TIMEOUT
4889 error request to https://registry.npm.taobao.org/cosmiconfig failed, reason: Socket timeout
4890 verbose exit 1

A: I ran into this as well. Fixed it by first running
vue config -e

Then setting this property to false:
{
  "useTaobaoRegistry": false
}

A: Ok, I just updated my os to Big Sur and now it seems to work.

A: Updating to Big Sur did not help me.
This, however, helped:
sudo npm uninstall -g vue
sudo npm uninstall -g vue-cli
sudo npm uninstall -g @vue/cli
sudo npm cache clean --force
sudo npm install -g vue
sudo npm install -g @vue/cli


text:
Q: Accessing class-level values of type parameters in Scala I have a trait and a case class implementing it. One of the features of the trait that the implementations override is a default value. I can't find a good way to access this default value from a class that is parametrized by a specific implementation of that trait.
This is minimal code, so it doesn't really demonstrate the motivation anymore, but it does demonstrate the error:
import scala.language.implicitConversions

trait Distance[T] {
  val Zero: T
  def +( that: T ): T
}

case class DoubleDistance( val v: Double ) extends Distance[DoubleDistance] {
  val Zero = DoubleDistance( 0.0 )
  def +( that: DoubleDistance ) = DoubleDistance( v + that.v )
}

object DistanceImplicits {
  implicit def DoubleToDistance( v: Double ) = new DoubleDistance( v )
}

class User[T<:Distance[T]] {
  val default: T = T.Zero // This line gives me a compilation error
}

The error I get is
not found: value T

When I needed to construct an Array[T] inside my User class I could get that to work by adding implicit typetag:ClassTag[T] to my arguments, but that doesn't seem to have any effect here.

A: First, why this doesn't work: consider a different implementation of Distance.
case class DoubleDistance1(val v: Double) extends Distance[DoubleDistance1] {
  val Zero = this
  def +(that: DoubleDistance1) = ??? // doesn't matter
}

What would you expect DoubleDistance1.Zero to mean? You can make it work using a "type class":
trait DistanceOps[T] {
  val zero: T
  def add(d1: T, d2: T): T
}

// just to let you write distance1 + distance2
implicit class RichDistance[T](d: T)(implicit ops: DistanceOps[T]) {
  def +(other: T) = ops.add(d, other)
}

case class DoubleDistance(v: Double)

object DoubleDistance {
  implicit object DoubleDistanceOps extends DistanceOps[DoubleDistance] {
    val zero = DoubleDistance(0.0)
    def add(d1: DoubleDistance, d2: DoubleDistance) = DoubleDistance(d1.v + d2.v)
  }
}

// how to use
class User[T](implicit ops: DistanceOps[T]) {
  val default: T = ops.zero
}

A: This looks like a classic use case for the type class pattern. Rather than associating an instance of the Distance trait with each value of interest, you associate one with each type of interest:
trait Distance[T] {
  val Zero: T
  def +( a: T, b: T ): T
}

implicit object DoubleDistance extends Distance[Double] {
  val Zero = 0.0
  def +( a: Double, b: Double ) = a + b
}

class User[T : Distance] {
  val default: T = implicitly[Distance[T]].Zero
}

A: Where is that Zero supposed to come from? Are you looking to do something like this?
class User[T<:Distance[T]] {
  self:Distance[T] =>
  val default: T = Zero
}


text:
Q: What are the white exclamation point icons for?
I have circled them in fuchsia in this image.
I have cleared these rooms of enemies, and, as far as I know, completed any intractable objects, so I'm unsure what they represent.
Why does my dungeon map have these icons and what do they represent?

A: There is a manual in the game menu, which lists these as Dungeon Events, and nothing more.
So I'm unsure if the icons disappears when the event is completed, or if, like the other icons, they remain on the map to denote a location where an event occurred.
Update
Icons will be removed from the dungeon map when they have been completed. Except for permanent icons such as crafting tables and fishing spots.


text:
Q: Cannot inject TimerService I have an application in JBoss AS 7.1.1 and would like to use the TimerService. I inject it thusly:
@Resource
private TimerService timerService;

This results in the following error when accessing a page in the application:
16:08:30,471 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/c3e].[Faces Servlet]] (http--127.0.0.1-8080-2) Servlet.service() for servlet Faces Servlet threw exception: javax.naming.NameNotFoundException: env/myapp.mypackage.MyClass/timerService -- service jboss.naming.context.java.module.myapp.myapp.env."com.dpdhl.cac.c3e.etl.beans.Resources".timerService

I have tried several other methods, including injecting the SessionContext or using lookup() on an InitialContext to obtain the SessionContext, but they all run into essentially the same problem.
What am I missing here?

A: Problem solved: the bean into which I inject TimerService must be an EJB, not just a CDI bean as it was. I added
@Singleton

to the bean's declaration and it works now.


text:
Q: Small Icon Of Notifications Are Not Drawn In Gray On Oreo? For Android 21+ notification small icons must be alpha-only. Otherwise android will draw them in gray color.
I put here notification screenshots of two devices, one is Oreo and other is Pie, so both are 21+
Android Pie (Xiaomi Mi 6), this is okay it draws the icon in gray

Android Oreo (Samsung Galaxy A - 2016), the small icon is not drawn in gray. Is not it weird ?

Code of notification,
 Notification notification = new NotificationCompat
            .Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher_bos_new)
            .setContentTitle(title)
            .setContentText(message)
            .setSubText(subtitle)
            .setAutoCancel(true)
            .setLights(ContextCompat.getColor(this, R.color.yellow), 1000, 1000)
            .setTicker(getString(R.string.app_name))
            .build();

Why this doesn't behave same on all 21+ devices ?

A: Because at some point Google realized that notification bar backgrounds can be any color, so that meant they had to restrict those icons to using only the alpha channel. This allows the system to automatically recolor the icons to achieve maximum contrast.


text:
Q: Share from Native app to webapp My Chrome Progressive-Web-App(running on an android phone) needs to receive an Share intent from a native app.
Is there a way to do this?

A: I don't think there is a standard way to do that at the moment, but there is already a proposed Web API to do exactly that, and it's called the Web Share Target API. Definitely something worth looking forward to.


text:
Q: Redis mget using Lua script in Nodejs I am passing an array of keys. Here keylist = ['KEY_100', 'KEY_101']
I want to get all the values of the keys. But I am getting an error saying this, node_redis: Deprecated: The EVAL command contains a argument of type Array.
There is an issue in github suggesting to use toString() and again Parse the value in the end. But I am satisfied with that ans. Can anyone help me with this problem?
Nodejs:
getDataLua (keylist) {
    console.log('lua keylist:', keylist)
    const getAsync = promisify(this.client.eval).bind(this.client)
    const reply = await getAsync(fs.readFileSync('./lib/test1.lua'), 1, keylist)
    console.log('reply', reply)
    return reply
  }

Lua Script:
local keys = redis.call('keys', KEYS[1])
local values = redis.call('mget', unpack(keys))
local keyValuePairs = {}
for i = 1, #keys do
  keyValuePairs[i] = .. values[i]
end
return keyValuePairs

A: You should do something like this:
const reply = await getAsync(fs.readFileSync('./lib/test1.lua'), keylist.length, ...keylist);


text:
Q: How to count rows per worksheet in OpenXML I switched from Interop library to OpenXML, because I need to read large Excel files. Before that I could use:
worksheet.UsedRange.Rows.Count

to get the number of rows with data on the worksheet. I used this information to make a progressbar. In OpenXML I do not know how to get the same information about the worksheet. What I have now is this code:
 using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(path, false))
{
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
    int row_count = 0, col_count;
    // here I would like to get the info about the number of rows
    foreach (Row r in sheetData.Elements<Row>())
    {
        col_count = 0;
        if (row_count > 10)
        {
            foreach (Cell c in r.Elements<Cell>())
            {
                // do some stuff
                // update progressbar
            }
        }
        row_count++;
    }
}

A: It's not that hard (When you use LINQ),
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open("PATH", true))
{
    //Get workbookpart
    WorkbookPart workbookPart = myDoc.WorkbookPart;

    //then access to the worksheet part
    IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts;

    foreach (WorksheetPart WSP in worksheetPart)
    {
        //find sheet data
        IEnumerable<SheetData> sheetData = WSP.Worksheet.Elements<SheetData>();
        // Iterate through every sheet inside Excel sheet
        foreach (SheetData SD in sheetData)
        {
            IEnumerable<Row> row = SD.Elements<Row>(); // Get the row IEnumerator
            Console.WriteLine(row.Count()); // Will give you the count of rows
        }
    }
}

Edited with Linq now it's straight forward.


text:
Q: Isomorphism Between Cyclic group algebra and Quotient Polynomial Ring Let $F$ be a field. I'd like to show that:

$a)$ If $V$ is a cyclic group of order $n$, then $$F[V] \cong F[x]/(x^n - 1).$$
$b)$ If $\operatorname{char}(F)\neq 2$, $V=\{1, f, g, fg\}$ is the Klein group, and $\phi : F[x,y] \to F[V]$ is a morphism such that $\phi(x)=1+f$ and $\phi(y)=1+g$; then
$$F[V] \cong F[x,y]/(x^2,y^2).$$

My attempt : for $a)$ if $\varepsilon:F[x]\to F[V]$ is a morphism, then $\ker(\varepsilon)$ is an ideal of $F[x]$. Since $F[x]$ is a PID, then there exists $m \in F[x]$ monic such that $\ker(\varepsilon)=(m)$. For $b)$ I think that the kernel of of $\phi$ is $(x^2,y^2)$: we have $\phi(x^2)=\phi(y^2)=0$.
Thanks for any help!


text:
Q: Looping issue: BeautifulSoup only collecting some elements per page I'm crawling through multiple pages to collect some HTML, but it seems that BeautifulSoup is only collecting some random selection of information. I'm also using selenium with geckodriver on Ubuntu 16.04 OS to click through to the next page.
# import libraries
import urllib.request
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import certifi
import urllib3
import pandas as pd
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import requests

# This URL is ok according to eBay's robots.txt:
urlpage = 'https://www.ebay.com/sch/i.html?_nkw=lululemon&_sacat=15724&rt=nc&LH_Sold=1&LH_Complete=1&_pgn=6'

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
r = http.request('GET', urlpage)
page = urllib.request.urlopen(urlpage).read()
soup = BeautifulSoup(page, 'html.parser')

# Specify containers
item_containers = soup.find_all('div', {'class': 's-item__info clearfix'})
print(len(item_containers)) # should be about 4 dozen

driver = webdriver.Firefox()

# get web page
driver.get(urlpage)

# Loop through
for container in item_containers:
    # If the item has a summary, then extract...:
        if container.find('h3', class_ = 's-item__title s-item__title--has-tags') is not None:
        # The summary
            summary = container.find('h3', class_ = 's-item__title s-item__title--has-tags').text
            summaries.append(summary)
        # The color
            #color = container.find('span', {'class': 's-item__dynamic s-item__dynamicAttributes2'})
            #colors.append(color)
        # The price
            price = container.find('span', attrs = {'class':'POSITIVE'}).text
            prices.append(price)

            button = driver.find_elements_by_class_name('x-pagination__control')[1]
            button.click()

            driver.refresh()
            time.sleep(20)

        # driver.quit()

There are ~4 dozen elements to collect for each tag I specify per page, but after several pages, I'll only have maybe a dozen. Loop logic is off- please advise, I'm trying to improve my python!

A: You can do that without selenium.Use requests of Beautiful Soup.
from bs4 import BeautifulSoup
import requests
url="https://www.ebay.com/sch/i.html?_nkw=lululemon&_sacat=15724&rt=nc&LH_Sold=1&LH_Complete=1&_pgn=6"
html=requests.get(url).text
soup=BeautifulSoup(html,'html.parser')
summery=[]
price=[]
for item in soup.select('div.s-item__info.clearfix'):
    if item.select_one("h3.s-item__title"):
        summery.append(item.select_one("h3.s-item__title").text)
    if item.select_one("span.s-item__price"):
       price.append(item.select_one("span.s-item__price").text)

print(summery)
print(price)

For pagination you can use while loop ans use the page_number how many page you are after.for example i have provided upto 10 pages.
page_num=1
baseurl="https://www.ebay.com/sch/i.html?_nkw=lululemon&_sacat=15724&rt=nc&LH_Sold=1&LH_Complete=1&_pgn={}"

summery = []
price = []
while page_num<=10:
    html = requests.get(baseurl.format(page_num)).text
    soup = BeautifulSoup(html, 'html.parser')

    for item in soup.select('div.s-item__info.clearfix'):
        if item.select_one("h3.s-item__title"):
            summery.append(item.select_one("h3.s-item__title").text)
        if item.select_one("span.s-item__price"):
            price.append(item.select_one("span.s-item__price").text)

    page_num=page_num+1

print(summery)
print(price)

A: Your code is picking up the advertisements:
item_containers = soup.find_all('div', {'class': 's-item__info clearfix'})
The div tag "s-item__info clearfix" is also used for the advertisements shown in the left pane.


text:
Q: How to make a image when mOver(obj) is called i want to show image when mOver(obj) is called:
<script>
function mOver(obj) {
    obj.innerHTML = "Thank You"
}

function mOut(obj) {
    obj.innerHTML = "Mouse Over Me"
}
</script>

for instance i have this image:  http://www.w3schools.com/images/w3schoolscom_gray.gif
when i make so: http://www.w3schools.com/images/w3schoolscom_gray.gif
function mOver(obj) {
        obj.innerHTML = http://www.w3schools.com/images/w3schoolscom_gray.gif;
    }

it doesn't work.

A: innerHTML replace the content of your obj by a HTML representation of a string.
If your obj is a container (like a div) you should do this :
function mOver(obj) {
    obj.innerHTML = '<img src="http://www.w3schools.com/images/w3schoolscom_gray.gif" alt="..."/>';
}

If your obj is a <img> tag you should do this :
function mOver(obj) {
    obj.src = 'http://www.w3schools.com/images/w3schoolscom_gray.gif';
}

:)


text:
Q: DPM 2012 Installation Error We have windows server 2012 R2.
Trying to install DPM 2012 R2 with SQL Std 2012 R2 Installed on server.

Installed all prerequisite on server.
All the SQL services are running.
Here is the Error Log https://1drv.ms/t/s!AunGkJZbsiwbgQJ2UJlNYNiAGnNG

A: You can try to create a new report database in "reporting services configuration manager ":
Regarding "creating new report DB"


text:
Q: Are there any references regarding GCD of sets of numbers and GCD of Minkovski sum? I needed to define GCD of a set of integers and some properties involving GCD of Minkowski sum of sets. It is nothing too complicated, but I would like to point out references if something similar was defined before. However I could not find anything related.
Is there any papers/books where GCD is defined for sets of integers and/or GCD of Minkowski sum is considered?


text:
Q: TI AM335x QT4.8.3 read CANbus Short story: I have TI AM335x armv7l processor development board which runs embedded linux 3.2.0. I would like to read data from the CAN-bus and visualize this. I have no idea on how to start with this.
Longer story:
So I have a TI AM335x development board from GOEMBED (http://goembed.com/index.php/Products/detail/tpid/25 simular to the beaglebone black). It uses an armv7l processor which runs linux 3.2.0.
I connected a CAN-module to the development board. This CAN-module sends every second the same CAN-message onto the CAN-bus.
By entering the following commands into the terminal I can visualize the CAN-messages.
ip link set can0 type can bitrate 500000 triple-sampling on
ip link set can0 up
candump can0

At this point I can see the the ID and data of the CAN-message.
root@goembed:~# ip link set can0 type can bitrate 500000 triple-sampling on
root@goembed:~# ip link set can0 up
root@goembed:~# candump can0
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3
  can0  1FC0000F   [8]  F5 F8 F1 00 00 00 F2 F3

Now the big problem is, how can I get this data into a qt-application?
I would like to print the data of a message into a textbox.
Hopefully somebody can give me some hints on how to start with this, so I can learn out of it?
Kind regards

A: Ideally, you should build Qt 5.8 for your platform and use the QtSerialBus module. Otherwise, you're facing the boring task of backporting QtSerialBus to Qt 4. It won't be particularly hard.
Once you have access to the serial bus module, you can easily get notified in real time as CAN packets arrive, and then display them in any way you wish. E.g. you could accumulate them in a model, and display them in a QTableView.

A: I found an easy solution.
So as I want to read all messages in my embedded system, I easily just can take the response of my QProcess.
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&proc3,SIGNAL(readyRead()),this, SLOT(dataReady()));
    QD << QDir::currentPath();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::dataReady()
{
    while(proc3.bytesAvailable()){
        QString in = proc3.readLine();
        QString out;

        QRegExp reg("  can([01])  ([0-9A-F]+)   \\[([0-9]+)\\]  ([0-9A-F]+) ([0-9A-F]+) ([0-9A-F]+) ([0-9A-F]+) ([0-9A-F]+) ([0-9A-F]+) ([0-9A-F]+) ([0-9A-F]+)");

        if(reg.indexIn(in)>=0){
            out = "from Can%1 Id:%2 amount bytes:%3 first byte:%4 second byte:%5 third byte:%6 fourth byte:%7 fifth byte:%8 sixth byte:%9 seventh byte:%10 eight byte:%11";
            out = out.arg(reg.cap(1)).arg(reg.cap(2)).arg(reg.cap(3)).arg(reg.cap(4)).arg(reg.cap(5)).arg(reg.cap(6)).arg(reg.cap(7)).arg(reg.cap(8)).arg(reg.cap(9)).arg(reg.cap(10)).arg(reg.cap(11));
        }else{
            out = "Error:" + in;
        }
        ui->plainTextEdit->appendPlainText(out);
    }
}

void MainWindow::on_startButton_clicked()
{
    QString cmd1 = "ip";
    QStringList opt1;
    QD;
    opt1 << "link"<< "set"<< "can0"<< "bitrate"<< "500000"<< "triple-sampling"<< "on";
    proc1.start(cmd1,opt1);

    QString cmd2 = "ip";
    QStringList opt2;
    QD;
    opt2 << "link"<< "set"<< "can0"<< "up";
    proc2.start(cmd2,opt2);

    QString cmd3 = "candump";
    QStringList opt3;
    QD;
    opt3 << "can0";
    proc3.start(cmd3,opt3);
}

void MainWindow::on_stopButton_clicked()
{
    QString cmd4 = "ip";
    QStringList opt4;
    QD;
    opt4 << "link"<< "set"<< "can0"<< "down";
    proc4.start(cmd4,opt4);
}

So at this point I can put the ID, amount of databytes and the databytes itself into variables. So play time can start!
I hope this helps other people. If people know improvements, let me know.
Kind regards


text:
Q: Incremental field to existing collection I have a collection containing around 100k documents. I want to add an auto incrementing "custom_id" field to my documents, and keep adding my documents by incrementing that field from now on.
What's the best approach for this? I've seen some examples in the official document (http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/) however they're only for adding new documents, not for updating an existing collection.
Example code I created based on the link above to increment my counter:
function incrementAndGetNext(counter, callback) {
    counters.findAndModify({
        name: counter
    }, [["_id", 1]], {
        $inc: {
            "count": 1
        }
    }, {
        "new": true
    }, function (err, doc) {
        if (err) return console.log(err);
        callback(doc.value);
    })
}

On the above code counters is db.counters collection and I have this document there:
{_id:"...",name:"post",count:"0"}

Would love to know.
Thank you.
P.S. I'm using native mongojs driver for js

A: Well, using the link you mentionned, I'd rather use the counters collection approach.
The counters collections approach has some drawbacks including :

*

*It always generates multiples request (two): one to get the sequence number, another to do the insertion using the id you got via the sequence,

*If you are using sharding features of mongodb, a document responsible for storing a counter state may be used a lot, and each time it will reach the same server.

However it should be appropriate for most uses.
The approach you mentionned ("the optimistic loop") should not break IMO, and I don't guess why you have a problem with it. However I'd not recommend it. What happens if you execute the code on multiple mongo clients, if one has a lot of latency and others keep taking IDs? I'd not like to encounter this kind of problem... Furthermore, there are at least two request per successful operation, but no maximum of retries before a success...


text:
Q: Patterns in Sieve of Eratosthenes Consider an integer sequence
$$0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0...$$
Each term denotes the number of times the corresponding natural number, starting from $0$, was hit by subsequent steps of sieving.
After we sieve the number $2$, the sequence becomes:
$$1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1...$$
We can easily see a pattern here: it's just $1, 0$ repeated ad infinitum.
The pattern's length is $2$.
After we sieve the number $3$, the sequence becomes:
$$2,0,1,1,1,0,2,0,1,1,1,0,2,0,1,1,1,0,2,0,1,1,1,0,2,0,1,1,1,0...$$
It's clear that we just repeat $2,0,1,1,1,0$, a pattern whose length is $6$.
So the pattern constantly expands until we get to the number $6$.
Here are the patterns for $5$ and $6$ respectively (I've omitted commas for tighter spacing):
$401121202120301220203110311120302111301130202210302120212110$
$501121302120401220303110411120402111401130302210402120312110$
Both patterns share the same length of $60$. It however expands for $7, 8, 9$ and again it doesn't for $10$.
Numerical evidence suggests that the pattern only ever expands after sieving prime powers - if $n = p^{e}$, the pattern's length for $n$ is the pattern's length for $n-1$ multiplied by $e$. So far I've validated this up to $18$.
Can this conjecture be proven?
Most importantly, is there a way to conceive this phenomenon intuitively?
I've looked up the sequence of consecutive pattern lengths (starting from 2) and from what I can see it's got something to do with least common multiples.

A: Yes, this is all about least common multiples.
First, note that what you're doing is adding sequences, termwise: for each $n$, let $S^n$ be the sequence with a $1$ in every $n$th spot, starting at the first, and $0$s elsewhere. E.g.

*

*$S^2=1,0,1,0, . . .$

*$S^5=1, 0,0,0,0, 1, 0,0,0,0, 1, 0,0,0,0, . . .$

*And so on.
Now, there's a natural way to add sequences: just add their corresponding terms. So, for instance, $S^2+S^5=2, 0, 1, 0, 1, 1, 1, 0, 1, 0, 2, . . . $
You're asking about the period of $S^2+S^3+. . . +S^n$, as a function of $n$. Note the following (these are good exercises):

*

*If $A$, $B$ are periodic sequences with periods $a, b$ respectively, then $A+B$ has period $lcm(a, b)$. Similarly, if $C^1 , . . . , C^n$ have periods $c_1, . . . , c_n$ respectively, then $C^1+ . . . +C^n$ has period $lcm(c_1, . . . , c_n)$.

*$S^n$ has period $n$.

*If $n$ is not a prime power, then the lcm of $\{2, 3, . . . , n\}$ equals the lcm of $\{2, 3, . . . , n-1\}$, that is, the period doesn't change at non-prime-powers.

*Conversely, if $n$ is a prime power, then the lcm of $\{2, 3, . . . , n\}$ does not equal the lcm of $\{2, 3, . . . , n-1\}$.


text:
Q: Using shortcodes to communicate my page design I came across this page http://flare.bringthepixel.com/pages/services/ and on it there is this message: "The entire code of this sample page is available in the Shortcode Generator".
Lets say i gave someone this theme and wanted to produce his/her own page look just like the one shown without inserting one shortcode after another.Can shortcodes be used to make one big page "template" such that with one insertion of shortcode,the design in the services page shall be inserted and the user shall only swap the dummy content for his/her own?.

A: If you are going to use that shortcode inside post/page content, then you can build any layout/design with that shortcode. You can do even more if you are calling do_shortcode() in your theme.
Technically its possible to do it and whether it would be a good implementation or not depends on the use case. Like for specific layouts inside the page content, this is an excellent choice but for using it as a substitutes to page templates, that will be a bad design choice.
You can do pretty much inside a shortcode, point is when you should. Read more on implementation here - http://codex.wordpress.org/Shortcode_API


text:
Q: Survival analysis of two dependent variables (hatching time and total life duration) I strive to find the best approach to analyse survival data from an experiment where random samples of fish eggs (sample size 30) were put into 3 different solutions of 8 heavy metals (total 24 combinations solution x metal plus one control group).
For each egg the hatching time (in hours) was recorded (for eggs that was not already dead). Further, in case where an egg was successfully hatched, skeletal problems and total lifetime (up to 96 hours) were recorded (one observation every 6 hours, up to 96 hours).
Hatching time survival analysis was rather straightforward using Kaplan Meier estimator and log - rank tests in order to find homogeneous metals for each solution subgroup. As a partial result some metals were recognized as more toxic than the others.
However, total lifetime is obviously dependent to hatching time (and hatching event) as well as on skeletal problems after hatch. Since there is more than one independent variables to explain life duration, Kaplan Meier is not an appropriate choice and Cox regression should be applied.
A choice is to consider life duration after hatching event as the dependent variable and run a Cox regression having metal solution and skeletal problems as explaining variables. However, this model seems to be a poor choice since it seems natural to expect that the exposure of the egg to the toxic environment before hatch will also affect the total life duration.
So, a question arises.
What could be the best approach in order to model the lifetime duration? Is the above choice (life duration after hatch) the only possible approach or there is a more sophisticated procedure to follow in order to model the total burden that a fish accepts from the metal environment? In case of an affirmative answer what is the suggested procedure in R or SPSS to accomplish this task?


text:
Q: No DNS resolution when running XP in VMWare Fusion with a static IP I'm winning Windows XP under VMWare Fusion on my OSX 10.7.4 in bridged mode.
I need to be able to reference the Guest (XP) via a hostname, as it hosts a server i use in development.  To achieve that, I have gone into the XP network settings and specified for it to use a Static IP address.  Then I edit my Hosts (OSX) /etc/hosts file to add a hostname entry for that ip address.  This all works fine, however when I do it that way, the XP does not have internet access.  It seems that it has no DNS resolution (ie i can ping external IP addresses, but not hostnames).
When I have XP use dynamic IP's via DHCP, the internet works perfectly - but then I can't reference it via it's hostname.
Can anyone suggest how I can achieve both here?  Is there a way I can have the guest with a static ip, but automatically use the DNS that my host uses?
Note that I don't mind whether it's bridged or NAT. Should I be using NAT instead?  The key things I require are:
 1. The Guest XP must be able to be referenced via a hostname from the Host OSX.
 2. The Guest XP must have internet access.
Any help would be greatly appreciated.

A: I had problems with this setup trying to tunnel into iisexpress using hostnames. Finally got things working using the following setup.

*

*Set vmware network to shared with mac (NAT)

*set guest (windows) network to dhcp note down ALL the settings dhcp assigns.

*change back to static and use those settings

*the gotcha for me was that i didn't notice the local domain prefix assigned to DNS under advanced options.

Now your mac (host) may be on dhcp and get a new ip address every time but the guest os will always have the same static ip address. This was essential for me as i work from a macbook pro and connect to different networks with different subnets.
hope this helps.


text:
Q: how to get image from a source to view on my blackberry simulator
Possible Duplicate:
Bundling images with Blackberry

hi i am doing blackberry application development for OS 5.0 using eclipse IDE but i cant find the code for getting a PNG image file from a source to be viewed on my blackberry simulator.

A: Paste an image on res folder on your project.
.
Then use Bitmap.getBitmapResource(..) to get the image.
Bitmap myImage = Bitmap.getBitmapResource("my_image.png");


text:
Q: Why is my left view in text field not working? I've added a left view to my text field using the code below:
    usernameField.leftViewMode = UITextFieldViewMode.always
    passwordField.leftViewMode = UITextFieldViewMode.always

    let usernameImageView = UIImageView()
    let usernameImage = UIImage(named: "user icon grey.png")
    usernameImageView.image = usernameImage
    usernameField.leftView = usernameImageView

    let passwordImageView = UIImageView()
    let passwordImage = UIImage(named: "lock icon grey.png")
    passwordImageView.image = passwordImage
    passwordField.leftView = passwordImageView

This didn't work, I then added a UIDesignable, a very neat process that I took from this question below on StackOverflow. This means that I can see the icons in the storyboard, as can be seen below. However, this doesn't show up.
Swift add icon/image in UITextField

A: The problem is with how you create the image view. You first create an empty image view which then has no size. You then assign the image to the image view but this does not automatically resize the image view.
There are two solutions.

*

*Tell the image view to resize itself after assigning the image.
let usernameImageView = UIImageView()
let usernameImage = UIImage(named: "user icon grey.png")
usernameImageView.image = usernameImage
usernameImageView.sizeToFit()

*Create the image view with the image. This is simpler approach.
let usernameImage = UIImage(named: "user icon grey.png")
let usernameImageView = UIImageView(image: usernameImage)

A: The problem is with your code. using this code now your left view in textField is working.
@IBOutlet weak var name: UITextField!
override func viewDidLoad() {
  super.viewDidLoad()
  usernameField.leftViewMode = .always
  let usernameImageView = UIImageView()
  usernameImageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
  let usernameImage = (your image name)
  usernameImageView.image = usernameImage
  usernameField.leftView = usernameImageView


text:
Q: Entity Framework many-to-many relationship include extremely slow I have an Entity Framework 4 model, with 2 entities containing many-to-many relationship, so 3 tables, [Q], [P] and [Q2P]-cross table. Running code like:
context.Q.Include("P");

Results in long time wait (I waited like 5 mins then aborted it). Then I checked SQL generated and found this:
SELECT *
FROM ( SELECT *
    FROM  [Q] AS [Extent1]
    LEFT OUTER JOIN  (SELECT *, CASE WHEN ([Join1].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
        FROM  [Q_P] AS [Extent2]
        INNER JOIN [P] AS [Extent3] ON [Extent3].[Id] = [Extent2].[Id] ) AS [Join1] ON [Extent1].[Id] = [Join1].[Id]
)  AS [Project1]
ORDER BY [Project1].[Id] ASC, [Project1].[C2] ASC

I can't hide my suprise, WTF is this?  The usual many-to-many SQL query
select * from [q2p]
join [q] on qId=q.Id
join [p] on pId=p.Id

executes in less than 1ms, while EF query executes forever.

A: Yep, that's not a secret that it takes long, please vote on the connection I opened about a year ago.
However, 5 minutes is something it's definitely not supposed to take.
Try separating the execution from the query generation, and use ToTraceString to see how long does it take to determine query generation time.
Eager-loading is not the great deal in current version, they said they're planning toreduce the performance cost in future.
Anyway, what you could do is use Stored Procedures or create your own ObjectQueries.
See:
 - http://msdn.microsoft.com/en-us/library/bb896241.aspx
 - http://msdn.microsoft.com/en-us/library/bb896238.aspx

A: I have switched to Nhibernate.


text:
Q: RabbitMQ: Delete a queue if consumer is gone forever? Imagine each user has it's own queue. Messages are put in to the queue when the user is offline and when they reconnect, they receive all those messages.
However, what if the client leaves and never comes back (stops using the service)? Does RabbitMQ have a way to delete a queue if messages haven't been consumed in a while? Messages might be coming in, but they aren't going out because the client is no longer active. How could I handle this with the amqp.node plugin?

A:
Imagine each user has it's own queue. Messages are put in to the queue when the user is offline and when they reconnect, they receive all those messages.

this is a common idea, but one with unfortunate consequences, that you should avoid.
as i wrote in that linked article:

You could potentially work around this by having a queue per user. You
  could set up your code so that the web server only subscribes to a
  queue for the user when that user is logged in and available.
This doesn't solve the problem.
Now you have 30,000 messages distributed across 1,000 queues – a bad
  situation in itself. This requires RabbitMQ to persist the queues and
  the messages within the queues. And what happens when all 1,000 users
  log in to your system at the same time? Now your web server has 1,000
  queue subscriptions to deal with.

sure, you could argue that you won't have that many users. but it gets worse. in your situation, you won't be able to delete the queue the way you want, automatically.
you can set a queue to automatically delete once all consumers are disconnected. but keeping the queue around would require a consumer per user queue, where the consumer is connected for as long as that user exists. if the application crashes, the queue and all of it's messages would disappear.
TTL will only do part of what you want. it will put a life on the message in the queue and the message will be removed after that timeout... but it won't delete the queue.
ultimately, you don't want to do this with RabbitMQ.
again, from my article on the subject:

Getting back to the original scenario, what should you do when the
  user is not online and you can't send the message to them immediately?
Store the message in a database.
Add a field to the database record that says who this message belongs
  to. When the user reconnects later, query the database for any
  messages that this user needs to see and send them along at that time.
The full process started above, then becomes this:

*

*User's browser connects to SignalR/Socket.io/Pusher/websockets on web
  server

*Web server checks a queue for updates that happen during a long
  running process

*When a message for a logged in user comes in

*

*If the
  user is logged in, broadcast the message through the websocket to the
  user

*If the user is not logged in, store the message in a database

*When the user logs in again, query the database and send all waiting
  messages

  It's what you would have done before the idea of a message
  queue came in to play, right? It should be what you would do now that
  you have a message queue, as well.

A: It appears to be possible, but I haven't tried it myself. See:
https://www.rabbitmq.com/ttl.html
Look at Queue TTL way down at the bottom. "This controls for how long a queue can be unused before it is automatically deleted."
To see an example usage, this test in the node-amqp code base might be inspirational:
https://github.com/postwait/node-amqp/blob/f64704d3727266230901598e2daf0fa780766feb/test/test-queue-args.js#L8


text:
Q: Trying to pass data into computed property Vue JS I have a project that uses Vue JS, more specifically, Nuxt JS. In my web page I need to render some classes onto an element that exists within a v-for, so I need to be able to pass data to some computed property, I also need to pass the validation classes to it. For some reason, my computed property isn't accepting my arguments, what am I doing wrong?
The error I'm getting is:

_vm.getClassesForDataItem is not a function

And my code is:
<template>

        <validation-provider
          name="data source"
          :rules="{ required: { allowFalse: false } }"
          v-slot="{ errors, classes }"
        >

Data Source

{{ table }}

                <svg xmlns="http://www.w3.org/2000/svg" fill="none" height="24" width="24" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>

            <input :id="'source-'+sourceIndex" v-model="source.isChecked" type="checkbox" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded cursor-pointer hidden">

          {{ errors[0] }}
        </validation-provider>

</template>

Am I better off using a method for this?

A: Computed properties can't take in parameters but technically you can return a function from the computed property that takes in a parameters:
getClassesForDataItem() {
    return ui => ui ? 'border-indigo-300 ring-indigo-50' : 'border-gray-300 ring-gray-50';
}

You can also move it to a method, see here for an explanation between the two options.

A: Try to return a  function with parameters from your computed property :
export default {
  computed: {
    getClassesForDataItem () {
      return (ui, errorClasses) => errorClasses || (ui ? 'border-indigo-300 ring-indigo-50' : 'border-gray-300 ring-gray-50')
    }
  }
}


text:
Q: How to trigger celery signals on tests I'm writting a tests for celery task_failure signal handler, however I have a problem to trigger this signal during tests.
How can I trigger celery signal manually?
I have following code:
tasks.py
def do_something():
    print "hello"

@app.task(name='simple_task')
def simple_task(x, y):
    do_something()
    return x - y

@task_failure.connect(sender='simple_task')
def task_failure_handler(args=None, **kwargs):
    logger.exception("Task failed")

@celeryd_init.connect
def init_signals(*args, **kwargs):
    task_failure.connect(
        task_failure_handler
        sender='simple_task'
    )

and I'm trying to write a tests to check if signal is called when task fail.
So far I've done:
@patch('tasks.task_failure_handler')
@patch('tasks.do_something')
def test_signal_handler(task_mock, signal_mock):
    task_mock.side_effect = Exception()
    tasks.simple_task.apply((1, 2,))
    assert signal_mock.called

But signal is not triggered and assertion fail.
I did some debugging and problems seems to be related with self._live_receivers(sender) in celery/utils/dispatch/signal.py
self._live_receivers(sender) is empty despite the fact that recipient is available, but none of these conditionals: r_senderkey == NONE_ID or r_senderkey == senderkey are true. I do not understand why is this happening.
Why my receiver is not a live? How can I trigger signal manually?


text:
Q: How to change Firefox image background color back to white? I have problems viewing any transparent images, which have no background color set: the black lines are almost invisible on the dark gray background that Firefox has now set instead of the white color which was in use for 30 years(?).
Everyone has assumed the color is white for so long time, so all the transparent images are now hard to read.
How do i change the Firefox default background color for images (#222222) back to #FFFFFF ?
Firefox version: 13.0.1

A: You can use the Old Default Image Style add-on to restore the old behaviour. It also allows you specify the exact background colour used, and keep the new centred alignment instead of the old top-left corner, if you want.


text:
Q: Dynamic sorting in related lists in Salesforce classic It seems I can't change the sorting order of a related lists inside the Account layout.
Is it possible to allow the user to change the sorting column of a related list without "going to list" ?

A: The only way to sort a related list is by setting the related sort options in the related lest settings on the page layout interface.


text:
Q: Why does matching this function parameter seprately work, but not with guards. (Haskell) So, I have been trying to use SDL to make a simple GUI. This is so that I start to understand how to use haskell. In this case, I was using https://github.com/palf/haskell-sdl2-examples/blob/master/examples/lesson04/src/Lesson04.hs as reference.
Pay attention, in particular to payloadToIntent on line 72.
payloadToIntent :: SDL.EventPayload -> Intent
payloadToIntent SDL.QuitEvent         = Quit
payloadToIntent (SDL.KeyboardEvent k) = getKey k
payloadToIntent _                     = Idle

This works perfectly. However, when I change the code to the following, it produces an error. Why does it happen, as to my (admittedtly novice) eyes, this looks equivalent.
payloadToIntent e
  | e == SDL.QuitEvent = Quit
  | e == SDL.KeyboardEvent k = getKey SDL.KeyboardEvent k
  | otherwise = Idle

Error:
src/Events/Intent.hs:15:28: error:
    Variable not in scope: k :: SDL.KeyboardEventData
   |
15 |   | e == SDL.KeyboardEvent k = getKey SDL.KeyboardEvent
   |                            ^

I am using these language extensions: OverloadedStrings, GADTs, PatternGuards
So why did this happen? How could I fix this? Which one would be more idiomatic haskell?

A: (==) is a function that takes two values of the same type and compares them for equality, returning a Bool. SDL.KeyboardEvent k is not a value of any type (since k is unbound), so you can't compare it with (==).
The idiomatic "choice" is the one that works, i.e. pattern matching. If you want something that has a similar appearance, you can pattern match with case...of instead:
payloadToIntent e = case e of
  SDL.QuitEvent -> Quit
  SDL.KeyboardEvent k -> getKey k
  _ -> Idle

A: The key idea here is: patterns define variables, bringing them into scope, while expressions do not, requiring all the variables in them to be already defined.
The guard e == SDL.KeyboardEvent k is a boolean valued expression, not a pattern. This is calling function (==) with two arguments: e and SDL.KeyboardEvent k. Your definition, to the compiler, looks like:
payloadToIntent e
  | isEqual e SDL.QuitEvent = Quit
  | isEqual e (SDL.KeyboardEvent k) = getKey SDL.KeyboardEvent k
  | otherwise = Idle

The compiler can not call the equality-test function without passing it the arguments. For that, it needs variable k to be in scope, i.e., to be defined somewhere else.
To stress the point, consider this non-working code:
isSquare :: Int -> String
isSquare n | n == m*m  = "It's the square of " ++ show m
           | otherwise = "It isn't a square"

This would magically invert the squaring, if possible. That is, however, asking too much to the compiler, which won't magically solve the equation for us. (Indeed, the solution could even fail to be unique!)
As an even more cumbersome case:
f x | x == F y || x == G z = ...

Even if this worked, can we use y or z in the final ...? Probably not. Why should then this be allowed?
Finally, note that, even in those cases where it could work, allowing expressions guards to define variables could be a bad idea. Consider this:
c :: Int
c = 7

f x | x == F c  = "Hi"
    | otherwise = "there"

Now, is the c in F c a new local variable which is defined on the spot, or is it the constant 7 defined above? If we call f (F 6) do we get Hi (c was a new variable) or there (c was 7)?
Pattern matching avoids this issue by requiring a distinct syntax.


text:
Q: How I can fix "iio-sensor-proxy" detect orientation problem? I am a Arch Linux user and I have a  Laptop that has a built in sensor to detect orientation .and according this sensor the screen will be rotate. but the main problem here is that this sensor detect wrongly. this mean when I turn on my Laptop the screen has been rotated to right 90 deg. How I can solve this problem?

A: You can change the way orientation is detected by using a matrix to switch axes and orientations with systemd. You will find a really good documentation at systemd github project.


text:
Q: I am trying to run AVD with react-native, but an unknown variable error appears I am trying to run the code created through react-native as AVD in android studio, but I am getting an error about the variable JAVA_HOME. What should I do?
ERROR: JAVA_HOME is set to an invalid directory: C:\Program Files\Java\jdk1.8.0_131

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

A: Sometime we need to manually set the path (environment) of JAVA_JDK . Install latest JAVA JDK from official website. And set the path of jre and bin folder. After looking your directory C:\Program Files\Java\jdk1.8.0_131 I guess you are on windows , So I'm not sure how to set environment variable for windows but definitely you could get help from youtube.


text:
Q: Metric and Connection I have read and heard that there are several theories of gravity and Quantum Gravity which treat the metric (defining rods and clocks) and connection (defining free fall equation of geodesic) of the manifold as independent quantities. I know that the Levi-Civita connections are given as,
$$
\Gamma_{\mu\nu}^{\alpha}=\frac{1}{2}g^{\alpha\delta}(g_{\mu\delta,\nu}+g_{\nu\delta,\mu}-g_{\mu\nu,\delta})
$$
But in this case, the connection is uniquely determined by the metric tensor. However, as I see it, the converse is not true (that is the metric cannot be uniquely determined by a given Levi-Civita connection).
So,
Given that the Levi-Civita connection can be uniquely determined by the metric tensor, does this fact ascribe certain general properties to the manifold? Hence, by violating these properties of the manifold, one can find other mathematical forms of connection which can be uniquely determined by the metric tensor.

A: The Levi-Civita connection (or Christoffel symbols) are coming from the metric compatibility constraint :
$$\tag{1}
\nabla_{\lambda} \, g_{\mu \nu} = 0,$$
plus the "desire" to get a symetrical connection : $\Gamma_{\mu \nu}^{\lambda} = \Gamma_{\nu \mu}^{\lambda}$.  This last commandement is arbitrary, and is only justified to get the simplest theory possible (i.e classical General Relativity).  If you remove the symetrical constraint but only imposes equ (1), you then get the Levi-Civita connection and a contorsion tensor :
$$\tag{2}
\Gamma_{\mu \nu}^{\lambda} = \frac{1}{2} \, g^{\lambda \kappa} \, (\, \partial_{\mu} \, g_{\nu \kappa} + \partial_{\nu} \, g_{\mu \kappa} - \partial_{\kappa} \, g_{\mu \nu}) + K^{\lambda}_{\mu \nu}.
$$
The antisymetrical part $T^{\lambda}_{\mu \nu} \equiv \Gamma_{\mu \nu}^{\lambda} - \Gamma_{\nu \mu}^{\lambda}$ is the torsion tensor, which is assumed to vanish in GR.  This guy is not 0 in the Einstein-Cartan theory, which is the natural extension of GR (a bit more general than GR).
Some theories consider that the connection is an independant variable when they don't impose the symetric constraint, or even the compatibility (1) above.


text:
Q: Regex for specific format I'm a newbie at using regex in c# and I'm trying to use it to validate a phone number with this format 09oxoxxxxxx where x can be any number and o can be only 1-9 and the total length should be 11 numbers. Here's what I think which is probably wrong.
if (Regex.IsMatch("09203041152", "^[0]{1}[9]{1}[1-9]{2}[1-9]{1}[0-9]{6}"))

A: You can use shorthand character \d which represents any number [0-9]:
Regex.IsMatch("09203041152", @"^09[1-9]\d[1-9]\d{6}$")

Your patter is not working due to repetitions count {2} here:

^[0]{1}[9]{1}[1-9]{2}[1-9]{1}[0-9]{6}

That requires two non-zero numbers in a row. But you need one non-zero number and one any number at this place:

^[0]{1}[9]{1}[1-9]{1}[0-9]{1}[1-9]{1}[0-9]{6}

Note - you don't need to specify repetitions count equal to {1}, because that means single token occurrence, which is true without specifying that explicitly.

A: Your regular expression is a bit more complex that it needs to be:
^09[1-9][0-9][1-9][0-9]{6}$

*

*^: Match the start-of-line.

*09: Matches the number 0 followed by 0.

*[1-9]: Matches any number between 1 and 9.

*[0-9]: Matches any number between 0 and 9.

*[1-9]: Again matches any number between 1 and 9.

*[0-9]{6}: Matches any number between 0 and 9 six times.

*Now the total number of digits matched is 11.

A: The following RegExp should match the format you stated '09oxoxxxxxx'
^09[1-9][0-9][1-9][0-9]{6}$

A: Try this:
^09[1-9][0-9][1-9][0-9]{6}


text:
Q: How to add 2 different times in VBA? I need to convert from GMT to UTC time and would like to add the 2 different times.
Here is the code that I have currently :
Dim CurDate, Correction, UTCTime As Date
CurDate = Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")
UTCTime = DateAdd("h", 4.5, CurDate)

However it is adding only the integer part of the hours i.e., 4 and not 4.5
Any idea, how to achieve this ?

A: try this
UTCTime = DateAdd("n", 4.5 * 60, CurDate)

A: In Excel, the integer part of a date is days, so adding 4.5 hours would be adding 4.5/24
UTCTime = CurDate + 4.5 / 24


text:
Q: How to get all my google business account reviews using PHP (curl) I need to get my google business account reviews . I have used  place API method
$parameters = "key=$api_key&placeid=$place_id";
$place_id = trim($place_id,' ');
$api_key = trim($api_key,' ');
$url = "https://maps.googleapis.com/maps/api/place/details/json?key=$api_key&placeid=$place_id";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close($ch);
$res = json_decode($result,true);
return $res;

Its return only top  5 reviews . But I need to get all my business reviews . So that I go for below  link "https://mybusiness.googleapis.com/v3/accounts/account_name/locations/location_name/reviews"  .
Here how shall I find  account_name and location_name , then what are parameter (like access token,and so on) to pass for execute curl. Please help to get all my business reviews .


text:
Q: Validating guice module configuration - how to use the SPI? I'm writing a framework that uses Guice to bootstrap a server, and so I've extended Guice's AbstractModule to create a Module that provides some convenience methods for users to configure their code. However, I want to to check that the configuration is sane before launching the code. So it has to go somewhere in here:
// here, before the injector is created?
Injector injector = Guice.createInjector(someModule);
// here, after configure() is called?
Object something = injector.getInstance(SomeServer.class);
// start the server

It seems that there's not much I can check before the injector is created because the modules are not configure()ed yet. There is some mention of using the Guice SPI to validate module configuration, but the documentation is not too clear. Can someone, who uses Guice, give a short description on the best practices for validating modules before injectors are used?

A: I haven't experienced much of this first-hand, but it seems to me that you have three choices:

*

*Refactor to MyConvenienceMethodModule.myConfigure() and MyConvenienceMethodModule.validate() if your convenience methods are expressive enough to provide useful information without ever running configure(). In theory you could call Module.configure(Binder) with a mock, but with Guice's EDSL that's far too complex; use ElementVisitor (below) instead.

*Call Elements.getElements() on a particular Module to check on the binding status. Because the elements might be of a variety of types, you'd probably want to create an ElementVisitor instead (probably by creating a subclass of DefaultElementVisitor to insulate you from future Elements yet to be created). This way you get a good view of all bindings, even bindings in Guice's EDSL, while still in the context of the Module. I think this is your best bet.

*Create your Injector as usual and call getAllBindings() to investigate it. This is probably your best option if your configuration's sanity depends on  how multiple modules interact, rather than how individual modules are structured. If you only check at this point, you won't really be able to tell one Module from another.


text:
Q: pandas crashes on repeated DataFrame.reset_index() Very weird bug here: I'm using pandas to merge several dataframes.  As part of the merge, I have to call reset_index several times.  But when I do, it crashes unexpectedly on the second or third use of reset_index.
Here's minimal code to reproduce the error:
import pandas
A = pandas.DataFrame({
    'val' :  ['aaaaa', 'acaca', 'ddddd', 'zzzzz'],
    'extra' : range(10,14),
})
A = A.reset_index()
A = A.reset_index()
A = A.reset_index()

Here's the relevant part of the traceback:
....
    A = A.reset_index()
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2393, in reset_index
    new_obj.insert(0, name, _maybe_cast(self.index.values))
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 1787, in insert
    self._data.insert(loc, column, value)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/internals.py", line 893, in insert
    raise Exception('cannot insert %s, already exists' % item)
Exception: cannot insert level_0, already exists

Any idea what's going wrong here?  How do I work around it?

A: Inspecting frame.py, it looks like pandas tries to insert a column 'index' or 'level_0'.  If either/both(??) of them are already taken, then it throws the error.
Fortunately, there's a "drop" option.  AFAICT, this drops an existing index with the same name and replaces it with the new, reset index.  This might get you in trouble if you have a column named "index," but I think otherwise you're okay.
"Fixed" code:
import pandas
A = pandas.DataFrame({
    'val' :  ['aaaaa', 'acaca', 'ddddd', 'zzzzz'],
    'extra' : range(10,14),
})
A = A.reset_index(drop=True)
A = A.reset_index(drop=True)
A = A.reset_index(drop=True)

A: you can use :
A.reset_index(drop=True, inplace=True)


text:
Q: Average from two different table using group by I have a table Called DEPARTMENTS with Columns:
DepartmentID
DepartmentName
Another table Called EMPLOYEE with Columns:
EmployeeID
DepartmentID
EmployeeName
Salary
I need a JOIN query with possibly Group By to display DepartmentName and AVERAGE Salary
Basically the Output should display:
DepartmentX  40000
DepartmentY  15000
DepartmmentZ 35000

A: You need to use AVG() aggregate function with JOIN between two tables like
SELECT d.DepartmentName,
AVG(e.Salary) as average_salary
FROM Employee e
JOIN DEPARTMENTS d ON e.DepartmentID = d.DepartmentID
GROUP BY e.DepartmentID;

(OR) get the average first and then perform a JOIN like
SELECT d.DepartmentName,
xx.average_salary
FROM DEPARTMENTS d
JOIN (
select DepartmentID, AVG(Salary) as average_salary
from Employee
GROUP BY DepartmentID) xx  ON xx.DepartmentID = d.DepartmentID;


text:
Q: Can we have access to the statistical information about click behavior on Stack Exchange? Is there a way to get statistical info about click behavior on SE? What links do SE users visit: Questions, tags, StackExchange, User page, ... When, in what sequence?
This info would be of great help to formulate / test Graphical User Interface changes on SE.
Joel wrote about Usability Testing, and SE doesn't need that as they already have the log files that can be mined (by their trusted worker, not by outsiders).
To be specific, I'd like to know the number of times somebody clicks on StackExchange and then on Inbox (to establish the clickonomics proposal). As this data is already available to the SE dev team, it could be mined.
Edit It would be nice to have that statistical info available so people can look for other improvements as well.


text:
Q: C# extension method "overloading" Take a look at the following code
namespace OverLoadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong value = 10;

            var foo = new Foo();
            foo.DoStuff(value);
        }
    }

    public class Foo
    {
        public void DoStuff(float value)
        {
            // This is the resolved overload even if we have an extension method that takes ulong
        }
    }

    public static class FooExtensions
    {
        public static void DoStuff(this Foo foo, ulong value)
        {

        }
    }
}

Can someone explain why the extension method taking an ulong is not invoked here?


text:
Q: Parsing a document in a table How do I parse a document in a table and send it across as a JSON file to another db.
Detailed Desc:
I have crawled and taken data into a table from websites using anemone. I need to now parse it and transfer it as a JSON file to another server. I think, I will have to first convert the document in the table into nokogiri document which can be parsed and converted to json file. Any idea how can I convert the doc into nokogiri document or if anyone has any other idea to parse it and send it as a json file ?

A: Nokogiri is your best bet for the HTML parsing, but as for converting it to JSON you're on your own from what I can tell.
Once you have it parsed via Nokogiri it shouldn't be terribly hard to extract the elements you need and generate JSON that represents them. What you're doing isn't a very common task, so you'll have to bridge the gap between Nokogiri and whichever gem you're using to generate the JSON.

A: Okay I found the answer long time back,  I basically made use of REST to send message form one application to another, i sent it across as a hash. And the obvious one, I used nokogiri for parsing the table.
def post_me
     @page_hash = page_to_hash

    res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3007/element_data/save.json'),@page_hash)
  end

For sending the hash from one application to another using net/http.
def page_to_hash
    require 'rubygems'
    require 'nokogiri'
    require 'open-uri'
    require 'domainatrix'

    #page = self.page.sub(/^<!DOCTYPE html(.*)$/, '<!DOCTYPE html>')
    hash={}
    doc = Nokogiri::HTML(self.page)
    doc.search('*').each do |n|
      puts n.name
    end

Using Nokogiri for parsing the page table in my model. page table had the whole body of a webpage.
file_type = []

    file_type_data=doc.xpath('//a/@href[contains(. , ".pdf") or contains(. , ".doc")
                          or contains(. , ".xls") or contains(. , ".cvs") or contains(. , ".txt")]')
    file_type_data.each do |href|
      if href[1] == "/"
        href = "http://" + website_url + href
      end
      file_type << href
    end
file_type_str = file_type.join(",")
    hash ={:head => head,:title => title, :body => self.body,
      :image => images_str, :file_type => file_type_str, :paragraph => para_str, :description => descr_str,:keyword => key_str,
      :page_url=> self.url, :website_id=>self.parent_request_id, :website_url => website_url,
      :depth => self.depth, :int_links => @int_links_arr, :ext_links => @ext_links_arr
    }

A simple parsing example and how i formed my hash.


text:
Q: remote notification on ios I'm trying to send a remote notification from own php server to app.
Here's the code in AppDelefate.m:
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate ()

@end

@implementation AppDelegate

#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [self registerForRemoteNotifications];
    return YES;
}

- (void)registerForRemoteNotifications {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
            if(!error){
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            }
        }];
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSLog(@"User Info : %@",notification.request.content.userInfo);
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

//Called to let your app know which action was selected by the user for a given notification.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
    completionHandler();
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"%@", userInfo);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"%@", userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)applicationDidFinishLaunching:(UIApplication *)app {
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

// Handle remote notification registration.
- (void)application:(UIApplication *)app
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    NSString *token = [[devToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"content---%@", token);
}

- (void)application:(UIApplication *)app
didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Remote notification support is unavailable due to error: %@", err);
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

@end

When I run the app, it ask for notification privilege, after accepted. Console print the following token:
content---13eeb8d33de4f0ba55f520469f9b0970e973faa6904a38428b2193b04ac3782b

So I use this token in my PHP server for testing:
<?php
// Put your device token here (without spaces):
$deviceToken = '13eeb8d33de4f0ba55f520469f9b0970e973faa6904a38428b2193b04ac3782b';

// Put your private key's passphrase here:
$passphrase = 'xoxoxo';

// Put your alert message here:
$message = 'Test push.';

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'BDSPKCertificates.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
var_dump($ctx);

// Open a connection to the APNS server
$apns = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); // production

echo "
Open Connection
";
if(!$apns)
{
    echo "
Failed to connect!
Error Number: " . $err . "
Code: " . $errstr . "
";
    return;
}
else
{
    echo "
Connected
";

    // Create the payload body
    $body = array();
    $body['aps'] = array(
        "title"=>"Test title",
        'alert' => $message,
        'sound' => 'default',
        'badge' => 1
        );

    // Encode the payload as JSON
    $payload = json_encode($body);

    echo "
Message: ";
    print_r($payload);
    echo "
";

    // Build the binary notification
    $msg = chr(0) . pack("n",32) . pack('H*',str_replace(' ', '', $deviceToken)) . pack ("n", strlen($payload)) . $payload;

    // Send it to the server
    $result = fwrite($apns, $msg, strlen($msg));

    if (!$result)
    {
        echo 'Message not delivered' . PHP_EOL;
    }
    else
    {
        echo 'Message successfully delivered' . PHP_EOL;
    }

    // Close the connection to the server
    fclose($apns);
}

?>

When i run this PHP code, it prints the following:
resource(2) of type (stream-context)
Open Connection

Connected

Message: {"aps":{"title":"Test title","alert":"Test push.","sound":"default","badge":1}}

Message successfully delivered

However my app receive nothing. Please help me to find what is missing in my codes. Thanks.

A: please confirm, you have open 2195 port in server firewall. Apple push notification sent via 2195 port. So it should open.

A: I think you are using sandbox environment but in your PHP script your socket client is production, use sandbox for development like below.
Sandbox
ssl://gateway.sandbox.push.apple.com:2195'

// Open a connection to the APNS server
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); // sandbox

Production
ssl://gateway.push.apple.com:2195'

// Open a connection to the APNS server
$apns = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); // production


text:
Q: Why does lm generate NA for each independent variable? I tried to make a linear regression with the lm function, but the output is NA for every independent variable. The dataframe is numeric.
I have already tried to change the independent variable and only use one dependent variable, but the result was the same.
# Read csv file
gh_old_shorty <- read.csv(file.choose(), header=T, sep=";")

# make dataframe numeric
as.data.frame(lapply(gh_old_shorty, as.numeric))

# create linear regression
model1 <- lm(Year ~ Age +  OfficeOfPresidency + MembersOfParliament +
     Assembly + GovernmentOfficials + LocalGovernmentOfficials + JudgesAndMagistrates + FightingCorruption, data=gh_old_shorty, na.action = na.omit)
summary(model1)

Call:
lm(formula = Year ~ Age + OfficeOfPresidency + MembersOfParliament +
    Assembly + GovernmentOfficials + LocalGovernmentOfficials +
    JudgesAndMagistrates + FightingCorruption, data = gh_old_shorty,
    na.action = na.omit)

Residuals:
ALL 1 residuals are 0: no residual degrees of freedom!

Coefficients: (8 not defined because of singularities)
                         Estimate Std. Error t value
(Intercept)                  2007         NA      NA
Age                            NA         NA      NA
OfficeOfPresidency             NA         NA      NA
MembersOfParliament            NA         NA      NA
Assembly                       NA         NA      NA
GovernmentOfficials            NA         NA      NA
LocalGovernmentOfficials       NA         NA      NA
JudgesAndMagistrates           NA         NA      NA
FightingCorruption             NA         NA      NA
                         Pr(>|t|)
(Intercept)                    NA
Age                            NA
OfficeOfPresidency             NA
MembersOfParliament            NA
Assembly                       NA
GovernmentOfficials            NA
LocalGovernmentOfficials       NA
JudgesAndMagistrates           NA
FightingCorruption             NA

Residual standard error: NaN on 0 degrees of freedom


text:
Q: Stoilow Theorem I want to see the precise statement and a proof for a theorem of Stoilow on "inner" functions (I do not know what this exactly means, I suppose it is an open map with other natural properties). A vague statement is this:
An inner function is a continuous deformation of a holomorphic function.
I am looking for a simple version rather than the most general one.
Any accessible reference is welcome (I understand Romanian).
Thanks in advance.

A: First of all, it seems that every author has his own favourite definition of "inner mapping". The best thing would probably be to adopt the one used by Martin Jurchescu: a continuous, open, zero-dimensional mapping.
Stoilow's theorem says, then, that if $\phi : R \to S^2$ is a map from a Hausdorff, connected topological surface $R$ to the Riemann sphere $S^2$, then the following are equivalent:

*

*$\phi$ is an interior mapping

*$\phi$ behaves locally like the mapping $\{ |z| \le 1 \} \ni z \mapsto z^n \in \{ |z| \le 1 \}$

*there exist a unique Weyl-Rado Riemann surface on $R$ such that $\phi$ becomes a holomorphic mapping.

To make things a bit confusing, the article about "inner mapping" on the Springer encyclopedia of mathematics gives a slightly different statement of the theorem.
For more details, check "Analysis and Topology: A Volume Dedicated to the Memory of S Stoilow" (World Scientific, 1998), pages 420-421.

A: I'm a bit late to the party but I thought I'd offer my two cents both to Stoilow's theorem and on some related terminology.
Stoilow's theorem is one of the more classical results in my field, and even though I rarely use it, it gets mentioned a lot. ("In dimension two problem X is completely understood due to Stoilow's theorem.") A bit over a year ago me and my then adviser were talking that it might be beneficial to study the proof of the theorem to see if it could be applied in a more general setting. What we learned that there were very few sources from where the proof could be found. Long story short - we decided it would be beneficiary to write up an exposition containing a self-contained proof of the theorem. This can now be found from arXiv: 1701.05726. (Note that there are several different theorems that people call Stoilow's theorem. Our exposition focuses on results found in Stoilow's 1928 paper and what Whyburn calls Stoilow's theorem in his book Topological Analysis.)
The mappings Stoilow is interested in the 1928 paper are mappings $f \colon \Sigma \to \Sigma'$ between topological surfaces which are

*

*continuous,

*open (images of open sets in $\Sigma$ are open in $\Sigma'$), and

*light (pre-image of any point $y \in \Sigma'$ is totally disconnected).

As Alex.M mentioned in their answer, some authors use the term "inner map" to mean this class of mappings. Some other authors use the term "inner mapping" to describe mappings for which the image of any open set in the domain is open in the image of the mapping.  (Another term for this I've seen is quasi-open.) For example the plane map  $\mathbb{R}^2 \to \mathbb{R}^2$, $(x,y) \mapsto (|x|,y)$ is, with this terminology, a quasi-open map but not an open one.
One of the first things Stoilow proves is that continuous, open and light mappings are in fact discrete, i.e. the pre-image of any point $y \in \Sigma'$ is discrete. Such continuous, open and discrete mappings are called branched covers by many authors, but this term is used also for different, but related, types of mappings; see e.g. Aaltonen or Bonk-Meyer. I would advice to be careful when reading papers about either inner maps or branched covers since the definitions vary slightly. (This makes it sometimes hard to read older papers since the authors' might not explicitly state which definition they are using.)
In modern times there seems to be, from my subjective point of view, more interest in continuous, open and discrete mappings than in continuous, open and light mappings. Some reasons for this shift of interest seem to be:

*

*Stoilow's theorem. All planar continuous, open and light maps are discrete).

*Results of Church-Hemmingsen stating that between Euclidean domains of equal dimension, a topologically orientable continuous, light and open map is, in fact, discrete.

*Reshetnyak's theorem stating that a quasiregular mapping between Riemannian $n$-manifolds is a continuous, open and discrete map.

For more details I suggest looking at previously mentioned exposition by me and Pekka Pankka, we tried to make it as reader friendly as possible.


text:
Q: Django - Unable to lookup 'u' yesterday everything was working perfect, today i enter to the admin and this error is showing when i click in "usuarios_aux" model...
Unable to lookup 'u' on Usuario_aux or Usuario_AuxAdmin
Why is this happening? heres the traceback.

Environment:
Request Method: GET Request URL:
  http://provisional.jetint.webfactional.com/admin/clients/usuario_aux/
Django Version: 1.7.3 Python Version: 2.7.9 Installed Applications:
  ('django.contrib.admin.apps.SimpleAdminConfig',
  'django.contrib.auth',  'django.contrib.contenttypes',
  'django.contrib.sessions',  'django.contrib.messages',
  'django.contrib.staticfiles',  'adminplus',  'clients',  'currier')
  Installed Middleware:
  ('django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware')
Template error: In template
  /home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/contrib/admin/templates/admin/change_list.html, error at line 91    Unable to lookup 'u' on Usuario_aux or
  Usuario_AuxAdmin    81 :         {% endif %}
82 :       {% endblock %}
83 :
84 :       {% csrf_token %}
85 :       {% if cl.formset %}
86 :         {{ cl.formset.management_form }}
87 :       {% endif %}
88 :
89 :       {% block result_list %}
90 :           {% if action_form and actions_on_top and
  cl.full_result_count %}{% admin_actions %}{% endif %}
91 :            {% result_list cl %}
92 :           {% if action_form and actions_on_bottom and
  cl.full_result_count %}{% admin_actions %}{% endif %}
93 :       {% endblock %}
94 :       {% block pagination %}{% pagination cl %}{% endblock %}
95 :
96 :
97 :
98 : {% endblock %}
99 :
Traceback: File
  "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/core/handlers/base.py"
  in get_response
    137.                 response = response.render() File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/response.py"
  in render
    103.             self.content = self.rendered_content File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/response.py"
  in rendered_content
    80.         content = template.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    148.             return self._render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in _render
    142.         return self.nodelist.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    844.                 bit = self.render_node(node, context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/debug.py"
  in render_node
    80.             return node.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/loader_tags.py"
  in render
    126.         return compiled_parent._render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in _render
    142.         return self.nodelist.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    844.                 bit = self.render_node(node, context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/debug.py"
  in render_node
    80.             return node.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/loader_tags.py"
  in render
    126.         return compiled_parent._render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in _render
    142.         return self.nodelist.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    844.                 bit = self.render_node(node, context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/debug.py"
  in render_node
    80.             return node.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/loader_tags.py"
  in render
    65.                 result = block.nodelist.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    844.                 bit = self.render_node(node, context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/debug.py"
  in render_node
    80.             return node.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/loader_tags.py"
  in render
    65.                 result = block.nodelist.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    844.                 bit = self.render_node(node, context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/debug.py"
  in render_node
    80.             return node.render(context) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/template/base.py"
  in render
    1207.                     _dict = func(*resolved_args, **resolved_kwargs) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/contrib/admin/templatetags/admin_list.py"
  in result_list
    307.     headers = list(result_headers(cl)) File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/contrib/admin/templatetags/admin_list.py"
  in result_headers
    101.             return_attr=True File "/home/jetint/webapps/jet_test/lib/python2.7/Django-1.7.3-py2.7.egg/django/contrib/admin/utils.py"
  in label_for_field
    324.                 raise AttributeError(message)
Exception Type: AttributeError at /admin/clients/usuario_aux/
  Exception Value: Unable to lookup 'u' on Usuario_aux or
  Usuario_AuxAdmin

how i can fix this?
model:
class Usuario_aux(models.Model):
    user = models.ForeignKey(User)
    clave = models.CharField(max_length=100)
    correo = models.BooleanField(default=False)

admin.py:
class Usuario_AuxAdmin(admin.ModelAdmin):
    list_display = ('user', 'correo')
    search_fields = ('user', 'correo')
admin.site.register(Usuario_aux, Usuario_AuxAdmin)


text:
Q: String truncation when using PreparedStatement and SetString with SQL Server I'm trying to use PreparedStatement and setString to insert data into a TEXT field of a SQL Server DB.  The statement is something like this:
PreparedStatement p = con.prepareStatement("insert into comments(comments) VALUES (?)");
p.setString(1, comment);

The insert is working correctly but being truncated after 200-some characters.  An error is not thrown.  I can't find reference to this being the case anywhere else.  It's definitely coming from the Java side, I've tested longer inserts into the SQL db directly.
Ideas? Is there a way I could convert the string to a different data type maybe?


text:
Q: Pointers and online change in TwinCAT and CoDeSys Are pointers safe against online change of running PLC program in TwinCAT 2.10 and in CoDeSys 2.3 on which the first one is based? What happens if memory block gets reallocated as part of online program change and there are pointers pointing to that memory block?

A: ADR (Address Operator) description in TwinCAT's help says:
Attention:
After an Online Change there might be changes concerning the data on certain addresses. Please regard this in case of using pointers on addresses.
It looks to me like pointers cannot be stored permanently if someone pretends to use online modification of the program. Otherwise if pointers are stored (for example as a binding between some data structures) online change should be avoided.


text:
Q: class library using asp.net ComponentModel.Annotations causes errors Well so far asp.net 5 is really time wasting and aggravating, even for simple tasks.
I was trying to write a domain model for a new project using asp.net5, since thats where we are supposedly heading.
Writing simple enums worked fine UNTIL I wrote some classes that needed them and some of those properties needed ComponentModel Annotations.
So when I used the helper to add that reference WOW WTF

Of course once I take that dependency out of the project.json it reruns to normal. Obviously I need the Annotations, so how do you add them since clearly the automatic way VS2015 is doing it isn't right, thus creating all these errors. Well the answer, from a lot of googling, appears to be that the dependency is "System.ComponentModel": "4.0.0.0", and it gets added in the dnxcore50 dependencies NOT where VS added its dependency. BUT that doesnt work, the Annotations still err!

A: The vNext web project has a dependency on Microsoft.AspNet.Mvc. Change this:
"dependencies": {
    "System.ComponentModel.Annotations": ""
},
to

"dependencies": {
     "Microsoft.DataAnnotations":  "" //use whatever latest version is
}