text:
Q: pygame - Scrolling down page My program in a nutshell is a Contacts App, which obviously means that a person needs to be able to store a number of contacts in the app, which in turn means that contacts are going to eventually go "off" the screen, so I need to be able to scroll down the page so that a person can see all their contacts and interact with a specific contact.
However, I'm in a bit of pickle... how do I do this? The problems I'm facing is that the app is a fixed width and height so I can't scroll down the page only to find that the background is going to be black because my rectangle was only sized to be as long as the apps window length. The other problem is I just don't know how to 'push' the screen up. I just have no idea.
Here is the code for the program so far:
import pickle
import operator
import pygame
import sys
from pygame.locals import *
from itertools import groupby

#create Contact class
class Contact():
    def __init__(self, firstName, lastName, address, groupType,
                 telephone, mobile, email, photoField):
        self.firstName = firstName
        self.lastName = lastName
        self.address = address
        self.groupType = groupType
        self.telephone = telephone
        self.mobile = mobile
        self.email = email
        self.photoField = photoField

    def showDetails(self):
        print("First Name:\t", self.firstName)
        print("Last Name:\t", self.lastName)
        print("Address:\t", self.address)
        print("Telephone:\t", self.telephone)
        print("Mobile:\t", self.mobile)
        print("Email:\t", self.email)

    @classmethod
    def from_input(cls):
        firstName = input("First Name: ")
        lastName = input("Last Name: ")
        address = input("Address: ")
        telephone = input("Telephone: ")
        mobile = input("Mobile: ")
        email = input("Email: ")
        return cls(firstName, lastName, address, None,

                   telephone, mobile, email, None)

class AddressBook():
    def __init__(self):
        self.contactsList = pickle.load(open("save.p", "rb"))

    def addContact(self, contact = None):
        if contact is None:
            contact = Contact.from_input()
        self.contactsList.append(contact)
        pickle.dump(self.contactsList, open("save.p", "wb"))

    def delContact(self, contact = None):
        if contact is None:
            search = input("Search: ")
            for i in self.contactsList:
                if (i.firstName.lower() == search.lower()) or (i.lastName.lower() == search.lower()):
                    indexed = self.contactsList.index(i)
                    del self.contactsList[indexed]
                    pickle.dump(self.contactsList, open("save.p", "wb"))
                elif (i.firstName.lower() != search.lower()) or (i.lastName.lower() != search.lower()):
                    continue

    def contactInfo(self, contact = None):
        if contact is None:
            search = input("Search: ")
            print()

            #display contact information
            for i in self.contactsList:
                if (i.firstName.lower() == search.lower()) or (i.lastName.lower() == search.lower()):
                    i.showDetails()
                    print()
                elif (i.firstName.lower() != search.lower()) or (i.lastName.lower() != search.lower()):
                    continue
                else:
                    print("No contacts\n")

    def contactSearch(self, contact = None):
        if contact is None:
            search = input("Search: ")
            print()

            for i in self.contactsList:
                if (i.firstName.lower() == search.lower()) or (i.lastName.lower() == search.lower()):
                    print(i.firstName, i.lastName)
                    print()
                elif (i.firstName.lower() != search.lower()) or (i.lastName.lower() != search.lower()):
                    continue
                else:
                    print("No contacts\n")

class Page():
    def __init__(self, screen = pygame.display.set_mode((320, 480)), caption = pygame.display.set_caption("Contacts")):
        self.screen = screen
        self.caption = caption

    def style(self):
        pygame.draw.rect(self.screen, (171,0,0), (0,0,320,63), 0)
        pygame.draw.rect(self.screen, (230,230,230), (0,63,320,417), 0)
        pygame.draw.line(self.screen, (120,0,0), (5,61), (320, 61), 2)

class MainPage(Page):
    def __init__(self, screen = pygame.display.set_mode((320, 480)), caption = pygame.display.set_caption("Contacts"), title = "Contacts"):
        Page.__init__(self, screen, caption)
        self.title = title

    def style(self):
        Page.style(self)
        titleFont = pygame.font.SysFont("trebuchet ms", 38)
        textSurface = titleFont.render(self.title, True, (255,255,255))
        self.screen.blit(textSurface, (5, 18))
        AddButton().shape()

    def printContacts(self):
        addressBook = AddressBook()
        addressBook.contactsList
        addressBook.contactsList.sort(key = lambda c: (c.lastName, c.firstName) if c.lastName else (c.firstName, ""))
        contactFont = pygame.font.SysFont("trebuchet ms", 18)
        y = 80

        for (key, g) in groupby(addressBook.contactsList, lambda c: c.lastName[0] if c.lastName else c.firstName[0]):
            groupName = contactFont.render(key, True, (171,0,0))
            self.screen.blit(groupName, (5, y))
            pygame.draw.line(self.screen, (0,0,0), (5,(y+20)), (320, (y+20)), 1)
            y += 30

            for i in g:
                name = i.firstName + " " + i.lastName
                textName = contactFont.render(name, True, (0,0,0))
                pygame.draw.line(self.screen, (210,210,210), (5,(y+20)), (320, (y+20)), 1)
                self.screen.blit(textName, (5, y))
                y += 30

class AddPage(Page):
    def __init__(self, screen = pygame.display.set_mode((320, 480)), caption = pygame.display.set_caption("Contacts"), title = "Add Contact"):
        Page.__init__(self, screen, caption)
        self.title = title

    def style(self):
        Page.style(self)
        titleFont = pygame.font.SysFont("trebuchet ms", 38)
        textSurface = titleFont.render(self.title, True, (255,255,255))
        self.screen.blit(textSurface, (5, 18))
        AddButton().shape()
        CancelButton().shape()

class Button():
    def __init__(self, screen = pygame.display.set_mode((320, 480))):
        self.screen = screen

    def shape(self):
        pygame.draw.rect(self.screen, (120,0,0), (270,12,40,40), 0)

class AddButton(Button):
    def __init__(self, screen = pygame.display.set_mode((320, 480))):
        Button.__init__(self, screen)

    def shape(self):
        Button.shape(self)
        pygame.draw.line(self.screen, (255,255,255), (289, 15), (289,48), 2)
        pygame.draw.line(self.screen, (255,255,255), (272, 31.5), (307, 31.5), 2)

class CancelButton(Button):
    def __init__(self, screen = pygame.display.set_mode((320, 480))):
        Button.__init__(self, screen)

    def shape(self):
        pygame.draw.rect(self.screen, (120,0,0), (245,20,25,25), 0)
        pygame.draw.aaline(self.screen, (255,255,255), (252,32.5), (263,26))
        pygame.draw.aaline(self.screen, (255,255,255), (252,32.5), (263,39))

pygame.init()
page = MainPage()
page.style()
page.printContacts()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEBUTTONUP and event.button == 1 and isinstance(page, MainPage):
            if (pygame.mouse.get_pos() >= (270,13)) and (pygame.mouse.get_pos() >= (270,53)) and (pygame.mouse.get_pos() <= (309,13)) and (pygame.mouse.get_pos() <= (309,53)):
                page = AddPage()
                page.style()
        elif event.type == MOUSEBUTTONUP and event.button == 1 and isinstance(page, AddPage):
            if (pygame.mouse.get_pos() >= (270,13)) and (pygame.mouse.get_pos() >= (270,53)) and (pygame.mouse.get_pos() <= (309,13)) and (pygame.mouse.get_pos() <= (309,53)):
                page = MainPage()
                page.style()
                page.printContacts()
            elif (pygame.mouse.get_pos() >= (245,20)) and (pygame.mouse.get_pos() >= (245,45)) and (pygame.mouse.get_pos() <= (370,20)) and (pygame.mouse.get_pos() <= (370,45)):
                page = MainPage()
                page.style()
                page.printContacts()

    pygame.display.update()

    addressBook = AddressBook()
    addressBook.contactsList
    addressBook.contactsList.sort(key = lambda c: (c.lastName, c.firstName) if c.lastName else (c.firstName, ""))

    print("-------------------\nContacts\n")
    for i in addressBook.contactsList:
        print(i.firstName, i.lastName)
    print()

    print("Menu:\n\n1. Add Contact\n2. Show Contact Details\n3. Edit Contact\n4. Delete Contact\n5. Search Contact\n-------------------\n")

    choice = input()
    print()

    if choice == "1":
        #add contacts

        contact = AddressBook().addContact()

    elif choice == "2":
        contact = AddressBook().contactInfo()

    elif choice == "4":
        contact = AddressBook().delContact()

    elif choice == "5":
        contact = AddressBook().contactSearch()

    else:
        continue

I apologise for the mixture of pygame code and raw python code, as I still haven't fully transitioned the shell code into code that's usable by pygame. So contact entries etc are still done via the Shell/console. I first want to complete the main screen before I move on to actually being able to pass inputs via pygame.

A: As furas already said in a comment, it's better to use a GUI framework like Tkinter or PyQt etc., especially since text input will be a major PITA for you if you stick with pygame. There are some widget libraries for pygame, but they all suck IMHO compared to a "real" GUI framework.
Nonetheless, there's an easy way to add scrolling to your application. Instead of drawing your stuff directly to the screen, blit it to an intermediate Surface that is higher than the screen Surface. If you want to scroll down, just blit this intermediate Surface "above" the screen Surface.
Here's a simple example of scrolling with a mouse wheel:
import pygame
import string

pygame.init()

screen = pygame.display.set_mode((300, 300))
intermediate = pygame.surface.Surface((300, 600))
i_a = intermediate.get_rect()
x1 = i_a[0]
x2 = x1 + i_a[2]
a, b = (255, 0, 0), (60, 255, 120)
y1 = i_a[1]
y2 = y1 + i_a[3]
h = y2-y1
rate = (float((b[0]-a[0])/h),
         (float(b[1]-a[1])/h),
         (float(b[2]-a[2])/h)
         )
for line in range(y1,y2):
     color = (min(max(a[0]+(rate[0]*line),0),255),
              min(max(a[1]+(rate[1]*line),0),255),
              min(max(a[2]+(rate[2]*line),0),255)
              )
     pygame.draw.line(intermediate, color, (x1, line),(x2, line))

y = 20
f = pygame.font.SysFont('', 17)
for l in string.ascii_uppercase:
    intermediate.blit(f.render(l, True, (255, 255, 255)), (10, y))
    y += 20

clock = pygame.time.Clock()
quit = False

scroll_y = 0

while not quit:
    quit = pygame.event.get(pygame.QUIT)
    for e in pygame.event.get():
        if e.type == pygame.MOUSEBUTTONDOWN:
            if e.button == 4: scroll_y = min(scroll_y + 15, 0)
            if e.button == 5: scroll_y = max(scroll_y - 15, -300)

    screen.blit(intermediate, (0, scroll_y))
    pygame.display.flip()
    clock.tick(60)


text:
Q: How to allow an editor to edit all WordPress blog posts but have the last say as administrator? I run a simple WordPress setup hosted on SiteGround with no staging area and no special roles. The blog grew so much over the last few years that I barely write any content anymore.
I send a content brief and outline (Google Docs) for each article to the assigned writer, and they write the article on WordPress. I check, proof, edit, illustrate, and schedule or publish.
I am soon to hire an editor who will do all of the above. However, I feel weird giving so much power to somebody remote in a different country over my content. They could add malicious/paid-for links to existing content, and so on.
How can they "publish" every edit –even to published posts and pages– but not show the updated version publically, just yet. Changes would need to be reviewed manually by myself and confirmed, or rollbacked.
Any way of doing this? This is especially difficult for people editing currently published content.

A: You can use User Role Editor plugin and edit or add new user rule.
User Role Editor WordPress plugin allows you to change user roles and capabilities easy.
Just turn on check boxes of capabilities you wish to add to the selected role and click "Update" button to save your changes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in Pivot query I have the following query
 DECLARE @query NVARCHAR(4000)
DECLARE @Days NVARCHAR(4000)
SELECT  @Days = STUFF((SELECT DISTINCT
                        '],[' + ltrim(str(datepart(dw,visitdate)))
                        FROM    mktPlanHospitals
                        ORDER BY '],['  + ltrim(str(datepart(dw,visitdate)))
                        FOR XML PATH('')                        ), 1, 2, '') + ']'

SET @query =
'SELECT * FROM
(
    SELECT DoctorID,datepart(dw,visitdate),DoctorID
    FROM mktPlanHospitals
)t
PIVOT (SUM(DoctorID) FOR datepart(dw,visitdate)
IN ('+@Days+')) AS pvt'

EXECUTE (@query)

It is giving me error
Incorrect syntax near '('.

A: You can't order by a field not specified in your SELECT, if you use the DISTINCT keyword. One distinct value could have several values to order it by, thus there could be no correct order.
Blog entry about the error.

A: Here is the working query that solves the problem
DECLARE @query NVARCHAR(4000)
DECLARE @Days NVARCHAR(4000)
SELECT  @Days = STUFF((SELECT DISTINCT
                        '],[' + ltrim(str(datepart(dw,visitdate)))
                        FROM    mktPlanHospitals
                        ORDER BY '],['  + ltrim(str(datepart(dw,visitdate)))
                        FOR XML PATH('')                        ), 1, 2, '') + ']'

SET @query =
'SELECT * FROM
(
    SELECT DoctorID,datepart(dw,VisitDate) as vdate
    FROM mktPlanHospitals
)t

PIVOT (SUM(DoctorID) FOR vdate
IN ('+@Days+')) AS pvt'

EXECUTE (@query)


text:
Q: Bound on $\|A^+ z - z\|$ where $A^+$ is the Moore-Penrose inverse of the matrix $A\in \mathbb{R}^{n\times m}$ My question
Can we get any bound (depending on $A$ and $z$) of $\|A^+ z - z\|$, where $A^+$ is the Moore-Penrose inverse of the matrix $A\in \mathbb{R}^{n\times n}$ ?
Details
Actually this question came from a problem I have: Given $z^\star\in \mathbb{R}^n$, I must find $\underset{z\in \text{Im} A}{\text{argmin}} \|z-z^\star\|$ (or the min), and I thought that $A^+z^\star$ could be a good candidate, or at least a good approximation.
Then I saw here (Two questions on the Moore–Penrose inverse) that the Moore-Penrose inverse "finds the lowest norm solution of $\|Ax-z^\star\|$". So it seems that this is the solution. But then can we have a bound on the error we make?
Could someone help ?

A: The Moore-Penrose inverse can be used to obtain least squares solution to the linear system $Ax \approx b$, in the sense $x_{\mathrm{LS}} := A^{\dagger} b$ is such that $x_{\mathrm{LS}} = \mathrm{argmin}_{x \in \mathbb{R}^{m}} \Vert Ax - b \Vert_2$. So the closest vector in $\mathrm{im}(A)$ to $b$ is actually $Ax_{\mathrm{LS}} = A A^{\dagger} b$. (The matrix $A A^{\dagger}$ is actually the orthogonal projection matrix onto the range of $A$; see Moore-Penrose inverse.)
In your case, you are trying to approximate $Az \approx z^{\star}$, so the closest vector in the range of $A$ to $z$ is actually $A A^{\dagger} z^{\star}$. (As mentioned in the comment, this only makes sense if $n = m$.) We have $\Vert A A^{\dagger} z^{\star} - z^{\star} \Vert_2 = \Vert (I - A A^{\dagger}) z^{\star} \Vert_2$. This is the norm of the component of $z^{\star}$ in the kernel of $A^T$ (the orthogonal complement of the range of $A$). If $A$ is full rank, then clearly this is zero since $z^{\star} \in \mathrm{im}(A)$. So suppose that $A$ is not full rank for non-triviality. Then we have the trivial bound $\Vert A A^{\dagger} z^{\star} - z^{\star} \Vert_2 \leq \Vert z^{\star} \Vert_2$, which is achieved if $z^{\star} \in \mathrm{ker}(A^T)$.
I'm not sure if we can give a more precise bound in terms of $A$ and $z$.


text:
Q: Can't we assign a value that starts with 0(zero) to a variable ? example: a=0123. This throws error "invalid token" I'm trying to convert that data type to string. Even that's not working.
Example: str(0123)
But this is possible a="0123".
My complete assumption is 0123 is not accepted because it is octal not an integer. So, octal are not allowed in python. Please correct me if i'm wrong.

A: You're looking for 0o123. Numbers that start with only a zero, which is not the only symbol in the token, are invalid syntax.


text:
Q: What is the point of this ( reverse ) assignment / matching in this Elixir function My only guess is that it is for verifying that it is a struct. otherwise what does %User{}= user do?
def change_user(%User{} = user) do
  User.changeset(user, %{})
end

It comes from the Phoenix framework and various generators etc...
Thanks in advance.

A: Yup, that will just verify that the input can be matched to/is a %User{} struct and nothing else.
The point of it is to identify bugs (by static program analysis) or force runtime errors/crashes so your program won't do anything harmful (hopefully).

A: It might help if you think of it more as type-hint.  Although it is a pattern match, the syntax here reminds me of other languages (e.g. PHP, Python, or Go) that put data types in the function signatures.
But since it's Elixir, it IS a pattern match, and it is an idiomatic way to communicate the intent of that particular function clause or to set yourself up to define other function clauses.  For example, imagine these function clauses defined alongside the example you provided:
def change_user(%LegacyUser{} = legacy_user) do
  LegacyUser.changeset(legacy_user, %{})
end

def change_user(arg) do
  Logger.error("Unsupported argument given to change_user/1: #{inspect(arg)}")
end

Although functionally, it doesn't matter if you do %User{} = user or user = %User{}, it is more idiomatic to use the former.


text:
Q: How to Prove a Riemann Surface is Hyperbolic by Showing its Volume Grows Exponentially? We have a Holomorphic Foliation by curves on a Complex Manifold. Therefore, every leaf is a Riemann Surface.
Let $R$ be a Riemann Surface.
We say that the Riemann Surface $R$ is Hyperbolic if and only if one of the two following equivalent conditions is satisfied:

*

*$R$ is isomorphic to a quotient of the Upper Half-Plane by a Fuchsian Group.

*Its covering space is isomorphic to the Hyperbolic Disk.

Meanwhile, it is mentioned that to prove that the Riemann Surface $R$ is Hyperbolic it is sufficient to prove its volume grows exponentially.
What does that mean?
(Or, How to define the Volume of the Riemann Surface $R$, and to find out whether or not the volume grows exponentially?).

A: I'll use the word "area" instead of "volume", since we are in 2 dimensions.
The Uniformization Theorem implies that there exists a complete Riemannian metric on $R$ in the given conformal class with constant curvature $\kappa = -1$, $0$ or $+1$. Furthermore, that metric is unique if $\kappa = -1$ or $+1$, and it is unique up to scaling if $\kappa = 0$. Area on $R$ is defined using the area form of that metric.
In the case $\kappa = 1$, $R$ is a sphere and has finite area.
In the case $\kappa = 0$, $R$ is either a torus which has finite area, a cylinder which has linearly growing area, or the Euclidean plane which has quadratically growing area.
It follows that if the area of $R$ grows exponentially then $\kappa = -1$.


text:
Q: Can't run test function in GoLand: cannot find package "." I have used VS Code as my code editor for building service using Go for almost one year. Then, I tried to switch to GoLand. But, when I tried run a test function there is an error: cannot find package "." What is the problem?
Note: I use go module as go dependency management tool. When I use dep (in another project), there is no error when running a test function. My project is in GOPATH.

A: Please make sure there's a valid go.mod file defined at the ROOT of your project i.e. in $GOPATH/src/<Project-name>.
If you don't have, you can create one using go mod init command using the shell. More information on the same - https://github.com/golang/go/wiki/Modules
After that please try running the test from the shell. First cd into the directory where the test file is present. Then, use go test . -test "<TestName>" -v to run your test. If the issue goes away, you can run the test from IDE and it should work fine.


text:
Q: Delete items from woocommerce breadcrumbs Right now I have the following structure in the breadcrumbs of woocommerce:
HOME / SHOP / MAINCAT / SUBCAT / SUBCAT

And what I want is that it looks like this:
MAINCAT / SUBCAT / SUBCAT

It would remove the link from the home and the woocommerce store page.
Can you help?

A: function jk_woocommerce_breadcrumbs()
{
    return [
        'delimiter'   => ' / ',
        'wrap_before' => '<nav class="woocommerce-breadcrumb" itemprop="breadcrumb">',
        'wrap_after'  => '</nav>',
        'before'      => '',
        'after'       => '',
        'home'        => _x('', 'breadcrumb', 'woocommerce'),
    ];
}
add_filter('woocommerce_breadcrumb_defaults', 'jk_woocommerce_breadcrumbs');

A: woocommerce->global->breadcrumb.php
if(count($breadcrumb)>3){
    $breadcrumb = array_merge(array_slice($breadcrumb, 0, 1, false),array_slice($breadcrumb, -2, 2, false));
}


text:
Q: Filter json with set and map using nested attributes I am working with some json returned via an API call and trying to figure if it's possible to filter one json object based on the values from another.  I came across set and map which is close, but not sure how to handled the nested attributed... here is a simplified example:
var teachers = [
{id: 1, name : 'Bob',studentid: []},
{id: 2, name : 'Sue',studentid: []},
{id: 3, name : 'Jean',studentid: []},
{id: 4, name : 'Jim',studentid: [
    "500zz"
]},
{id: 5, name : 'Paul',studentid: [
    "100zz",
    "120zz",
    "130zz"
]}
];

var students = [
{_id: "100zz", name : 'Betty'},
{_id: "120zz", name : 'Bob'},
{_id: "500zz", name : 'Billy'}
];

console.log(
  teachers.filter(
    (set => item => set.has(item.studentid))(new Set(students.map(item => item._id)))
  )
)

I would like the result to include only the teachers Jim and Paul ( with all associated data )... not sure what I need to add or do?  The array of studentid's is throwing me for a loop.

A: const teachers = [
  { id: 1, name: "Bob", studentid: [] },
  { id: 2, name: "Sue", studentid: [] },
  { id: 3, name: "Jean", studentid: [] },
  { id: 4, name: "Jim", studentid: ["500zz"] },
  { id: 5, name: "Paul", studentid: ["100zz", "120zz", "130zz"] }
];

const students = [
  { _id: "100zz", name: "Betty" },
  { _id: "120zz", name: "Bob" },
  { _id: "500zz", name: "Billy" }
];

// Filter teachers with students greater than 0.
const filtered = teachers.filter(x => x.studentid.length > 0);

// Map teachers with Students
const teachersWithStudents = filtered.map(x => {
  const stu = students
    .map(student => {
      // Determine whether or not teacher 'studentid' contains student '_id'
      const hasStudent = x.studentid.includes(student._id);
      // Teacher has student
      if (hasStudent) {
        return {
          id: student._id,
          name: student.name
        };
      }
      // Teacher does not have student
      return false;
    })
    .filter(x => x); // filter objects that are not false
  // Return teacher object with student (stu) objects
  return {
    ...x,
    studentid: stu
  };
// Return those with matches only
}).filter(x => x.studentid.length > 0);

console.log(teachersWithStudents);


text:
Q: How to pronounce word 'rather' in American English? When I'm checking the pronunciation of the word 'rather', it seems that the letter 'a' has two different pronunciations in American English. First one is same like letter 'a' in 'father', and the second one is like letter 'a' in word 'bat'. Which one is the most common one that people normally use?

A: The most common way in American English is like the "a" in "bat".
Here's an audible example.


text:
Q: Static no Django Galera,
Queria um conselho ou ajuda sobre os 'static' no 'Django', meus arquivos que estao na pasta 'Static" eles nao vem ser carregados apresentando os seguintes erros abaixo:
    System check identified no issues (0 silenced).
December 30, 2020 - 15:49:40
Django version 3.1.4, using settings 'core.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[30/Dec/2020 15:49:47] "GET / HTTP/1.1" 200 6889
[30/Dec/2020 15:49:47] "GET /static/js/plugins/plugins.js HTTP/1.1" 404 1689
[30/Dec/2020 15:49:47] "GET /static/js/bootstrap/popper.min.js HTTP/1.1" 404 1704
[30/Dec/2020 15:49:47] "GET /static/site.css HTTP/1.1" 404 1650
[30/Dec/2020 15:49:47] "GET /static/js/active.js HTTP/1.1" 404 1662
[30/Dec/2020 15:49:47] "GET /static/js/jquery/jquery-2.2.4.min.js HTTP/1.1" 404 1713
[30/Dec/2020 15:49:47] "GET /static/js/bootstrap/bootstrap.min.js HTTP/1.1" 404 1713
[30/Dec/2020 15:49:47] "GET /static/img/core-img/pizza.png HTTP/1.1" 404 1692
[30/Dec/2020 15:49:47] "GET /static/static/img/bg-img/foto_receita.png HTTP/1.1" 404 1728
[30/Dec/2020 15:49:47] "GET /static/img/core-img/logo.png HTTP/1.1" 404 1689
[30/Dec/2020 15:49:47] "GET /static/js/bootstrap/popper.min.js HTTP/1.1" 404 1704
[30/Dec/2020 15:49:47] "GET /static/js/bootstrap/bootstrap.min.js HTTP/1.1" 404 1713
[30/Dec/2020 15:49:47] "GET /static/js/plugins/plugins.js HTTP/1.1" 404 1689
[30/Dec/2020 15:49:47] "GET /static/js/active.js HTTP/1.1" 404 1662

Na minha pasta settings.py esta da seguinte maneira
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '/static')
]

e minha urls.py esta assim:
urlpatterns = [
    path('',include('receitas.urls')),
    path('admin/', admin.site.urls),
] #+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Alguem que ja passou por isso que possa dar uma luz ?

A: Após fazer o deploy da aplicação, você precisa executar o comando:
python manage.py collectstatic

Assim os dados da pasta static serão copiados nos lugares devidos (configurados em seu settings.py) .
Segue a referência do collectstatic do django.


text:
Q: Sorting the Pandas DataFrame Describe output (early solutions do not work) I am trying to sort the describe of a dataframe, read several helps posts on very similar matter, but I can no make it work.
My three lines of code go like this:
df1 = myDataset.groupby(['country_code'])['country_code','score'].describe()

with pd.option_context('display.max_rows', None, 'display.max_columns', None):

display(df1)
display(df1.reset_index())
display(df1.reset_index().sort_values('count', ascending=False))

First display shows :
    score
count   mean    std min 25% 50% 75% max
country_code
AE  10.0    10.000000   31.622777   0.0 0.00    0.0 0.00    100.0
AM  1.0 0.000000    NaN 0.0 0.00    0.0 0.00    0.0
AO  5.0 0.000000    0.000000    0.0 0.00    0.0 0.00    0.0
...

second display goes:
    country_code    score
count   mean    std min 25% 50% 75% max
0   AE  10.0    10.000000   31.622777   0.0 0.00    0.0 0.00    100.0
1   AM  1.0 0.000000    NaN 0.0 0.00    0.0 0.00    0.0
2   AO  5.0 0.000000    0.000000    0.0 0.00    0.0 0.00    0.0
...

and the third raise an error:
KeyError                                  Traceback (most recent call last)
<ipython-input-28-855a7c54543c> in <module>()
      6       display( df1.reset_index() )
      7
----> 8       display( df1.reset_index().sort_values('count', ascending=False) )

1 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in _get_label_or_level_values(self, key, axis)
   1561             values = self.axes[axis].get_level_values(key)._values
   1562         else:
-> 1563             raise KeyError(key)
   1564
   1565         # Check for duplicates

KeyError: 'count'

Not sure what I am doing difrerently than other solutions as:
Sorting the Pandas DataFrame Describe output

A: df1.sort_values([('score','count')], ascending=False)

thanks @ilkyun-im


text:
Q: Output of this command Linux Please do anyone has an idea about the output of this command , I have googled a lot about it but I can't find anything useful
find . -type f -exec grep -H PATH {} \;

Thanks in advance

A: The command
find . -type f -exec grep -H PATH {} \;

finds all regular files (-type f) in the current directory (.) or below, and for each such file executes grep -H PATH {} with  {}  replaced by the full pathname of the file relative to the current directory.
The -H option to grep is non-standard but often implemented, and makes sure that each matching line is prefixed by the pathname of the file that the line was found in.  You could change the command to grep PATH /dev/null {} instead to force grep to always output the pathname of the file that contains the matching lines (standard grep does this when at least two files are given on the command line).
The pattern used with grep is the string PATH.
To summarize: The command finds and outputs all lines from all regular files in the current directory or below, that mention the substring PATH anywhere.  Each line is prefixed by the pathname of the file that contains the line.
A snippet of the output that I get when running this in my personal home directory:
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_NM:FILEPATH=/usr/bin/nm
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_OBJCOPY:FILEPATH=/usr/bin/objcopy
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_OBJDUMP:FILEPATH=/usr/bin/objdump
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_RANLIB:FILEPATH=/usr/bin/ranlib
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_SKIP_INSTALL_RPATH:BOOL=NO
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_SKIP_RPATH:BOOL=NO
./Documents/Pathfinder/build/CMakeCache.txt:CMAKE_STRIP:FILEPATH=/usr/bin/strip

The command could be made more efficient by letting grep run on as many files as possible at once, in batches, instead of once for each file:
find . -type f -exec grep -F -e PATH /dev/null {} +

I've also taken the liberty to change the grep command slightly here by adding -F so that it treats the string PATH as a string rather than as a regular expression.  The -e option is just used for indicating that the next argument is the pattern (useful if the pattern is later changed to something that may start with a dash, for example).
It's the change from \; to + at the end of the -exec predicate's argument that makes it collect the found pathnames into batches instead of running the utility for each and every one.


text:
Q: Return void or any other type with Typescript Can i do this ? its possible ?
If no, has an alternative method to do this ?
ngOnInit():  void | Observable<TModel> {
//return bla bla bla
}

A: Yes, it's possible.
An alternative is to have a return type of Observable<TModel> | undefined, which will work well with strict null checks:
function myFunction(): string | undefined {
    return Math.random() < 0.5 ? "" : undefined;
}

const myString = myFunction();
myString.charAt(0);  // error
myString!.charAt(0); // ok

if (typeof myString === "string") {
    myString.charAt(0); // ok
}


text:
Q: How to copy paste in ubuntu server using virtualbox So I'm using virtualbox and I want to copy paste a command, how do I do that and is that possible in Ubuntu Server 22.04?
Like I'm on Windows 10 and I have a command that I want to use on Ubuntu Server, I open Virtual Box Open ubuntu and if I try ctrl+c ctrl+v it doesn't work, if I try ctrl+SHIFT+c or ctrl+SHIFT+v it doesn't work too. Is there a way to do copy paste in Ubuntu Server 22,.4?


text:
Q: How to create a group on an existing HDF5 file? (HDF5) I have a 3rd party utility written in C++ that creates an HDF5 file with a single data group.
I would like to import two H5 files each with a unique data group, and output a single H5 file with the two data groups.
Does anyone have experience with working with HDF5 in C#?

A: I ended up just writing a command line utility that drives the precompiled HDF5 utilities.  Using H5Copy you can selectively copy groups from one h5 file to another.


text:
Q: main function in c - program termination success or failure As far as I understand if the main function returns 0 this indicates always successful program termination. Even if success is indicated by another int value.
If main returns a non-zero value it is implementation specific if this stands for unsuccessful program termination or another error code

If the value of status is zero or EXIT_SUCCESS, an
  implementation-defined form of the status successful termination is
  returned.  If the  value of status is EXIT_FAILURE, an
  implementation-defined form of the status unsuccessful termination
  is returned.   Otherwise the status  returned is
  implementation-defined.)

So only success is defined in the C standard (return 0) and not how a non-zero int value is interpreted, right? E.g. if in a certain system 1 stands for "success" return 0 would be deliver 1 as well? How is this done?

A: The main function is the entry point to your code, it is not the entry point to the executable. The executable contains an operating-system defined entry point, that runs some startup code before calling main.
main is called from the startup code just like a normal function. The return value from main is received by the startup code, which can perform any translations necessary to conform to the requirements of the operating system.
The startup code is specific to each operating system. Operating systems have requirements concerning the operation and environment of executables. The C language has requirements concerning the environment that the C code runs in (specifically the arguments to main and the return value from main). It's the responsibility of the startup code to bridge the gaps between those two sets of requirements.
The startup code is delivered as an object file, commonly called "crt.o", short for "C runtime". That file is included in the executable by the linker. You can find the actual name of that file by examining the linker command line. The startup file is typically the first file on the linker command line.


text:
Q: How do I change my e-mail on Stack Overflow? How to change email from Stack Overflow to another email?
How to unlink your Facebook account?
I tried to unlink it from the Facebook application and even delete it from the Stack Overflow profile, once it was removed from both sites, I log in as a new user with the email and the same profile appears.
In Stack Exchange, there is no way to modify it.
I looked into this question's solutions, but they do not work: How can I change my Stack Exchange login email?


text:
Q: Dropdown jQuery Menu with these effects? Ive been looking for a jQuery menu with a slide down effect like Yoothemes.
http://www.yootheme.com/demo/
Notice on the theme the submenu toggles or slides down.
I'm aware of the jQuery superfish menu which is ideal but the effects are slightly different.
http://users.tpg.com.au/j_birch/plugins/superfish/
Help appreciated.
Kind Regards

A: Are you asking how to change the effect from fading in and out to sliding down and up?
Because they are different animations.
$("object").fadeIn(500);
$("object").fadeOut(500);

vs
$("object").animate({top:0}, 500);
$("object").animate({top:'-'+$(this).css(height)}, 500);


text:
Q: MVC Scaffolding - Quick and Easy way to implement Paging? I am developing an ASP.NET MVC 4 application using MVC scaffolding.
Currently it returns all rows in a single fetch and displays them in the grid. However, I want to implement paging within the same so that it doesn't create any problem when the data are in large volume.
Any idea of how can we implement paging quick and easy way in MVC 4?

A: This link helped me to find out the proper way for paging, sorting and filtering.


text:
Q: Convert JSON object with duplicate keys to JSON array I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
For example
Input
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}

Output
{
"a":"b",
"c":["d","e"],
"f":"g"
}

The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
If possible, I'd like to do this without editing any library code

A: As of today the org.json library version 20170516 provides accumulate() method that stores the duplicate key entries into JSONArray
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("a", "b");
jsonObject.accumulate("c", "d");
jsonObject.accumulate("c", "e");
jsonObject.accumulate("f", "g");
System.out.println(jsonObject);

Output:
{
    "a":"b",
    "c":["d","e"],
    "f":"g"
}

A:
I want to remove the repeated keys by combining their values into an array.

Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into Map<String, List<String>> without using any library.
Sample code:
String jsonString = ...
// remove enclosing braces and double quotes
jsonString = jsonString.substring(2, jsonString.length() - 2);

Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String values : jsonString.split("\",\"")) {
    String[] keyValue = values.split("\":\"");
    String key = keyValue[0];
    String value = keyValue[1];

    if (!map.containsKey(key)) {
        map.put(key, new ArrayList<String>());
    }
    map.get(key).add(value);
}

output:
{
  "f": ["g"],
  "c": ["d","e"],
  "a": ["b"]
}

A: In order to accomplish what you want, you need to create some sort of custom class since JSON cannot technically have 2 values at one key. Below is an example:
public class SomeClass {

Map<String, List<Object>> values = new HashMap<String, List<Object>>();

public void add(String key, Object o) {
    List<Object> value = new ArrayList<Object>();
    if (values.containsKey(key)) {
        value = values.get(key);
    }
    value.add(o);
    values.put(key, value);
}

public JSONObject toJson() throws JSONException {
    JSONObject json = new JSONObject();
    JSONArray tempArray = null;

    for (Entry<String, List<Object>> en : values.entrySet()) {
        tempArray = new JSONArray();
        for (Object o : en.getValue()) {
            tempArray.add(o);
        }
        json.put(en.getKey(), tempArray);
    }

    return json;
}
}

You can then retrieve the values from the database, call the .add(String key, Object o) function with the column name from the database, and the value (as the Object param). Then call .toJson() when you are finished.

A: Thanks to Mike Elofson and Braj for helping me in the right direction. I only wanted to have the keys with multiple values become arrays so I had to modify the code a bit. Eventually I want it to work for nested JSON as well, as it currently assumes it is flat. However, the following code works for what I need it for at the moment.
public static String repeatedKeysToArrays(String jsonIn) throws JSONException
{
    //This assumes that the json is flat
    String jsonString = jsonIn.substring(2, jsonIn.length() - 2);

    JSONObject obj = new JSONObject();
    for (String values : jsonString.split("\",\"")) {
        String[] keyValue = values.split("\":\"");
        String key = keyValue[0];
        String value = "";
        if (keyValue.length>1) value = keyValue[1];

        if (!obj.has(key)) {
            obj.put(key, value);
        } else {
            Object Oold = obj.get(key);
            ArrayList<String> newlist = new ArrayList<String>();

            //Try to cast as JSONArray. Otherwise, assume it is a String
            if (Oold.getClass().equals(JSONArray.class)) {
                JSONArray old = (JSONArray)Oold;
                //Build replacement value
                for (int i=0; i<old.length(); i++) {
                    newlist.add( old.getString(i) );
                }
            }
            else if (Oold.getClass().equals(String.class)) newlist = new ArrayList<String>(Arrays.asList(new String[] {(String)Oold}));
            newlist.add(value);

            JSONArray newarr = new JSONArray( newlist );
            obj.put(key,newarr);
        }
    }
    return obj.toString();
}


text:
Q: i got error from console while making loginPage but i don't know what's wrong (React.js)

import React,{useState} from "react";
import {connect} from "react-redux";
import {loginUser} from '../../actions/user_action'
function RegisterLogin() {
  const [loginData, setLoginData] = useState({
    email: "",
    password: "",
    errors: [],
  });

  const displayErrors = (errors) => {
    errors.map((error,i)=>
{error}
)
  }

  const handleChange = (e) => {

    setLoginData({[e.target.name]: e.target.value});
  }

  const submitForm = (e) => {
    e.preventDefault();
    let dataToSubmit ={
      email: loginData.email,
      password: loginData.password
    }
    if (isFormValid(loginData)){
      setLoginData({errors: []});
      this.props.dispatch(loginUser(dataToSubmit))
      .then(response => {console.log(response)})

    }
  }

  const isFormValid = ({email,password}) => email&&password;

  return (

Login

        <form className="column s12">

            {/* email */}
            <input
              name="email"
              value={loginData.email}
              onChange={e=>{handleChange(e)}}
              id="email"
              type="email"
              className="validate"
              placeholder="Email"
            />

             {/* password */}

            <input
              name="password"
              value={loginData.password}
              onChange={e=>{handleChange(e)}}
              id="password"
              type="password"
              className="validate"
              placeholder="Password"
              autoComplete="off"
            />

          {/* errormessages */}
           {loginData.errors.length >0 &&(

              {displayErrors(loginData.errors)}

          )}

         {/* buttons */}

              <button
              className="btn waves-white black brighten-2"
              type="submit"
              name="action"
              onSubmit={submitForm}
              >
                Login
              </button>

        </form>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.i need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logoi need a logo

  );
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

export default connect(mapStateToProps)(RegisterLogin);

above is my code. and whenever i try to write on input tag I keep getting this error message:
TypeError: Cannot read property 'length' of undefined
RegisterLogin
src/components/RegisterLogin/index.js:43
  40 |

  41 |
Login

  42 |   <form className="column s12">
> 43 |

     | ^  44 |

  45 |       {/* email */}
  46 |       <input

However I have no clue about this error, can you inform me what is wrong?
thx for reading, your help will be appreciated
p.s when i remove errors property in state and also remove
{loginData.errors.length >0 &&(

              {displayErrors(loginData.errors)}

this code at least i can type something on input value but with those code i even can't type a single alphabet even tho i used handleChange function as onclick event on input tag

A: From what you have posted here, I would say the most likely issue is that loginData.errors is undefined when you attempt to evaluate the .length property of it.  Since there is no undefined.length, you get a TypeError.
The quickest way around this would be to use the optional chaining operator (?.) when getting those properties so that the code will simply move on when it can't find the property:
{loginData?.errors?.length >0 && (

    {displayErrors(loginData.errors)}

)}


text:
Q: rsyslog: regex extract between 2 strings I want to extract a substring of msg field between 2 strings.
Example of the log: Test local logging: db=testdb,message
What I want is "testdb", so, the string between "db=" and ","
This is my configuration:
template(name="jsonTemplate"
         type="list"
         option.json="on") {
           constant(value="{")
             constant(value="\"timestamp\":\"")      property(name="timereported" dateFormat="rfc3339")
             constant(value="\",\"message\":\"")     property(name="msg")
             constant(value="\",\"host\":\"")        property(name="hostname")
             constant(value="\",\"severity\":\"")    property(name="syslogseverity-text")
             constant(value="\",\"facility\":\"")    property(name="syslogfacility-text")
             constant(value="\",\"syslogtag\":\"")   property(name="syslogtag")
             constant(value="\",\"database\":\"")    property(name="msg" regex.expression="(db=)(.*)(,)" regex.match="0" regex.type="ERE")
           constant(value="\"}")
         }

However, the result I got is: "db=testdb,", but I don't want "db=" and "," to appear.
I've tested several regex but didn't worked:
(?<=db=)(.*)(?=,)  --> this works in https://regex101.com
I don't understand why the regex doesn't work.
Version: rsyslogd: version 8.24.0

A: Found the solution using the submatch 2:
property(name="msg" regex.expression="(db=)(.*)(,)" regex.submatch="2" regex.type="ERE")


text:
Q: Improving multi-label loss function Trying to train a CNN on a multilabel problem, each image can have 0, 1, 2 or 3 labels assigned to it. The number of labels is not known a priori. I figured the standard loss function for such problem is the sigmoid cross entropy (as opposed to the softmax cross entropy, which would only be appropriate for single class problems). For example, in TensorFlow one would use sigmoid_cross_entropy_with_logits.
I did that, but found my network to not converge much beyond some trivial level. Looking in more detail at the errors made, I found my network to perform well on examples with 0 or 1 labels while performing badly on examples with more than 1 label. In fact, there is a strong correlation between the number of labels in an example and the cross-entropy loss.
The picture below shows the cross entropy for 64 test samples, color coded for how many labels they were supposed to have. I consider everything with a loss of less than 0.3 a "pretty good" result. Clearly examples with 0 or 1 label are "pretty good" and more labels get progressively worse.

The question is, what can I do to improve my cost function? What can there be possibly wrong? It must be a fairly generic problem as many of these cat and dog classifiers allow multiple classes/labels.
The four categories (0,1,2,3 labels) are about equally represented in the training data. This related question does not answer beyond "use sigmoid cross entropy".


text:
Q: Android webview javascript Interface not working properly Really do not have any ideal why this doesn't work. Basically, I am trying to do this.
 public void testJS() {
        final WebView webView = (WebView) findViewById(web);
//        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JSInterface(webView), "sample");
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        /* Do whatever you need here */
                Log.e("chrome", "asdf");
                return super.onJsAlert(view, url, message, result);
            }

        });
        webView.loadUrl("javascript:window.sample.doEchoTest();void(0);");
    }

and this is the JSInterface
   public class JSInterface {
        WebView mAppView;

        public JSInterface(WebView appView) {
            this.mAppView = appView;
        }

        public void doEchoTest() {
            Log.e("sample", "test details");
            Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

the javascript code never runs.
basic functions like alert works :
webView.loadUrl("javascript:alert('sample')");

why is webView.loadUrl("javascript:window.sample.doEchoTest();void(0);");
not working ?

A: Just browsing for a different answer, a guess at this would be that you haven't exposed it to be accessible from JS. You need to do so explicitly for each method as so:
@JavascriptInterface
public void doEchoTest() {
            Log.e("sample", "test details");
            Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
            toast.show();
        }


text:
Q: Getting corner coordinates of polygon on a grid I have a problem in which I need to calculate the coordinates of all corners in a given polygon. The information I have available is a list of tiles/squares within that shape. The shape is always made out of these squares and always aligns exactly on the grid. Two examples of these kinds of shapes are as follows:
Two examples
Taking the first example shape, I would like to know the coordinates of the corners represented by the dots in the following image:
Example 1 with corners dots
The exact information I have available is a list of all the squared tiles that are in that shape. They are represented by their most bottom-left corner. So in example 1, I have the following information:
$$(0,0); (0,1); (0,2); (0,3); (1,0); (1,1); (1,2); (1,3); (2,0); (2,1); (2,2); (3,0); (3,1); (3,2); (4,2); (5,2); (5,3)$$
I tried to iterate the list and remove the inside squares so that I only have the outer ones left. Then I would take all the maximum and minimum values. The problem then, is that I only get the four most outer corners and not the corners in the middle of the shape.
Anyone know a good way to approach this?

A: *

*Compute the set of outer edges (an square edge is outer edge if it delimits present square from absent)

*Order the edges by some graph walking algorithm, say, bfs.

*From the ordered set of outer edges compute the desired points as the turning points (when previous edge do not have the same direction as the next one).

import copy
from collections import deque
from PIL import Image, ImageDraw
s=('(0,0);(0,1);(0,2);(0,3);(1,0);(1,1);(1,2);(1,3);(2,0);(2,1);(2,2);'
   '(3,0);(3,1);(3,2);(4,2);(5,2);(5,3)')
s=[tuple(int(j) for j in i.strip('()').split(',')) for i in s.split(';')]
mx,my=[max(i[j] for i in s) for j in [0,1]]
im=Image.new('RGB',(20*(mx+2),20*(my+2)),(255,255,255))
draw=ImageDraw.Draw(im)
for x,y in s:
    draw.rectangle(tuple(i*20+10 for i in [x,y,x+1,y+1]),
                   fill=(192,192,192),outline=None,width=0)

borders=lambda x,y:[frozenset([(x+a,y+b),(x+c,y+d)])
    for (a,b),(c,d),(e,f) in [
        ((0,0),(0,1),(0,-1)),
        ((0,0),(1,0),(-1,0)),
        ((1,0),(1,1),(0,1)),
        ((0,1),(1,1),(1,0)),
         ]
    if (x+f,y+e) not in s]
edges=sum((borders(*i) for i in s),[])
for e in edges:
    draw.line(tuple(i*20+10 for i in [j for p in e for j in p]),
              fill=(0,0,0),width=1)
#im.show()
adjacent=lambda x,y:[(x+i,y+j) for i,j in
                     [(1,0),(0,1),(-1,0),(0,-1)]]
def bfs(s):
    res,res_p=[],[]
    s=copy.copy(s)
    s_taken=set()
    #assuming 1 connected component
    for x in s:break
    s.remove(x)
    res.append(x)
    p=list(x)[0]
    res_p.append(p)
    q=deque([p])
    #print(p)
    while q:
        p=q.popleft()
        for p1 in adjacent(*p):
            e=frozenset([p,p1])
            if e in s:
                q.append(p1)
                s.remove(e)
                res.append(e)
                res_p.append(p1)
                break
    return res,res_p

ordered_edges,ordered_points=bfs(set(edges))
orientation=lambda x:(lambda y:y[0][0]==y[1][0])(list(x))
res=[]
for e1,p,e2 in zip(ordered_edges,
                   ordered_points,
                   ordered_edges[1:]+ordered_edges[:1]):
    if orientation(e1)!=orientation(e2):
        res.append(p)

for x,y in res:
    draw.ellipse((20*x+10-2,20*y+10-2,20*x+10+2,20*y+10+2),
                 fill=(0,0,255))
im.show()

Try it online


text:
Q: How to prevent sub panel from popping up over my current activity I'm creating an app for FTV and having an intermittent issue where I press and hold menu button on remote, a subpanel is created over our current window. This sub panel contains no children, thus invisible. But when the subpanel appears, it gets the focus and D-pad buttons "stop working"(presumably the input commands are going to subpanel but since subpanel contains nothing, it appears as if our app is frozen until we press back button to dismiss the subpanel.
I have tried setting several flags for the windoe window.addFlags(WindowManager.LayoutParams.TYPE_APPLICATION) or window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) or window.addFlags(WindowManager.LayoutParams.LAST_APPLICATION_WINDOW)
WIthout subpanel
$ adb shell dumpsys window | grep -E "mCurrentFocus"
   mCurrentFocus=Window{f40d919 u0 com.amazon.myApp/com.amazon.myApp.activities.MainActivity}

With subpanel
$adb shell dumpsys window | grep -E "mCurrentFocus"
   mCurrentFocus=Window{4df66a3 u0 SubPanel:com.amazon.myApp/com.amazon.myApp.activities.MainActivity}

Is there a way to disable/prevent subpanels in my activities?


text:
Q: Comparing data in different structure I have a string
string cubeinline = "12345123451234X1234512345";

which is equal to a List<string>
List<string> cube = new List<string>(){ "12345",
                                        "12345",
                                        "1234X",
                                        "12345",
                                        "12345"};

But different arranged. The string is split by length. In this case 5.
Now i need to compare the string with the List - char by char. But my method says every char is invalid.
int maxLength = 5;
for (int i = 0; i < cubeinline.Length; i++)
{
    if (cubeinline[i] == cube[i / maxLength][i % maxLength])
    {
        Console.WriteLine("Error in char" + i);
    }
}

A: Change == into !=. You inverse the logic here: the program should display the message when there is a difference, not an equlity!

A: you can do it like this:
string cubeinline = "12345123451234X1234512345";
List<string> cube = new List<string>(){ "12345",
                                    "12345",
                                    "1234X",
                                    "12345",
                                    "12345"};
bool isEqual = cubeinline == string.Concat(cube);

A: I use LINQ for this purpose usually. In this approach you are using the SequenceEqual method which checks two sequences (one is cube and one is Splitted string into 5 size) and checks whether two sequences are equal by comparing the elements or not:
bool res = cube.SequenceEqual(Enumerable.Range(0, cubeinline.Length / 5)
    .Select(i => cubeinline.Substring(i * 5, 5)));

A: Change your if condition to
if ( cubeinline[i] != cube[i / maxLength][i % maxLength] )
{
    Console.WriteLine ("Error in char" + i);
}

OR please add else condition,
if ( cubeinline[i] == cube[i / maxLength][i % maxLength] )
{
    Console.WriteLine ("Match found at " + i);
}
else
{
    Console.WriteLine ("Error in char" + i);
}

A: What is the reasoning for storing the strings in a list? Even if you must keep them in the list, you can use a string temp variable to combine the strings in the list into a single string, then use the String.Equals method to compare your string and the temp string.
This method is better for comparing strings based on values as == checks reference equality. Heres another question you should check out.


text:
Q: Moving an image in pygame? So, I'm making my first game in pygame, and have done OK up to this point. I just can't move the image. Can I please get some help?
mc_x = 20

mc_y = 20

spider_x = 690

spider_y = 500

while True:

for event in pygame.event.get():

    if event.type == pygame.QUIT:

        pygame.quit()

        sys.exit()

    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            mc_x -= 5
        elif event.key == pygame.K_RIGHT:
            mc_x += 5

        elif event.key == pygame.K_UP:
            mc_y += 5
        elif event.key == pygame.K_DOWN:
            mc_y -= 5

screen.blit(background,(0,0))#fixed
screen.blit(spider_small,(spider_x,spider_y))#FIXED
screen.blit(mc,(mc_x,mc_y))

pygame.display.update()

A: Based on your code:
screen.blit(mc,(mc_x,mc_y))

pygame.display.update()

should be inside the loop so that it would update/refresh your game for every keystroke.

A: You forgot to update the screen. Set the update function inside the main game loop. This is going to work fine!
Here's my sample code
import pygame
pygame.init()

WHITE = (255, 255, 255)
RED = (255, 0, 0)

canvas = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Example')

gameExit = False
lead_x, lead_y = 300, 300

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            lead_x -= 10
        elif event.key == pygame.K_RIGHT:
            lead_x += 10
        elif event.key == pygame.K_DOWN:
            lead_y += 10
        elif event.key == pygame.K_UP:
            lead_y -= 10

    canvas.fill(WHITE)
    pygame.draw.rect(canvas, RED, [lead_x, lead_y, 30, 30])
    pygame.display.update()

pygame.quit()
quit()


text:
Q: GDBus: how to be notified when the top-level ObjectManager object appears on the bus? In GDBus it's possible to watch for a particular name to appear on the bus with g_bus_watch_name_on_connection(). It's also possible to be notified about new interfaces/objects added on objects implementing the org.freedesktop.DBus.ObjectManager interface. I cannot however find a way to be notified about the appearance of the top-level ObjectManager on the bus. In other words:
We have a name org.foobar which exports an ObjectManager at /org/foobar which manages /org/foobar/abc and /org/foobar/xyz.
I can get notified about the name acquisition of org.foobar and about the addition of /org/foobar/abc and /org/foobar/xyz. However some time passes between when the org.foobar name is taken and then the /org/foobar object appears. How do I programmatically and correctly wait for it in GLib?


text:
Q: PHP 5.3.29 on Ubuntu 16.04 in order to run Joomla 1.5 locally I'm working on a Joomla 1.5 website, which was developed with PHP 5.3. Now I'm having some incompatibilities issues with some components.
My machine runs Ubuntu 16.04.
The version of Joomla is 1.5.
PHP versions are 5.6 and 7.0 (apache is configured to run PHP 5.6)
I can't find a way to download and install it. The apt command only shows 5.5, 5.6, 7.0 and 7.1 PHP versions.
Can anyone help me?

A: I have joomla 1.5 on a website running. My config shows that PHP 5.4.16 is in use. Therefore, why dont you try it with PHP 5.4 and get it from the download page:
http://php.net/releases/
If you have troubles to install it on your computer. Take a look here:
https://serverfault.com/questions/353550/how-to-install-old-php-version
The link explains how you install a old php version on linux. Btw.: in the link it is only explained how to replace a PHP version. But it is possible to run different versions on a server.


text:
Q: Multiple activities competing one intent I got an interview question.....
How to specify which Activity to be launched from an implicit intent, when there are multiple activities competing to execute the intent, without requiring user intervention.
My answer to this question is to use proper intent-filter within every activity, but it just sounds wrong..
Thanks in advance!

A: When creating an Intent you can pass explicit component name. i.e. class name. Only that component will now receive the intent.
example:
Intent myIntent = new Intent(getApplicationContext(),RequiredActivity.class);
startActivity(myIntent);

If you don't specify the exact component, Android will smartly let user choose one of the components that handles the intent.
example:
    Intent myIntent = new Intent(Intent.ACTION_VIEW);
    startActivity(myIntent);

If you want to go through all the components that handle the intent, yourself instead of letting android show choices to user, you can do that too:
example:
    Intent myIntent = new Intent(Intent.ACTION_VIEW);

    List<ResolveInfo> infoList = getPackageManager().queryIntentActivities(myIntent, 0);

    for (ResolveInfo ri : infoList){
        ActivityInfo ai = ri.activityInfo;
        String packageName = ai.packageName;
        String componentName = ai.name;

       // you can pick up appropriate activity to start
       // if(isAGoodMatch(packageName,componentName)){
       //     myIntent.setComponent(new ComponentName(packageName,componentName));
       //     startActivity(myIntent);
       //     break;
       // }

    }

I got six Activity matches for above code:


text:
Q: If $G/Z(G)$ is finite, then $|G'| < \infty$ Let $G$ be an infinite group. Suppose that $G/Z(G)$ is a finite group, where
$$G^{\prime}= \left\langle xyx^{-1}y^{-1}\ \middle\vert\ x,y \in G\right\rangle.$$
Prove that $|G'| < \infty$.

A: This is false. Let $H$ be a perfect group such that $H' = H$ and $Z(H) \neq 1$ (for example, $SL_n(F)$ for suitable $n$ and $F$) Then for $G = H \oplus H \oplus H \oplus \cdots$ (infinite direct sum), we have $G' = G$ but $Z(G)$ is infinite.


text:
Q: Bloco if não está bem localizado, como resolver? Fiz assim, pelo jeito ele ta dando erro, porque a porta 80 está aberta e ele retorna como fechada
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server = '201.27.188.138'
port = '80'

def MeuScanDaorao(port):
    try:
        s.connect((server, port))
        return True
    except:
        return False

if MeuScanDaorao(port):
    print(MeuScanDaorao('aaa'))
else:
    print('Ta fechada')

Esse meu código de baixo funciona, não entendo porque o de cima não. Python é muito legal, preciso aprender só
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server = '201.27.188.138'

def MeuScanDaorao(port):
    try:
        s.connect((server, port))
        return True
    except:
        return False

for x in range(80,81):
    if MeuScanDaorao(x):
        print('Porta', x, 'ta aberta')
    else:
        print('Porta', x,'fechada')

A: Como eu comentei, não faz sentido algum você chamar a função para a porta 'aaa'. Tentei pelos comentários, mas parece ter sido ineficiente.
Seu código está assim:
if MeuScanDaorao(port):
    print(MeuScanDaorao('aaa'))
else:
    print('Ta fechada')

Que pode ser traduzido para:

*

*Tenta conectar na porta 80, port;

*Se conectar com sucesso, exiba o resultado de MeuScanDaorao('aaa');

*Caso contrário, exiba 'Ta fechada';

Se você analisar o item 2, perceberá que o que será exibido é o retorno da chamada da função MeuScanDaorao na porta 'aaa', o que não faz o menor sentido. Provavelmente o resultado de MeuScanDaorao('aaa') sempre será False, a menos que o servidor possua uma porta 'aaa'.
Ao invés de fazer essas confusões com chamadas da função, por quê não começa com o simples?
if MeuScanDaorao(port):
    print('Porta está aberta')
else:
    print('Porta está fechada')

Se mesmo assim exibir que está fechada... bom, é provável que ela esteja fechada mesmo.

A: Me parece que a sua intenção é fazer com que o seu if fique fora do escopo da função.
Seu bloco if deve ser identado no mesmo nível que o def, veja só:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server = 'externo'
port = '80'

def MeuScanDaorao(port):
    try:
        s.connect((server, port))
        return True
    except:
        return False

if MeuScanDaorao(port):
    print( MeuScanDaorao('aaa') )

Repare que no Python 3.6, print espera parêntesis.


text:
Q: MPMoviePlayerController freezes if background audio is active In a view controller I have a video playing and also some background music. If the background music is playing, the video freezes when it goes to loop. If the background music is not playing the video loops normally as it should.
Here's how I'm setting up the video player:
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[self getBundleClip:@"MyVideo"]];
self.moviePlayer.controlStyle = MPMovieControlStyleNone;
self.moviePlayer.shouldAutoplay = YES;
self.moviePlayer.repeatMode = MPMovieRepeatModeOne;

The audio is playing via this Sound Manager. Any idea why the video would be freezing?

A: Try to use play music in background AVAudioPlayer and play same time MPMoviePlayerController like below code for play the AVAudioplayer in repeat mode:
first initialize the AVAudioplayer object in your header file (.h) like below:
@interface  Yourviewcontroller : UIViewController
{
    //your some codes after
    AVAudioPlayer *audioPlayer;
}

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

after implement play audio file in background like below code:
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:    [[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"]] error:NULL];

    audioPlayer.numberOfLoops =-1;//it's play audio repeatedly
    audioPlayer.currentTime=0.0f;
    [audioPlayer prepareToPlay];

after play audio any part of project like below code:
  [audioPlayer play];

you want stop the audio player like below code:
 [audioPlayer stop];


text:
Q: Text location in JTextArea I have the following question: can I align one part of text along the right edge and another along the left if this text is in one line?
Now I'll try to explain clearer. I have this window:

Can I align time of receiving by the right edge? Now I separate time by usual tabulation. Here's the code of the method:
frame.getSubscribe().addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        sTopic = frame.getTopicValue();
        try {
            if (mqttClient.isConnected()) {
                mqttClient.subscribe(sTopic);
                MqttCallback callback = new MqttCallback() {
                    @Override
                    public void connectionLost(Throwable throwable) {

                    }

                    @Override
                    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                        Date date = new Date();
                        String sDate = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
                        frame.getTextArea().append(String.valueOf(mqttMessage)+"\t\t"+sDate+'\n');
                    }

                    @Override
                    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                    }
                };
                mqttClient.setCallback(callback);
            }
        } catch (MqttException e1) {
            e1.printStackTrace();
        }
        System.out.println("Subscribed");
    }
});


text:
Q: alerting users before they leave page if they filled some fields I want to use two javascript events: onbeforeunload and inside it I need to use onhashchange. The point is on leaving the page if user has filled some fields then the confirmation message appear warning user whether they want to stay on page or leave.
My code is following
       window.onbeforeunload = function (e) {
      window.onhashchange = function (r) { return ''; }
        };

But the above code does not seem to be working? what am I doing wrong?
[Updated]
Again, what I am trying to achieve is I want to alert a user if the leave the page and if they have filled some fields on the page

A: You can try
window.onbeforeunload = function (e) {
       if (content on page changed) { confirm("Do you want to leave page?") }

        };
window.onhashchange = function (r) { if (content on page changed) { confirm("Do you want to leave page?") } }

I have just given pseudo code, you can replace with actual code.
Basic mistake is you are trying to bind event onhashchange in onbeforeunload.


text:
Q: Logic for values in JSF I have simple problem in JSF 2.0 and I need advice what is better solution.  So, on my .xhtml page there is component  which has 2 values : Yes and No.
<h:outputLabel id=v1 value="#{someValue}"/>
<f:selectItem itemValue="0" itemLabel="#{msg['label.no']}" />
<f:selectItem itemValue="1" itemLabel="#{msg['label.yes']}" />

What I am trying to accomplish is get default value of f:select based on outputLabel.
For example: if outputLabel gets value: Amateur than default f:selectItem is 'Yes' otherwise is 'No' default. Is it better with some logic in backing bean or via rendering on xhtml page?

A: You need to set it in the property behind the input component's value attribute. You didn't show the complete code, but if it's for example a <h:selectOneRadio> like so
<h:outputLabel for="foo" value="#{bean.label}" />
<h:selectOneRadio id="foo" value="#{bean.value}">
    <f:selectItem itemValue="0" itemLabel="#{msg['label.no']}" />
    <f:selectItem itemValue="1" itemLabel="#{msg['label.yes']}" />
</h:selectOneRadio>

then you should be setting the #{bean.value} in bean's (post)constructor. The complete picture is unclear, so here's a basic kickoff example instead of a well-suited solution:
private String label;
private Integer value;

@PostConstruct
public void init() {
    label = "Amateur";
    value = "Amateur".equals(label) ? 1 : 0;
}


text:
Q: calculate in mysql the median How can I calculate the median of each year for each code.
Below is the mysql table:

tbl_sales:

+-----+------+------+------+
| cod | cant | mont | year |
+-----+------+------+------+
| 432 |   1  |   10 | 2012 |
| 432 |   2  |   10 | 2012 |
| 432 |   4  |   10 | 2012 |
| 432 |   2  |   3  | 2012 |
| 432 |   3  |   2  | 2016 |
| 432 |   2  |   1  | 2016 |
| 432 |   8  |   8  | 2017 |
+-----+------+------+------+

Manual calculation of the median:

+------+---+---+---+---+---+---+---+---+---+----+----+----+-------+
| year | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | TOTAL |
+------+---+---+---+---+---+---+---+---+---+----+----+----+-------+
| 2012 |   |   | 2 |   |   |   |   |   |   |  7 |    |    |   9   |
| 2016 | 2 | 3 |   |   |   |   |   |   |   |    |    |    |   5   |
| 2017 |   |   |   |   |   |   |   | 8 |   |    |    |    |   8   |
+------+---+---+---+---+---+---+---+---+---+----+----+----+-------+

MEDIAN (5,8,9) = 8

How can I display in sql this way: 432 => 8
Thank you!

A: The kernel of the query is (obviously?):
SELECT year,SUM(cant) total FROM my_table GROUP BY year ORDER BY year;

From here, I would handle the rest in application code. You can calculate medians in SQL, but not without further hits on the data base, which just seems tedious when you already have all the information needed to perform the calculation (the number of rows and the value of the middle row(s)) right here in this result.


text:
Q: Lebesgue Integrability : for what values of $\alpha$? Let $\alpha \in [0,1]$. We consider $f_{\alpha} : \mathbb{R} \rightarrow [0,+\infty]$ defined by $f_{\alpha}(x) = \dfrac{ \sqrt{|x|} }{1-x} 1_{[0,\alpha]}(x)$.
We can write $f_{\alpha} (x) = \sum_{n=0}^{+\infty} \dfrac{\alpha^{n+3/2} }{n+3/2}$.
I would like to know what are the values of $\alpha$ for which the function $f_{\alpha}$ is Lebesgue-integrable.
Sorry for my bad english. Thank you in advance.


text:
Q: D3.js defs and url() does not work This code is a part of my project that I am trying to make force-layout graph in it. All links between nodes should have a marker that I make them (the markers) by the means of defs patterns.
In this code I expect to see defined markers in defs where I have called them by url(#id) but I do not see it while I get no error. It was working before but suddenly all defs has been disabled in my code.
Here you see the result svg:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
  shape-rendering: crispEdges;
}

.link.flow {
    opacity: 1!important;
    /*stroke-width: 1.5px;*/
}

#licensing {
    fill: green;
}

.link.flow.licensing {
    stroke: green;
}

.link.flow.resolved {
    stroke-dasharray: 0,2 1;
}

circle.flow {
    fill: #ff2575;
    stroke: #ff2575;
    /*stroke-width: 1.5px;*/
}

text.flow {
    font: 10px sans-serif;
    pointer-events: none;
    text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}

path.link.flow {
    fill: none;
 stroke: blue;
}

</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var maxWeight = 0;
var maxSize = 0;

//  new graph: start
var margin = 10;
var width = 455,
 height = 350;

var svgMaster = d3.select("body").append("svg") //  initiate svg
 .attr("id","flow")
 .attr("width", width)
 .attr("height", height)
 .style("margin-right",margin+"px")
 .style("margin-left",margin+"px");

var svg = svgMaster.append('svg:g')
 .attr('id','groupFlow');

var link = svg.selectAll(".link"),
 node = svg.selectAll(".node");  //  nodes and links
// :end new graph

var jsonData = {
 "nodes": [
  {"username": "S_Christophorus", "social_net_id": "55641120cdfa6618acdd1952", "last_name":
   "Christophorus", "first_name": "Stanly", "avatar": "/media/avatars/C02.png", "person_id": "556431f3cdfa661108325774"
  , "id": "55641120cdfa6618acdd1a8e"},
  {"username": "A_Field", "social_net_id": "55641120cdfa6618acdd1952"
  , "last_name": "Field", "first_name": "Abdul", "avatar": "/media/avatars/B01.png", "person_id": "556431f3cdfa6611083257f6"
  , "id": "55641120cdfa6618acdd1b94"},
  {"username": "B_Hugh", "social_net_id": "55641120cdfa6618acdd1952"
  , "last_name": "Hugh", "first_name": "Beale", "avatar": "/media/avatars/B02.png", "person_id": "556431f3cdfa6611083257f7"
  , "id": "55641120cdfa6618acdd1b96"},
  {"username": "M_Kennedy", "social_net_id": "55641120cdfa6618acdd1952"
  , "last_name": "Kennedy", "first_name": "Mordy", "avatar": "/media/avatars/B05.png", "person_id": "556431facdfa661108327e21"
  , "id": "55641128cdfa6618acdd9fed"}
 ],
 "edges": [
  {"source": 0, "target": 1, "weight": 1.5},
  {"source": 2, "target": 0, "weight": 46.5},
  {"source": 0, "target": 2, "weight": 6.0},
  {"source": 2, "target": 1, "weight": 1.5},
  {"source": 2, "target": 3, "weight": 3.0}
 ]
}

/*
 * refresh graph based on given data
 */
var refreshForceFlow = function(json){
 clearGraphFlow();
 var maxWeight = 0;

    for(var edgeIndex = 0; edgeIndex < json.edges.length; edgeIndex++){
      if(json.edges[edgeIndex].weight > maxWeight) maxWeight = json.edges[edgeIndex];
      }
   console.log(json);
 var force = d3.layout.force()
  .nodes(d3.values(json.nodes))
  .links(json.edges)
  .size([width, height])
  .linkDistance(60)
  .charge(-300)
  .on("tick", tickFlow)
  .start();

 // Per-type markers, as they don't inherit styles.
 svg.append("defs").selectAll("marker")
  .data(json.edges)
  .enter().append("marker")
  .attr("id", function(d) { return ("weight_"+d.weight).replace(".","_"); })
  .attr("viewBox", "0 -5 10 10")
  .attr("refX", 13)    //  15
  .attr("refY", 0)    //  -1.5
  .attr("markerWidth", 6)
  .attr("markerHeight", 6)
  .attr("orient", "auto")
  .append("path")
  .style("fill", function(d){
   var color = 'FF';
   var c = Math.floor((d.weight*99)/maxWeight);
   c = 100 - c;
   if( c < 10) c = '0'+c;
   color = c + color;
   color = c + color;
   //console.log('#'+color);
   return '#'+color;
  })
  .style("stroke", function(d){
   var color = 'FF';
   var c = Math.floor((d.weight*99)/maxWeight);
   c = 100 - c;
   if( c < 10) c = '0'+c;
   color = c + color;
   color = c + color;
   //console.log('#'+color);
   return '#'+color;
  })
  .style("stroke-width", "1px")
  .attr("d", "M0,-5L10,0L0,5");

 var path = svg.append("g").selectAll("path")
  .data(force.links())
  .enter().append("path")
  .attr("class", function(d) { return "link flow "; })
  .style("stroke-width", function(d) {
   var res = 1 + ((d.weight * 2.5) / maxWeight);
   return res + 'px';
  })
  .style("stroke", function(d){
   var color = 'FF';
   var c = Math.floor((d.weight*99)/maxWeight);
   c = 100 - c;
   if( c < 10) c = '0'+c;
   color = c + color;
   color = c + color;
   //console.log('#'+color);
   return '#'+color;
  })
  .attr("marker-end", function(d) { return "url(#" + ("weight_"+d.weight).replace(".","_") + ")"; });

 var circle = svg.append("g").selectAll("circle")
  .data(force.nodes())
  .enter().append("circle")
  .attr("r", 6)
  .attr("class", "flow")
  .call(force.drag);

 var text = svg.append("g").selectAll("text")
  .data(force.nodes())
  .enter().append("text")
  .attr("class", "flow")
  .attr("x", 8)
  .attr("y", ".31em")
  .text(function(d) { return d.username; });

 // Use elliptical arc path segments to doubly-encode directionality.
 function tickFlow() {
  path.attr("d", linkArc);
  circle.attr("transform", transform);
  text.attr("transform", transform);
 }

 function linkArc(d) {
  var tx = d.target.x - 0;
  var ty = d.target.y - 0;
  var sx = d.source.x - 0;
  var sy = d.source.y - 0;

  var dx = tx - sx,
   dy = ty - sy,
   dr = Math.sqrt(dx * dx + dy * dy);
  return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
 }

 function transform(d) {
  return "translate(" + d.x + "," + d.y + ")";
 }
};  //  end of function

/*
 * clear gragh
 */
var clearGraphFlow = function(){
 svg.selectAll("g").remove();
 svg.selectAll("defs").remove();
};

refreshForceFlow(jsonData);

</script>

A: the urls are not valid.
Replace this...
.attr("id", function(d) { return d.weight; })

with this...
.attr("id", function(d) { return ("weight_"+d.weight).replace(".","_"; })

A: The problem I pointed out in my previous answer was the reason for the refs issue, but there were other problems as well through-out the code.  Please see corrected code below...

//debug panel///////////////////////////////////////////////////////////////////////////////////////////
var update = d3.select("#update")
  .on("click", (function() {
    var dataSet = false;
    return function() {
      refreshForceFlow(JSON.parse(JSON.stringify(jsonData[(dataSet = !dataSet, +dataSet)])))
    }
  })());
////////////////////////////////////////////////////////////////////////////////////////////////////////
var maxWeight = 0;
var maxSize = 0;

//  new graph: start
var margin = 10;
var width = 500,
  height = 150;

var svgMaster = d3.select("body").append("svg") //  initiate svg
  .attr("id", "flow")
  .attr("width", width)
  .attr("height", height)
  .style("margin-right", margin + "px")
  .style("margin-left", margin + "px");

var svg = svgMaster.append('svg:g')
  .attr('id', 'groupFlow');

var link = svg.selectAll(".link"),
  node = svg.selectAll(".node"); //  nodes and links

// :end new graph

var jsonData = [{
  "nodes": [{
    "username": "S_Christophorus",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Christophorus",
    "first_name": "Stanly",
    "avatar": "/media/avatars/C02.png",
    "person_id": "556431f3cdfa661108325774",
    "id": "55641120cdfa6618acdd1a8e"
  }, {
    "username": "A_Field",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Field",
    "first_name": "Abdul",
    "avatar": "/media/avatars/B01.png",
    "person_id": "556431f3cdfa6611083257f6",
    "id": "55641120cdfa6618acdd1b94"
  }, {
    "username": "B_Hugh",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Hugh",
    "first_name": "Beale",
    "avatar": "/media/avatars/B02.png",
    "person_id": "556431f3cdfa6611083257f7",
    "id": "55641120cdfa6618acdd1b96"
  }, {
    "username": "M_Kennedy",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Kennedy",
    "first_name": "Mordy",
    "avatar": "/media/avatars/B05.png",
    "person_id": "556431facdfa661108327e21",
    "id": "55641128cdfa6618acdd9fed"
  }],
  "edges": [{
    "source": "0",
    "target": "1",
    "weight": 1.5
  }, {
    "source": "2",
    "target": "0",
    "weight": 46.5
  }, {
    "source": "0",
    "target": "2",
    "weight": 6.0
  }, {
    "source": "2",
    "target": "1",
    "weight": 1.5
  }, {
    "source": "2",
    "target": "3",
    "weight": 3.0
  }]
}, {
  "nodes": [{
    "username": "A_Field",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Christophorus",
    "first_name": "Stanly",
    "avatar": "/media/avatars/C02.png",
    "person_id": "556431f3cdfa661108325774",
    "id": "55641120cdfa6618acdd1a8e"
  }, {
    "username": "B_Hugh",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Field",
    "first_name": "Abdul",
    "avatar": "/media/avatars/B01.png",
    "person_id": "556431f3cdfa6611083257f6",
    "id": "55641120cdfa6618acdd1b94"
  }, {
    "username": "M_Kennedy",
    "social_net_id": "55641120cdfa6618acdd1952",
    "last_name": "Hugh",
    "first_name": "Beale",
    "avatar": "/media/avatars/B02.png",
    "person_id": "556431f3cdfa6611083257f7",
    "id": "55641120cdfa6618acdd1b96"
  }],
  "edges": [{
    "source": "0",
    "target": "1",
    "weight": 1.5
  }, {
    "source": "2",
    "target": "0",
    "weight": 26.5
  }, {
    "source": "0",
    "target": "2",
    "weight": 16.0
  }, {
    "source": "2",
    "target": "1",
    "weight": 1.5
  }]
}];

/*
 * refresh graph based on given data
 */
var refreshForceFlow = (function() {
  // Need to use a single instance of force because of
  // this bug https://github.com/mbostock/d3/issues/2468
  // hence the closure...
  var force = d3.layout.force()
    .size([width, height])
    .linkDistance(60)
    .charge(-300)

  return function(json) {
    //    clearGraphFlow();  ***d3 does this for you if you do it right***
    //    var maxWeight = 0;
    //***this code is already written for you: you just need to wire it up***
    //    for(var edgeIndex = 0; edgeIndex < json.edges.length; edgeIndex++){
    //      if(json.edges[edgeIndex].weight > maxWeight) maxWeight = json.edges[edgeIndex];
    //    }
    var maxWeight = d3.max(json.edges, function(d) {
      return d.weight
    });
    //clean up the data: force needs type Number on link.source/destination
    json.edges.forEach(function(d) {
      d.source = +d.source;
      d.target = +d.target
    });
    console.log(json);

    force
      .nodes(json.nodes) //***don't need to wrap in d3.value***
      .links(json.edges)
      .on("tick", tickFlow)
      .start();

    // Per-type markers, as they don't inherit styles.
    // UPDATE
    var defs = svg.selectAll("defs").data([json.edges]);
    // EXIT
    defs.exit().remove();
    // ENTER
    defs.enter().append("defs");
    // UPDATE+ENTER for defs
    // UPDATE for markers
    var markers = defs.selectAll("marker")
      .data(function(d) {
        return d
      }); //get the data elements from the defs datum
    //ENTER
    markers.enter().append("marker") //new markers only
      .attr("viewBox", "0 -5 10 10")
      .attr("refX", 13) //  15
      .attr("refY", 0) //  -1.5
      .attr("markerWidth", 6)
      .attr("markerHeight", 6)
      .attr("orient", "auto")
      .append("path");
    // UPDATE+ENTER
    markers.attr("id", function(d) {
        return ("weight_" + d.weight).replace(".", "_");
      })
      .select("path")
      .style("fill", function(d) {
        var color = 'FF';
        var c = Math.floor((d.weight * 99) / maxWeight);
        c = 100 - c;
        if (c < 10) c = '0' + c;
        color = c + color;
        color = c + color;
        //console.log('#'+color);
        return '#' + color;
      })
      .style("stroke", function(d) {
        var color = 'FF';
        var c = Math.floor((d.weight * 99) / maxWeight);
        c = 100 - c;
        if (c < 10) c = '0' + c;
        color = c + color;
        color = c + color;
        //console.log('#'+color);
        return '#' + color;
      })
      .style("stroke-width", "1px")
      .attr("d", "M0,-5L10,0L0,5");
    // EXIT
    markers.exit().remove();

    var link = svg.selectAll("g.link").data(force.links());
    link.enter().insert("g", ".link").attr("class", "link")
      .append("path")
      .attr("class", "link flow"); //***don't need a function for constant value***;
    link.exit().remove();
    path = link.select("path")
      .style("stroke-width", function(d) {
        var res = 1 + ((d.weight * 2.5) / maxWeight);
        return Math.round(res) + 'px';
      })
      .style("stroke", function(d) {
        var color = 'FF';
        var c = Math.floor((d.weight * 99) / maxWeight);
        c = 100 - c;
        if (c < 10) c = '0' + c;
        color = c + color;
        color = c + color;
        //console.log('#'+color);
        return '#' + color;
      })
      .attr("marker-end", function(d) {
        return "url(#" + ("weight_" + d.weight).replace(".", "_") + ")";
      });

    var node = svg.selectAll("g.node")
      .data(force.nodes()), //node is the node container: includes circle and text
      nodeEnter = node.enter().append("g").call(force.drag),
      //append the circle and the text inside the node g
      //ENTER
      circle = nodeEnter.attr("class", "node")
      .append("circle")
      .attr("r", 6)
      .attr("class", "flow"),
      //  .on("contextmenu", d3.contextMenu(menu)),

      text = nodeEnter.append("text")
      .attr("class", "flow")
      .attr("x", 8)
      .attr("y", ".31em")
      .style({
        "pointer-events": "all",
        cursor: "default"
      }) //***include dragging by text***

    //ENTER+UPDATE
    text.text(function(d) {
      return d.username;
    });

    // EXIT
    node.exit().remove();

    // Use elliptical arc path segments to doubly-encode directionality.
    function tickFlow(e) {
      path.attr("d", linkArc);
      node.attr("transform", transform); //circle and text is wrapped by node
    }

    function linkArc(d) {
      var tx = d.target.x - 0;
      var ty = d.target.y - 0;
      var sx = d.source.x - 0;
      var sy = d.source.y - 0;

      var dx = tx - sx,
        dy = ty - sy,
        dr = Math.sqrt(dx * dx + dy * dy);
      return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
    }

    function transform(d) {
      return "translate(" + d.x + "," + d.y + ")";
    }
  }; //  end of function
})();

/*
 * clear gragh
 */
//  var clearGraphFlow = function(){  // ***Not required***
//    svg.selectAll("g").remove();
//    svg.selectAll("defs").remove();
//  };

refreshForceFlow(JSON.parse(JSON.stringify(jsonData[0])));
body {
      font: 10px sans-serif;
      shape-rendering: crispEdges;
    }
    svg {
      outline: 1px solid red;
      overflow: visible;
    }
    .link.flow {
      opacity: 1!important;
      /*stroke-width: 1.5px;*/
    }
    #licensing {
      fill: green;
    }
    .link.flow.licensing {
      stroke: green;
    }
    .link.flow.resolved {
      stroke-dasharray: 0, 2 1;
    }
    circle.flow {
      fill: #ff2575;
      stroke: #ff2575;
      stroke-width: 1.5px;
    }
    text.flow {
      font: 10px sans-serif;
      pointer-events: none;
      text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
    }
    path.link.flow {
      fill: none;
      stroke: blue;
    }
    div#panel {
      display: block;
    }
    input {
      margin: 10px;
    }
<div id="panel">
  <input id="update" type="button" value="update">
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>


text:
Q: Using System.Device in an MVC project This doesn't seem to make sense.
I'm trying to use the System.Device library in a project to take advantage of the geo location functionality. I'm adding code to a Razor page as I usually do.
I have a reference to the library and I've added the using to the top of the razor view:
@using System.Device;

Device has a red underline because it cannot be found. Typing System.D does not yield Device in intellisense. This doesn't seem to make sense as the library is definitely referenced.
The web.config is in Views has no mention of System.Device. If I do a full search of the solution for 'device' there are no mentions of it anywhere I wouldn't expect.
I've open and closed files, removed the reference, restarted VS, restarted my computer. Everything. It still persists.
I feel like either there's something I don't know or I'm doing something stupid. Am I missing something here?

A:
The web.config is in Views has no mention of System.Device.

You need to add System.Device to your web.config. Depending on whether you're using Areas you may need to add it to the web.config for that area too. If it's not in web.config, razor doesn't know about it.
 <namespaces>
    <add namespace="System.Device" />
 </namespaces>

Further, try setting Copy Local to True for the Reference Properties of System.Device. It didn't work for me until I did both.


text:
Q: How to find $\int_0^{\pi/4}\sec(x)^3dx$ How do I find $$\int_0^{\pi/4}\sec(x)^3dx$$
I arrive at $\sec x\tan x + 1/3 \ln| (\cos^3(x))| dx$
where $u = \sec x$ and $v' = \sec^2(x)$
What's my error? Could I get a step by step solution?

A: In your last step, you did
$$\int v \, du = \int \tan^2 x \sec x \, dx $$
and you somehow got to $\frac{1}{3} \ln |\cos^3 x \, dx$.  First, the $dx$ there does not make any sense; you are adding that infinitessimal to the ordinary quantity $\sec x \tan x$, which is always a sign of something wrong.  But assuming that that was just a typo, your mistake was in integrating
$$\int \tan^2 x \sec x \, dx = \int u^2 du$$
with $u = \tan x$. which is
$$\frac{1}{3} tan^3 x$$
So the indefinite integral is
$$
\tan x \sec x + \frac{1}{3} \tan^3 x
$$
The last  part of the problem is evaluating this at the lower endpoint:
$$
1 \cdot \sqrt{2} + \frac{1}{3} \cdot 1 - 0 \cdot 1 -\frac{1}{3}\cdot 0 = \sqrt{2}+\frac{1}{3}
$$

A: So you're integrating by parts with $u = \sec x$ and $dv = \sec^2 x = (\tan x)'$. Then:
$$
I := \int_{0}^{\frac{\pi}{4}} \sec^3 x dx = \sec \left(\frac{\pi}{4}\right)\tan \left(\frac{\pi}{4}\right)  - \int_{0}^{\frac{\pi}{4}}\tan^2 x \sec x dx
$$
Where the last integral is
$$
\int_{0}^{\frac{\pi}{4}}\tan^2 x \sec x dx = \int_{0}^{\frac{\pi}{4}} \frac{1-\cos^2 x}{\cos^3 x} = I - \int_{0}^{\frac{\pi}{4}} \sec xdx
$$
Plugging this in the first expression yields:
$$
2I = \sec \left(\frac{\pi}{4}\right)\tan \left(\frac{\pi}{4}\right)  + \int_{0}^{\frac{\pi}{4}} \sec xdx  = \sec \left(\frac{\pi}{4}\right)\tan \left(\frac{\pi}{4}\right)  + \log\left\lvert \sec \left(\frac{\pi}{4}\right) + \tan \left(\frac{\pi}{4}\right) \right\rvert
$$
So $I = \frac{1}{\sqrt{2}} + \log \sqrt{1+\sqrt{2}}$.


text:
Q: Key saved but not correctly I was able to save my key on GitHub. (It does not end in .pub).
When testing if this was done correctly and using the 'ssh -T git@github.com' code, there is something off.
The terminal asks me if I want to continue, and I wrote 'yes', then a pop-up box asking for a password came up... I input nothing and clicked "unlock", which resulted in the bottom code saying "Permission denied". (see screenshot).

I'm not sure what to do here--I have followed the instructions multiple times.
Please let me know how to fix this.

A: When you add your SSH key to GitHub, that would be the one ending with .pub.
Then, double-check the correct private key is used with:
ssh -Tv git@github.com

It would ask for a passphrase only if you have created the private key with a passphrase.
If you did, make sure to add your key to the agent first.
Check also your ~/.ssh permissions.


text:
Q: Changing look of meshc plot in matlab I have some code that creates a random landscape and contour, but I can't find out to control the colours, shading, contour line colors, number of contour lines etc. Nothign I've found googling helps. Here's the code:
function create_landscape()

Lx=1;
dx=0.01;
x=0:dx:Lx;
nx=length(x);
Ly=5;
dy=0.01;
y=0:dy:Ly;
ny=length(y);

[mgx,mgy]=meshgrid(x,y);
landscape=zeros(ny ,nx);
nhills=100;
maxh=1;
maxw=0.03;
maxl=maxw*Ly/Lx;
xbuf=0.1;
ybuf=0.1;
pd=makedist('Normal','mu',0,'sigma',1e-5*exp(-1));

for i=1:nhills
    center=[xbuf+(Lx-2*xbuf)*rand,ybuf+(Ly-2*ybuf)*rand];
    w=rand*maxw;
    l=rand*maxl;
    sign=(-1)^(ceil(2*rand));
    h=random(pd)*maxh/1e-5;
    landscape=landscape+hill(mgx,mgy,sign*h,center,w,l);
end

m=meshc(mgx,mgy,landscape);
axis([-0.2 Lx+0.2 -0.2 Ly+0.2 -maxh*1.5 maxh*3])
grid off
xlabel('x')
ylabel('y')
hold off;

end

function fx=hill(x,y,h,center,w,l)
fx=h*exp(-(x-center(1)).*(x-center(1))/w^2).*exp(-(y-center(2)).*(y-center(2))/l^2);
end

Any idea how I can change how it looks?

A: You can change the color using the function colormap
Instead of using the mesh function, you can use the surfc(...,...,...,'EdgeColor','none') function if you want a plain surface.
If you want to create a landscape with more lines, you will have to change your parameter dx and dy
The colormap('pink') would give you the following result (you can also define your own colormap), on the left the function surfc and on the right the function meshc.


text:
Q: Deleting a row from table view and server also in swift I am trying to delete a row from table view and I want to delete that from the server to I am using localhost as my server
my delete URL is LocalHost in id place I have to send "id" and I am getting that through did select of  table view and I am passing through that URL and I am unable to remove from the server while doing this process
please help me is there any changes in my code
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

       // getting id //
        id1 = "\(arrdata[indexPath.row].id)"
        print(id1)

        self.arrdata.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
        let url = URL(string: "http://localhost:8080/hub/business/fun/=%@",id1 as CVarArg)

        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            do{if error == nil{
                self.arrdata = try JSONDecoder().decode([jsonstruct3].self, from: data!)

                for mainarr in self.arrdata{
                    //                    print(mainarr.name,":",mainarr.capital,":",mainarr.alpha3Code)
                    //                    print(data)

                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
                }

            }
            catch
            {
                print("Error in get json data")
                print(error)
            }

            }.resume()

        tableView.reloadData()
        tableView.endUpdates()
    }
}

A: Here is the answer, Please follow it.

*

*First of all, for deleting the record from app side - You need to
delete it from Array and also need to remove the cell from
tableview.

*For deleting the record from server side, You need to call an API to
let server know about which data server will delete.
I checked your code and found that deleting the record from app side seems correct but while calling an API - I guess you need to pass some more info to server. May be you would like to pass Header, HTTP Method, Parameters etc. You can do all this things with URLRequest. You just passed the URL in your code, so instead of pass the URL directly please try to pass the URLRequest.

And after following the answer, please try below code to check exact
  what your are getting back from server side.

if let url = URL(string: "Your API URL here") {
            var urlRequest = URLRequest(url: url)
            urlRequest.httpMethod = "POST" //Can be any as "GET", "PUT"
            urlRequest.addValue("Bearer \("token")", forHTTPHeaderField: "Authorization") //Based on your back-end requirements.
            let params = ["id": "5"] //Based on your back-end requirements.
            urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])

            URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
                if error == nil, let jsonData = data {
                    do {
                        if let jsonResponse = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                            print(jsonResponse)
                        }
                    } catch {
                        print("\(error.localizedDescription)")
                    }
                }
            }.resume()
        }


text:
Q: Variable not working on scrollTop value inside .animate() Hi peeps wondering if anyone could help me with a click function, should animate to the target anchor which it does fine when using an integer for the scrollTop value however when I pass a variable it doesnt like it. Any ideas?
$(".project a").click(function(event){
    event.preventDefault();
    var full_url = this.href;
    var parts = full_url.split("#");
    var trgt = parts[1];
    var target_offset = $("#"+trgt).offset();
    var target_top = target_offset.top; //- 90;

    $('html, body').animate({scrollTop:target_top}, 1000, function() {
    });
});

FIXED: Ok apologies peeps the function was working fine from the get go however a colleague has pointed out var trgt contained an element that was set to display:none in the css, with the original intention of using slideToggle on callback... massive sigh. Cheers for your responses though!

A: Try to parse variable to integer with
parseInt(target_top)

and try again. Let me know if not working my suggestion.
Or read this: Using a variable for a key in a JavaScript object literal. Look at Andy E's answer.