text:
Q: How can I create a tree for Huffman encoding and decoding? For my assignment, I am to do a encode and decode for huffman trees. I have a problem creating my tree, and I am stuck.
Don't mind the print statements - they are just for me to test and see what the output is when my function runs.
For the first for loop, I got all the values and index from the text file I used in my main block for testing.
In the second for loop I inserted all the stuff into the priority queue.
I am so stuck about where to go next - I'm trying to make nodes, but I am confused about how to progress. Can someone tell me if I'm doing this right?
def _create_code(self, frequencies):
    '''(HuffmanCoder, sequence(int)) -> NoneType
    iterate over index into the sequence keeping it 256 elements long, '''
    #fix docstring
    p = PriorityQueue()
    print frequencies

    index = 0
    for value in frequencies:
        if value != 0:
            print value #priority
            print index #elm
            print '-----------'
        index = index + 1

    for i in range(len(frequencies)):
        if frequencies[i] != 0:
            p.insert(i, frequencies[i])
            print i,frequencies[i]
            if p.is_empty():
                a = p.get_min()
                b = p.get_min()
                n1 = self.HuffmanNode(None, None, a)
                n2 = self.HuffmanNode(None, None, b)
                print a, b, n1, n2
    while not p.is_empty():
        p.get_min()

I manually inserted the first two to start my tree, is that correct?
How do I keep going? I know the idea of it, just code-wise I am very stuck.
This is using python by the way. I tried looking at Wikipedia, I know the steps, I just need help on code and how I should keep going, thanks!
The HuffmanNode comes from this nested class:
class HuffmanNode(object):

    def __init__(self, left=None, right=None, root=None):
        self.left = left
        self.right = right
        self.root = root

A: @Dave walk_tree is missing tree processing code
# Recursively walk the tree down to the leaves,
# assigning a code value to each symbol
def walk_tree(node, prefix="", code={}):
    if isinstance(node[1].left[1], HuffmanNode):
        walk_tree(node[1].left,prefix+"0", code)
    else:
        code[node[1].left[1]]=prefix+"0"
    if isinstance(node[1].right[1],HuffmanNode):
        walk_tree(node[1].right,prefix+"1", code)
    else:
        code[node[1].right[1]]=prefix+"1"
    return(code)

A: @Dave class HuffmanNode(object) has a subtle bug.  When the two frequencies are equal an exception is thrown:  For example let
    freq = [ (200/3101, 'd'), (100/3101, 'e'), (100/3101, 'f') ]

Then you get TypeError: unorderable types: HuffmanNode() < str().
The problem has to do with the PriorityQueue implementation.  I suspect when the first elements of the tuples compare equal, PriorityQueue wants to compare the second elements one of which is a python object.  You add the lt method to your class and the problem is solved.
    def __lt__(self,other):
        return 0

A: I was working out this problem today, to try and match results in above response. For most part, this solution works well but only thing i find non-intuitive is to add [0] and [1] in printing the non-node (leaf).
But this answers miracles question - you can essentially print it using any traversal mechanism
import queue

class HuffmanNode(object):
    def __init__(self,left=None,right=None,root=None):
        self.left = left
        self.right = right
        self.root = root
    def children(self):
        return (self.left,self.right)
    def preorder(self,path=None):
        if path is None:
            path = []
        if self.left is not None:
            if isinstance(self.left[1], HuffmanNode):
                self.left[1].preorder(path+[0])
            else:
                print(self.left,path+[0])
        if self.right is not None:
            if isinstance(self.right[1], HuffmanNode):
                self.right[1].preorder(path+[1])
            else:
                print(self.right,path+[1])

freq = [
    (8.167, 'a'), (1.492, 'b'), (2.782, 'c'), (4.253, 'd'),
    (12.702, 'e'),(2.228, 'f'), (2.015, 'g'), (6.094, 'h'),
    (6.966, 'i'), (0.153, 'j'), (0.747, 'k'), (4.025, 'l'),
    (2.406, 'm'), (6.749, 'n'), (7.507, 'o'), (1.929, 'p'),
    (0.095, 'q'), (5.987, 'r'), (6.327, 's'), (9.056, 't'),
    (2.758, 'u'), (1.037, 'v'), (2.365, 'w'), (0.150, 'x'),
    (1.974, 'y'), (0.074, 'z') ]

def encode(frequencies):
    p = queue.PriorityQueue()
    for item in frequencies:
        p.put(item)

    #invariant that order is ascending in the priority queue
    #p.size() gives list of elements
    while p.qsize() > 1:
        left,right = p.get(),p.get()
        node = HuffmanNode(left,right)
        p.put((left[0]+right[0],node))
    return p.get()

node = encode(freq)
print(node[1].preorder())

A: The Huffman algorithm in Wikipedia tells you exactly how to create the node tree, so your program can be based on that algorithm, or another like it.  Here is a Python program with comments showing the corresponding wikipedia algorithm step.  The test data is frequencies of the letters of the alphabet in English text.
Once the node tree is created, you need to walk it down to assign Huffman codes to each symbol in your dataset.  Since this is homework, that step is up to you, but a recursive algorithm is the simplest and most natural way to handle it. It's only six more lines of code.
import queue

class HuffmanNode(object):
    def __init__(self, left=None, right=None, root=None):
        self.left = left
        self.right = right
        self.root = root     # Why?  Not needed for anything.
    def children(self):
        return((self.left, self.right))

freq = [
    (8.167, 'a'), (1.492, 'b'), (2.782, 'c'), (4.253, 'd'),
    (12.702, 'e'),(2.228, 'f'), (2.015, 'g'), (6.094, 'h'),
    (6.966, 'i'), (0.153, 'j'), (0.747, 'k'), (4.025, 'l'),
    (2.406, 'm'), (6.749, 'n'), (7.507, 'o'), (1.929, 'p'),
    (0.095, 'q'), (5.987, 'r'), (6.327, 's'), (9.056, 't'),
    (2.758, 'u'), (1.037, 'v'), (2.365, 'w'), (0.150, 'x'),
    (1.974, 'y'), (0.074, 'z') ]

def create_tree(frequencies):
    p = queue.PriorityQueue()
    for value in frequencies:    # 1. Create a leaf node for each symbol
        p.put(value)             #    and add it to the priority queue
    while p.qsize() > 1:         # 2. While there is more than one node
        l, r = p.get(), p.get()  # 2a. remove two highest nodes
        node = HuffmanNode(l, r) # 2b. create internal node with children
        p.put((l[0]+r[0], node)) # 2c. add new node to queue
    return p.get()               # 3. tree is complete - return root node

node = create_tree(freq)
print(node)

# Recursively walk the tree down to the leaves,
#   assigning a code value to each symbol
def walk_tree(node, prefix="", code={}):
    return(code)

code = walk_tree(node)
for i in sorted(freq, reverse=True):
    print(i[1], '{:6.2f}'.format(i[0]), code[i[1]])

When run on the alphabet data, the resulting Huffman codes are:
e  12.70 100
t   9.06 000
a   8.17 1110
o   7.51 1101
i   6.97 1011
n   6.75 1010
s   6.33 0111
h   6.09 0110
r   5.99 0101
d   4.25 11111
l   4.03 11110
c   2.78 01001
u   2.76 01000
m   2.41 00111
w   2.37 00110
f   2.23 00100
g   2.02 110011
y   1.97 110010
p   1.93 110001
b   1.49 110000
v   1.04 001010
k   0.75 0010111
j   0.15 001011011
x   0.15 001011010
q   0.10 001011001
z   0.07 001011000

A: One more solution returning a dictionary {label:code} and a recursive dictionary tree containing the resulting graph. The input vals is in form of dictionary {label:freq}:
def assign_code(nodes, label, result, prefix = ''):
    childs = nodes[label]
    tree = {}
    if len(childs) == 2:
        tree['0'] = assign_code(nodes, childs[0], result, prefix+'0')
        tree['1'] = assign_code(nodes, childs[1], result, prefix+'1')
        return tree
    else:
        result[label] = prefix
        return label

def Huffman_code(_vals):
    vals = _vals.copy()
    nodes = {}
    for n in vals.keys(): # leafs initialization
        nodes[n] = []

    while len(vals) > 1: # binary tree creation
        s_vals = sorted(vals.items(), key=lambda x:x[1])
        a1 = s_vals[0][0]
        a2 = s_vals[1][0]
        vals[a1+a2] = vals.pop(a1) + vals.pop(a2)
        nodes[a1+a2] = [a1, a2]
    code = {}
    root = a1+a2
    tree = {}
    tree = assign_code(nodes, root, code)   # assignment of the code for the given binary tree
    return code, tree

This can be used as:
freq = [
(8.167, 'a'), (1.492, 'b'), (2.782, 'c'), (4.253, 'd'),
(12.702, 'e'),(2.228, 'f'), (2.015, 'g'), (6.094, 'h'),
(6.966, 'i'), (0.153, 'j'), (0.747, 'k'), (4.025, 'l'),
(2.406, 'm'), (6.749, 'n'), (7.507, 'o'), (1.929, 'p'),
(0.095, 'q'), (5.987, 'r'), (6.327, 's'), (9.056, 't'),
(2.758, 'u'), (1.037, 'v'), (2.365, 'w'), (0.150, 'x'),
(1.974, 'y'), (0.074, 'z') ]
vals = {l:v for (v,l) in freq}
code, tree = Huffman_code(vals)

text = 'hello' # text to encode
encoded = ''.join([code[t] for t in text])
print('Encoded text:',encoded)

decoded = []
i = 0
while i < len(encoded): # decoding using the binary graph
    ch = encoded[i]
    act = tree[ch]
    while not isinstance(act, str):
        i += 1
        ch = encoded[i]
        act = act[ch]
    decoded.append(act)
    i += 1

print('Decoded text:',''.join(decoded))

One can visualize the tree with Graphviz as:

The figure was generated by the following script as (Graphviz is needed):
def draw_tree(tree, prefix = ''):
    if isinstance(tree, str):
        descr = 'N%s [label="%s:%s", fontcolor=blue, fontsize=16, width=2, shape=box];\n'%(prefix, tree, prefix)
    else: # Node description
        descr = 'N%s [label="%s"];\n'%(prefix, prefix)
        for child in tree.keys():
            descr += draw_tree(tree[child], prefix = prefix+child)
            descr += 'N%s -> N%s;\n'%(prefix,prefix+child)
    return descr

import subprocess
with open('graph.dot','w') as f:
    f.write('digraph G {\n')
    f.write(draw_tree(tree))
    f.write('}')
subprocess.call('dot -Tpng graph.dot -o graph.png', shell=True)


text:
Q: Xamarin.Android C#, stuck at SQLiteConnection(dbpath). Null Exception, Object reference not set to an instance of object Here is the Code:
    public long AddCase(Customer addCust)
    {
        using (var db1 = new SQLiteConnection(_helper.WritableDatabase.Path)) //Null Exception:Error
        {
            try
            {
                return db1.Insert(addCust);
            }
            catch (Exception ex)
            {
                //catch Exception;
            }
        }
    }

I am trying to invoke the above function with the code below
DatabaseUpdates ManageDb = new DatabaseUpdates();
ManageDb.SetContext(this);

DatabaseUpdates upd = new DatabaseUpdates();

upd.UpdateCustomer(var);
Name.Text = "";

.
.
I have a function to check if _helper is null or not..,
if (context != null)
            {
                _helper = new DataManagerHelper(context);
            }

Well I want to know what actually SQLiteConnection(dbpath) means. Why its showing null Exception. I know the concept why it declares null exception. Please help me understand why the below code gives me an error,
**using (var db1 = new SQLiteConnection(_helper.WritableDatabase.Path)) //Null Exception:Error**

No build errors. There are debug errors.
Please help

redpajama_set_name: RedPajamaStackExchange


text:
Q: CMS Made Simple .htaccess Redirect for non-WWW I need some help with a CMS Made Simple website that has pretty URLs enabled.
At the moment I have http://www.example.com/ going to http://example.com/
However If I try and access http://www.example.com/pagename it goes to http://example.com/index.php?page=pagename when it should be going to http://example.com/pagename
Additionally I want to redirect http://example.com/index.php to http://example.com/
I've included the contents of my .htaccess file below:
# Attempt to override some php settings, these settings may be helpful on some hosts if your
# default configuration does not meet CMS's minimum requirements, and your host
# has given your account appropriate permissions
#php_value upload_max_filesize "10M"
#php_value session_save_path "tmp/cache"

#php_flag magic_quotes_gpc Off
#php_flag register_globals Off
#php_flag session.use_trans_sid Off

# (this is important, so uncomment if your host permit)
#Options -Indexes
#ServerSignature Off

#Options +FollowSymLinks

# To prevent E_STRICT problems with PHP 5.3+ you can uncomment the following lines
# Note: These settings should only be enabled for production sites!
#php_flag display_startup_errors 0
#php_flag display_errors 0
#php_flag html_errors 0
#php_value docref_root 0
#php_value docref_ext 0

<IfModule mod_rewrite.c>
RewriteEngine on
#
#Sub-dir e.g: /cmsms
RewriteBase /

# 301 Redirect all requests that don't contain a dot or trailing slash to
# include a trailing slash
# but ignore POST requests.
#RewriteCond %{REQUEST_URI} !/$
#RewriteCond %{REQUEST_URI} !\.
#RewriteCond %{REQUEST_METHOD} !POST$
#RewriteRule ^(.*) %{REQUEST_URI}/ [R=301,L]

# Rewrites urls in the form of /parent/child/
# but only rewrites if the requested URL is not a file or directory
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [QSA]

#RewriteEngine On
#RewriteCond %{HTTP_HOST} !^www\.
#RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301]

</IfModule>

<IfModule mod_header.c>
# Disable ETags
Header unset ETag
FileEtag None
</IfModule>

<IfModule mod_deflate.c>
# Compress css, plaintext, xml, gif, and images in transport.
AddOutputFilterByType DEFLATE text/css text/plain text/xml image/gif image/jpeg image/png
</IfModule>

<IfModule mod_expires.c>
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
# Set expires tags on various files... so that the browser wont attempt to reload them.
ExpiresActive On
ExpiresDefault "access plus 1 year"
<IfModule mod_header.c>
  # Setting cache control to public allowes proxy servers to cache the items too.
  Header set Cache-Control "public"
</IfModule>
</FilesMatch>
</IfModule>

A: You need to move the www to non-www redirect above the internal index.php rewrite. Additionally, I would recommend adding the L flag to the internal rewrite. This flag is required for the 'www' redirect as well. Lastly, the internal rewrite needs to use (.*) instead of (.+) as the former includes requests to the root, whilst the latter does not.
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

Currently, the request is internally re-written to index.php?page=$1, which becomes the new request URI, which is then appended to the next redirect if 'www' is not included. Swapping those two blocks around will solve the issue.
To redirect /index.php to /, place the following redirect above the 'www' redirect shown above.
RewriteRule ^index.php$ / [R=302,L]

To make that redirect permanent and cached by browsers and search engines, change 302 to 301.


text:
Q: How to transfer objects over network using java what is the library should I use ?
what are the functions that help me?

A: The easiest way is probably using serialization. Therefore, your object classes must implement serializable, so do have all of the members (primitves and most of the standard java classes already do this). This allows the mapping between object instances and byte streams at runtime.
You also need a protocol for transer. You can have a look at RMI, if you don't want to deal with streaming you byte streams over the wire, though this is not that difficult.
Using RMI however allows you build more powerful distributed java applications later.

A: ObjectOutputStream/ObjectInputStream.
The whole logic is approximately as follows. Adjust by the demands of your app.
Send:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(objectToSend);
oos.close();

byte[] bytes = baos.toByteArray();
socket.write(bytes);

Receive:
ObjectInputStream ois = new ObjectInputStream(socketInputStream);
MyObject mo = (MyObject)ois.readObject();

A: It Depends:
If the other endpoint is in Java then Java serialization might be the fastest way to implement. But note supporting Java Serialization is not a trivial task and can be a chore to maintain over time. Just google "Java serialization gotchas" for some examples.
If the other endpoint is not in Java or future maintainability and compatibility is a goal, then I would recommend a more general reusable encoding.
For this I would look into Google Protocol Buffers or Apache Thrift (I can post only 1 hyperlink).
Of course, there is always the option of using XML to encode your objects. :)
Personally, in our projects we have been using Google Protocol Buffers and in my opinion can't be beat for ease of use, maintainability, and most important in our case, compatibility between Protocol Buffer versions.

A: If you are in a multi-platform environment, you can use CORBA. Although it is a little complicated because you may need to control both endpoints and implement the Interface Definition Language (IDL) bindings.
A good alternative is using JSON. You just need to map the JSON structure into your Java objects.


text:
Q: Linux FTP server which can work with unsalted SHA256 hashes? Problem
Some old WS_FTP server stopped booting at work after a Windows update. The corresponding admin is long gone. The only information I have is :

*

*file structure

*user names

*unsalted SHA256 hash for each user

One of those hashes is:

5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

which corresponds to "password". I could check with : echo -n password | sha256sum.
I don't even know where the FTP clients are. Some of them are remote sensors to which I cannot get access. They were still sending data until the server stopped. The data isn't confidential but important to us nonetheless.
Attempts

*

*I tried running john the ripper on the hashes. It found 4 passwords out of 30.

*I tried to find a Linux FTP server which uses unsalted SHA256 hashes. I think it's too insecure so no server proposed it, at least not as default

*Some servers (e.g. vsftpd) delegate to htpasswd. I couldn't find a way to save an unsalted SHA256 hash, though.
Question
Is it possible to create a htpasswd hash with SHA256, without salt and only one round? The minimum seems to be a 8-byte salt and 1000 rounds with mkpasswd.
Is there another linux FTP server which can be configured to work with thoses hashes?
I don't care much about security, I'd just like to set-up an FTP server which accepts incoming connections from the sensors.

A: @Broco suggested to use pyftpdlib, which worked perfectly for my needs!
Here are the steps:

*

*Install a Linux server

*Install Anaconda

*Install pyftpdlib

*Create a json file with a dict of username, hash and folder

*Create a pyftpdlib script for an FTP server which compares the SHA256 hashes

*Redirect port 21 to port 8021

*Run it as a systemd unit as a non-privileged user

*Restart the ftp server automatically if the json file is modified.

Here's a template for the json file:
{
    "user1": {
        "folder": "users/user1",
        "sha256": "DFB0CE07EDF923F1F40BA56CC9BA9C396B53E3399E3164D60E35050BAA2BE9C9"
    },
    "user2": {
        "folder": "users/user2",
        "sha256": "5E884898DA28047151D0E56F8DC6292773603D0D6AABBDD62A11EF721D1542D8"
    }
}

Here's the script:
#!/opt/anaconda3/bin/python -u
#encoding: UTF-8
import re
import os
import hashlib
import json
from pathlib import Path
from pyftpdlib.authorizers import DummyAuthorizer, AuthenticationFailed
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.filesystems import AbstractedFS

FTP_FOLDER = Path("/media/ftp_data")

with open('input/ftp_users.json') as users_json:
    USERS = json.loads(users_json.read())

current_folder = Path.cwd().resolve()

def login_dump(username, password, success):
    if success:
        subfolder = 'logins'
        attr = 'w'
    else:
        subfolder = 'logins/failed'
        attr = 'a'
    logins_folder = current_folder.joinpath(subfolder)
    logins_folder.mkdir(parents=True, exist_ok=True)
    with open(str(logins_folder.joinpath(username)), attr) as user_file:
        # NOTE: Could write better hash directly, e.g. with `mkpasswd -m sha-512`
        user_file.write(password + "\n")

class SHA256Authorizer(DummyAuthorizer):
    def validate_authentication(self, username, password, handler):
        sha256_hash = hashlib.sha256(password.encode('ascii')).hexdigest().upper()
        try:
            # NOTE: Case sensitive!
            if self.user_table[username]['pwd'] != sha256_hash:
                login_dump(username, password, False)
                raise AuthenticationFailed
        except KeyError:
            login_dump(username, password, False)
            raise AuthenticationFailed
        login_dump(username, password, True)

authorizer = SHA256Authorizer()

for user, params in USERS.items():
    print("Adding user %r" % user)
    folder = FTP_FOLDER.joinpath(params['folder'])
    folder.mkdir(parents=True, exist_ok=True)
    authorizer.add_user(user,
                        params['sha256'].upper(),
                        str(folder),
                        perm="elradfmw",
                        msg_login="Welcome, %s!" % user)
handler = FTPHandler
handler.authorizer = authorizer
handler.banner = "FTP server"

class WindowsOrUnixPathFS(AbstractedFS):
    def ftpnorm(self, ftppath):
        # NOTE: Some old clients still think they talk to a Windows Server
        return super().ftpnorm(ftppath.replace("\\", "/"))

handler.abstracted_fs = WindowsOrUnixPathFS

handler.passive_ports = range(40000, 40500)
# NOTE: Port forwarding is needed because this script shouldn't be run as root.
# See https://serverfault.com/a/238565/442344
server = FTPServer((IP_ADDRESS, 8021), handler)
server.serve_forever()

The script logs the passwords in plain text, which is acceptable because the data isn't confidential. After a few months, I'll switch to vsftpd.


text:
Q: How to dynamically update my dataframe in shiny? Now I have a function to pick the right row from the data frame and add it to the new data frame. In order to display the data better, I hope to update the data frame dynamically through the shiny package for loop (that is,  update the dataframe every iteration)。I'd try many approaches but failed. Here are the minimal example.
ui:
ui = fluidPage(
    sidebarLayout(
        sidebarPanel(
            sidebarSearchForm(label = "numbers you woudle to append",textId = "num",buttonId = "btn")
        ),
        mainPanel(
            dataTableOutput("dt_test")
        )
    )
)

server:
server = function(input, output) {
    num <- eventReactive(input$btn,input$num) # press the button to update value
    ls_vars <- reactiveValues(test_dt=data.frame())
    observeEvent(input$btn,{
        for (i in 1:5) {
            dt_1 <- data.frame(num(),num()) # view it as the new row
            Sys.sleep(2)  # view it as the running time
            ls_vars$test_dt <- rbind(dt_1,ls_vars$test_dt)
            output$dt_test <- renderDataTable({ls_vars$test_dt})
        }})
}

Is there anyone can help me? Thank you!


text:
Q: Can computers take uniform samples from a polytope? For each $r \in \mathbb N $ write $\mathbb Z/ 10^r = \{a/10^r: a \in \mathbb Z\}$ and $P(r)$ for the lattice $(\mathbb Z/10^r)^N \subset \mathbb R^N$.
Suppose the plane $P \subset \mathbb R^N$ is well-behaved with respect to the lattices $P(r)$. That means each $P \cap P(r)$ has more than one element (it follows it is a nontrivial sublattice of $P$).
Now suppose the polytope $B \subset P$ has nonempty interior when considered as a subset of $P$. By choosing an orthonormal basis for $P$ we can define the Lebesgue-measure on $B$ normalised to have $\mu(B)=1$. Note this is independent of the choice of basis since the transition matrices are measure-preserving.
But there is another way to measure subsets of $B$ using the lattices $P(r)$. For each $E \subset B$  we define
$\nu_r(E) = |P(r) \cap E|/ |P(r) \cap B|$ and $\nu(E) = \lim \nu_r(E)$
Is there any reason to believe these two measures coincide? In general I'm sure they don't since there is no reason for $B$ to intersect any $P(r)$ nontrivially. For example let $P$ be a line of irrational slope.
If it helps we can also assume $B$ is given by linear constraints with positive integer coefficients.


text:
Q: how to run textcleaner imagemagick script from git bash I installed Git Bash on Windows system. Now I want to run textcleaner Imagemagick script from it. Which package do I need to download to run textcleaner script and how to set the path for that  script. Please help.

A: Steps to make textcleaner work:

*

*open git bash.

*navigate to the directory of your wish. This way you avoid writing long paths to your images and stuff (see also https://stackoverflow.com/a/22509024/8340945)

*insert the downloaded script in this directory.

*(as in this answer)

*

*chmod +x textcleaner

*./textcleaner ... arguments ..


text:
Q: What needs to be done to update lablst.sty? This question is related to the question How to get a list of all the labels in a LaTeX document.  According to the author of lablst.sty, you can use lablst as a global option to documentstyle as \documentstyle[11pt,lablst]{article} to produce (a list of) label definitions at the end of the document.
Can this be updated so that it can be used with documentclass?

A: You can try with this newlablst.sty to be called by \usepackage{newlablst}:
\RequirePackage{atveryend,ltxcmds}
\AtVeryEndDocument{\@lablst}
\def\@lablst{
  \parindent 0pt \parskip 0pt
  \normalsize
  \newwrite \labfile \relax
  \immediate\openout \labfile =\jobname.lab\relax
  {\def\toc{toc}
   \def\@writefile##1##2{\def\temp{##1}%
     \ifx\temp\toc
       \immediate\write\labfile{\unexpanded{##2}}%
     \fi}
   \def\newlabel##1##2{\immediate\write\labfile{\string\newlabel{##1}{##2}}}
   \def\bibcite##1##2{\immediate\write\labfile{\string\bibcite{##1}{##2}}}
   \makeatletter
   \input \jobname.aux }
   \immediate\closeout\labfile
   \def\newlabel##1##2{\par \hbox to \textwidth
     {\hfill\makebox[10em][l]{\ttfamily ##1}\makebox[3.5em][l]{\first
      ##2}\hspace{1em}Page:\makebox[3em][r]{\second ##2}\hspace{4em}}}
   \ltx@ifpackageloaded{hyperref}
     {\def\first##1##2##3##4{##1}\def\second##1##2##3##4{##2}}
     {\def\first##1##2{##1}\def\second##1##2{##2}}
   \def\bibcite##1##2{\par\makebox[2in][l]{\ttfamily ##1}[##2]\par}
   \input \jobname.lab
   \clearpage
}

EDIT
This is perhaps a more robust version; it's just the more modern lablst.tex:
\RequirePackage{atveryend,ltxcmds}
\def\@lablst{%
  \ltx@ifpackageloaded{hyperref}
    {\long\def\x@firstoftwo##1##2##3##4{##1}%
     \long\def\x@secondoftwo##1##2##3##4{##2}}
    {\long\def\x@firstoftwo##1##2{##1}%
     \long\def\x@secondoftwo##1##2{##2}}
  \let \@mlabel \@gobbletwo
  % No protection needed:
  %
  \let \protect \relax
  % Better formatting?:
  %
  \let \raggedright  \relax
  % Only write out toc entries:
  %
  \def \@writefile ##1##2{%
    \def\lablst@tempa{##1}%
    \def\lablst@tempb{toc}%
    \ifx \lablst@tempa\lablst@tempb
      \par{##2}\par\nobreak
      \vspace{3pt}%
    \fi
  }
  % Allow characters like ^ _ to be printed `verbatim'.
  %
  \def\@lablstverb##1{%
    \def\lablst@tempa{##1}%
    {\ttfamily\expandafter\strip@prefix\meaning\lablst@tempa}}%
  % For first run:
  %
  \def \newlabel ##1##2{%
    \par
    \hbox to \textwidth{%
      \hfill\makebox[10em][r]{\@lablstverb{##1}}%
      \hspace{1em}\makebox[4.5em][l]{\x@firstoftwo ##2}%
      Page:
      \makebox[2.5em][r]{\x@secondoftwo ##2}%
      \hspace{4em}}\par
  }
  \let \bibcite \@gobbletwo
  {\Large \sl Logical labels within sections}
  \input{\jobname.aux}
  % For second run:
  %
  \def \bibcite ##1##2{\par
    \hbox to \textwidth{%
    \hfill\makebox[2in][r]{\@lablstverb{##1}}\hspace{1em}[##2]\hspace{4em}}}
  \let \newlabel \@gobbletwo
  \let \@writefile \@gobbletwo
  \par
  \vspace{2\baselineskip}
  {\Large \sl Bibliography logical labels}
  \input{\jobname.aux}\clearpage
}

This seems to works also with hyperref.


text:
Q: Get code from REPL If I'm entering code into the REPL using clisp, as in the program you get when you do sudo apt-get install clisp, is there a way to take all the code you've entered so far and save it in a file? I'm a Lisp beginner so I don't know if that's a ridiculous request or not.

A: You can start output recording with the function DRIBBLE.
Other than that I would run CLISP from a terminal program which can save input / output.
As the minimum I would usually use Emacs, run a shell via M-x shell and start the Lisp there. That way the I/O goes into an Emacs shell buffer.
There is also SLIME, which sets up quite a bit more functionality inside Emacs to communicate with a 'slave' Common Lisp. A 'listener' (aka REPL) is part of that.

A: There is probably a better way, but... If you are using a decent terminal program, you should be able to select the text in the terminal and save it to file. This would include your typed input as well as output, so you would have to manually remove the output.


text:
Q: Conditionally updating roles in WordPress I actually want to create an easy function but it doesn't seem to work.
I want that when a user logs to his account on Wordpress to change his role (subscriber -> directory_1) on some condition (easy in this case to test, it should change everytime, but still not working).
Here is my code :
add_action('wp_login', 'update_roles');

function update_roles()
{
   global $wpdb;
   $author = wp_get_current_user();
   if(current_user_can('subscriber'))
   {
       $author->remove_role( 'subscriber' );
       $author->add_role( 'directory_1' );
   }
}

Thanks for the help!

A: You should be using wp_update_user() to update a user's role. After you have added a role using add_role(), you can do something like this:
function custom_update_roles( $user_login, $user ) {

    if ( ! empty( $user->roles ) && is_array( $user->roles ) ) {

        if ( in_array( "subscriber", $user->roles ) ) {
            $user_id = wp_update_user( array( 'ID' => $user->ID, 'role' => 'directory_1' ) );

            if ( is_wp_error( $user_id ) ) {
                // Error.
            } else {
                // Success.
            }
        } else {
            // This user is not a subscriber.
        }
    }
}
add_action( 'wp_login', 'custom_update_roles', 10, 2 );

Refs:

*

*http://codex.wordpress.org/Function_Reference/wp_update_user

*http://codex.wordpress.org/Function_Reference/add_role


text:
Q: Is drawRect ---- leaking memory I am currenty seeing a problem with memory leaks, it seems to come from this code:
- (void)drawRect:(CGRect)rect
{

    CGImageRef cgImage = CGBitmapContextCreateImage(offScreenBuffer);
    UIImage *uiImage = [[UIImage alloc] initWithCGImage:cgImage];

    CGImageRelease(cgImage);

    [uiImage drawInRect:self.bounds];
    [uiImage release];

}

this method is called from touches events ...
-(void)drawPoint:(UITouch *)touch {

    currentLoc = [[PointLocation alloc] init];

    currentLoc.location = [touch locationInView:self];

    self.previousPoint = self.point;

    self.point = currentLoc;
    [self drawToBuffer];

    [currentLoc release];

}

and this is draw to buffer....
-(void)drawToBuffer {

    CGFloat color[4] = {R,G,B,A};

    if (self.previousPoint != nil) {
    CGContextSetRGBStrokeColor(offScreenBuffer, color[0],color[1],color[2],color[3]);

    CGContextBeginPath(offScreenBuffer);
    CGContextSetLineWidth(offScreenBuffer, lane);
    CGContextSetLineCap(offScreenBuffer, kCGLineCapRound);

    CGContextMoveToPoint(offScreenBuffer, previousPoint.location.x, previousPoint.location.y);
    CGContextAddLineToPoint(offScreenBuffer, point.location.x, point.location.y);

    CGContextDrawPath(offScreenBuffer, kCGPathStroke);

}
 [self setNeedsDisplay];

}

this is really slow....:( And I don't know why...
Every single time I draw in the selected view, this is called, but every time I need to create an image and show it on the screen. Is there any possibility how to do this another way??

A: Given this information the only possible leak that I can imagine could be related to offScreenBuffer.
If you show more code or the instruments traces it might help find the problem.
Also given the "SIZE" of the memory leak you can see if it is the image which if leaking or its something else and you are misreading the instruments reports.

A: The posted code inside drawRect should not be showing any leaks, as the images are properly released.

A: I currently solved this problem. It was a problem of getting saved to data memory one again a image of defined size. I need to create a drawing api from the beginning, it took some time, but it was better than updating unfunctional version. Thanks all for cooperation =)


text:
Q: Re-constraining views in Constraint Layout programmatically I have a constraint layout with a number of views and I wanted to sort them programmatically. I tried using ConstraintSet but it's not working as expected.
I created a sample app to demonstrate the problem
Here's the activity_main.xml file.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    android:theme="@style/Theme.MaterialComponents.DayNight">
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/leftGuide"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.02" />
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/rightGuide"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.98" />
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/topGuide"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.02" />
    <com.google.android.material.card.MaterialCardView
        android:id="@+id/myApp"
        android:layout_width="0dp"
        android:layout_height="117dp"
        app:cardBackgroundColor="#FFFDE7"
        app:cardCornerRadius="22dp"
        app:cardElevation="3dp"
        app:layout_constraintEnd_toStartOf="@id/cat"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toEndOf="@id/leftGuide"
        app:layout_constraintTop_toBottomOf="@id/topGuide"
        app:layout_constraintWidth_percent="0.3">
        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:layout_marginBottom="8dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher_background" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center"
            android:layout_marginBottom="3dp"
            android:maxWidth="100dp"
            android:maxHeight="60dp"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="#EB2B2313"
            android:textSize="14sp" />
    </com.google.android.material.card.MaterialCardView>
    <com.google.android.material.card.MaterialCardView
        android:id="@+id/cat"
        android:layout_width="0dp"
        android:layout_height="117dp"
        app:cardBackgroundColor="#FFFDE7"
        app:cardCornerRadius="22dp"
        app:cardElevation="3dp"
        app:layout_constraintEnd_toStartOf="@id/kicks"
        app:layout_constraintStart_toEndOf="@id/myApp"
        app:layout_constraintTop_toTopOf="@id/topGuide"
        app:layout_constraintWidth_percent="0.3">

        <ImageView
            android:layout_width="57dp"
            android:layout_height="57dp"
            android:layout_gravity="center"
            android:layout_marginBottom="6dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher_foreground" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center"
            android:layout_marginBottom="3dp"
            android:maxWidth="100dp"
            android:maxHeight="60dp"
            android:text="cat"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="#EB2B2313"
            android:textSize="14sp" />
    </com.google.android.material.card.MaterialCardView>
    <com.google.android.material.card.MaterialCardView
        android:id="@+id/kicks"
        android:layout_width="0dp"
        android:layout_height="117dp"
        app:cardBackgroundColor="#FFFDE7"
        app:cardCornerRadius="22dp"
        app:cardElevation="3dp"
        app:layout_constraintEnd_toStartOf="@id/rightGuide"
        app:layout_constraintStart_toEndOf="@id/cat"
        app:layout_constraintTop_toTopOf="@id/topGuide"
        app:layout_constraintWidth_percent="0.3">
        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:layout_marginBottom="6dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher_foreground" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center"
            android:layout_marginBottom="3dp"
            android:maxWidth="100dp"
            android:maxHeight="60dp"
            android:text="kicks"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="#EB2B2313"
            android:textSize="14sp" />
    </com.google.android.material.card.MaterialCardView>
</androidx.constraintlayout.widget.ConstraintLayout>

Here's how it looks like.
But i want to change the constraints programmatically to look like this
This is what I've tried
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myApp.setOnClickListener {
           val constrain = ConstraintSet()
           constrain.apply {
               clone(this@MainActivity,R.layout.activity_main)
               connect(myApp.id,ConstraintSet.END,rightGuide.id,ConstraintSet.START,0)
               connect(myApp.id,ConstraintSet.START,kicks.id,ConstraintSet.END,0)
               connect(cat.id,ConstraintSet.START,leftGuide.id,ConstraintSet.END,0)
               connect(cat.id,ConstraintSet.END,kicks.id,ConstraintSet.START,0)
               connect(kicks.id,ConstraintSet.END,myApp.id,ConstraintSet.START,0)
               connect(kicks.id,ConstraintSet.START,cat.id,ConstraintSet.END,0)

               applyTo(grid)
            }
        }
    }
}

But this is what I get

A: It seems it's a bug with constraint layout 2.0.0.beta2.
After upgrading to beta 4 (latest version currently), it produces the expected outcome.


text: Q: Can you color label a file/folder in Finder using a keyboard shortcut? Is there a faster way to label a selected file or folder without having to right-click and choosing a colour ? Such as a keyboard shortcut or another method to do this ?


text:
Q: Lua references between objects I implemented Simple Lua class in C. Usage of class:
require("test")
function foo()
    local t1 = test()
    local t2 = test()
    t1:attach(t2)
    return t1
end
o = foo()
-- some code
o = nil

attach function:
int class_attach(lua_State *L)
{
    module_data_t *mod = luaL_checkudata(L, 1, "test");
    luaL_checktype(L, 2, LUA_TUSERDATA);
    module_data_t *child = lua_touserdata(L, 2);
    printf("%p->%p\n", (void *)mod, (void *)child);
    return 0;
}

After return from function t2 object is cleaned by gc.
Is it possible to prevent that. Set reference between t1 and t2 objects? (calling __gc metamethod (of t2 object) only after parent module (t1) is cleaned).
Simple way is use table:
function foo()
    ret = {}
    ret[1] = test()
    ret[2] = test()
    ret[1]:attach(ret[2])
    return ret
end

but that is not fun way.
Thanks!

A: I've had the same issue in the past. The simple reason for this is that Lua doesn't know about the connection established in C code (there's none right now, but I guess it's going to be done somewhere).
You don't have to do the table approach, just link the two objects/tables/whatever on the Lua side as well:
function foo()
    local t1 = test()
    local t2 = test()
    t1:attach(t2)
    t1._dummy_link = t2
    return t1
end

Just keep in mind that's only good for 1:1 relationships. For more complex stuff you'll still have to use some kind of table or a similar approach. The probably cleanest way to do this would be doing the linking on the Lua side and just adding a callback to C in case there's C code to be run as well.

A: You can set it in the Lua registry. This is effectively a global table which can only be accessed in C code. You can set registry[t1] = t2;. As long as you unset this appropriately in t1's __gc. This can also scale to 1:n mappings, as you could do, for example, registry[t1].insert(t2) for multiple "children".


text:
Q: How can I see which button has been pressed in php? I'm quite new to php so this might seem very easy. I have a table called 'products' and for each product in that table I want to create a button with the id of that product. I have no problem creating the buttons but I can not see which of the buttons has been pressed.
How can I solve this?
This is my code:
$sql = "SELECT id FROM `products` WHERE subcategory = 'laptop' ORDER BY id desc limit 1";
$query = mysql_query($sql);
$id = mysql_result($query,0);
for($i=1; $i<= $id; $i++){
    $product2 = R::load('products', $i);
    echo "<input type='submit' name='$product2->id' value='Add to cart'/>";
}

Thank you !

A: assign a value to the button/input
<input type="submit" name="btn" value="button1" />
<input type="submit" name="btn" value="button2" />
<input type="submit" name="btn" value="button3" />

<?php echo filter_input(INPUT_POST, 'btn'); ?>

or
<input type="submit" name="btn1" value="button1" />
<input type="submit" name="btn2" value="button2" />
<input type="submit" name="btn3" value="button3" />

<?php if (filter_has_var(INPUT_POST, 'btn1')) { echo "button 1 clicked"; } ?>


text:
Q: WordPress AMP for Custom Post Types with own URL I want to use AMP with a Custom Post Type in WordPress.
For this reason, I've added the following code to my functions.php:
add_action( 'amp_init', 'xyz_amp_add_review_cpt' );
function xyz_amp_add_review_cpt() {
    add_post_type_support( 'xyz-review', AMP_QUERY_VAR );
}

The code is from the official plugin documentation: https://github.com/Automattic/amp-wp/blob/master/readme.md#custom-post-type-support
After that I've flushed my rewrite rules as they said.
Unfortunately it doesn't work for my CPT. Only for normal posts.
I think it's because my CPT has no slug. The URL is the same as for posts: example.com/custom-post-type-post/
If I add a slug to the CPT, the AMP will work.
But I couldn't do that.
Is there any other solution to fix this?

A: Try this
add_rewrite_rule( '^([^/]+)+[\/]+(amp)/?$', 'index.php?post_type=xyz-review&name=$matches[1]&amp=1', 'top' );


text:
Q: I like using ChartJS for it's simplicity, but I can't figure out how to make a bar graph that will graph positive and negative values starting at zero The goal is to make a bar chart that looks like this:
https://s3.amazonaws.com/uploads.hipchat.com/9783/747489/YXnBVg3j1WhmCoc/Screen%20Shot%202015-01-15%20at%2010.56.58%20PM.png
I can get the line graph no problem, and I haven tried overlaying the graphs yet, the main issue I'm running into is getting a bar graph that starts at 0 and has both a positive and a negative data set graphed at the same time as shown in the attached image.  Any help would be appreciated, right now all I can manage are bar graphs graphed from the bottom of the graph not from the center point (zero).


text:
Q: Selenium-webdriver dropdownlist not work php I want to choose one first drop-down list, then the second, but I can not even cope with the first
Please explain why I get the error
<?php
require_once "phpwebdriver/WebDriver.php";
$webdriver = new WebDriver("localhost", "4444");
$webdriver->connect("firefox");
$webdriver->get("http://namami.org/PKstate.aspx");
//$element = $webdriver->findElement('css selector', 'select[id="DdlState"] option[value="Assam"]');
$element = $webdriver->findElement("css selector", 'select[id="DdlState"] option[value="Assam"]')->click();
//$element=$webdriver->findElement(By.cssSelector("#DdlState")).click();
//$element->click();
$webdriver->close();
?>

Fatal error: Call to undefined method WebDriver::findElement() in C:\xampp\htdocs\temp\1.php on line 7
I could not find an answer. Use XAMPP.
I would be grateful for your help.
Regards Anton

A: You most likely need to delay the click.
The item that you're attempting to grab with Selenium is generated by Javascript, and I think what's happening is that the Selenium is trying to find something that isn't quite rendered yet.
Try calling
sleep(1); to delay the Selenium action and see if that works:
<?php
require_once "phpwebdriver/WebDriver.php";
$webdriver = new WebDriver("localhost", "4444");
$webdriver->connect("firefox");
$webdriver->get("http://namami.org/PKstate.aspx");
sleep(1); // allow the javascript some time to load
//$element = $webdriver->findElement('css selector', 'select[id="DdlState"] option[value="Assam"]');
//$element = $webdriver->findElement("css selector", 'select[id="DdlState"] option[value="Assam"]')->click();
////$element=$webdriver->findElement(By.cssSelector("#DdlState")).click();
////$element->click();
//$webdriver->close();
//?>

A: <?php
    require_once "phpwebdriver/WebDriver.php";
    $webdriver = new WebDriver("localhost", "4444");
    $webdriver->connect("firefox");
    $webdriver->get("http://namami.org/PKstate.aspx");
    sleep(1); // allow the javascript some time to load
    $element = $webdriver->findElement('id', 'DdlState');
    $select = new Select($element);
    $select->selectByValue("Assam");
    //?>


text:
Q: Experimental design: Same randomly selected stimuli versus different randomly selected stimuli in every subject In an experiment, we're going to present randomly generated stimuli to multiple subjects one trial at a time and measure neural responses to them. The stimuli are randomly generated to satisfy the conditions we want to compare, say for example half of the trials will use stimuli randomly drawn from an infinite pool of condition A stimuli and half will be drawn from an infinite pool of condition B stimuli.
It's the same amount of effort for us to use the same random generation of the stimuli to every subject, versus randomly generating entirely new stimuli for every subject while always having half of the stimuli from condition A and half of the stimuli from condition B. Our interest is to make inferences on the neural responses to condition A versus condition B. Which of the two would be preferred?


text:
Q: New event count on each day I have a table Events which has 2 columns dt (Date) and event. I am trying to get the new event count for each day. For e.g. if the event appeared today and tomorrow, then it should only be counted for today (as it is show for the first time) and should be excluded from tomorrow's count.
+------------+-------+
| dt         | event |
+------------+-------+
| 2019-02-01 | u1    |
| 2019-02-01 | u2    |
| 2019-02-01 | u3    |
| 2019-02-01 | u4    |
| 2019-02-01 | u1    |
| 2019-02-02 | u5    |
| 2019-02-02 | u1    |
| 2019-02-02 | u6    |
| 2019-02-02 | u4    |
| 2019-02-03 | u8    |
| 2019-02-03 | u9    |
| 2019-02-03 | u6    |
+------------+-------+

I'm trying to get the below output:
+------------+-------------------------+
| dt         | count(distinct c.event) |
+------------+-------------------------+
| 2019-02-01 |                       4 |
| 2019-02-02 |                       2 |
| 2019-02-03 |                       2 |
+------------+-------------------------+

The query I am using is:
with cte (dt,event,rnk) as
(
select dt,
event,
row_number() over (partition by dt order by event) as rnk
from events order by event
)
select e.dt, count(distinct c.event) from events e left join cte c
on  e.event <> c.event where e.dt = c.dt
group by 1;

But I am not able to filter out the already appeared event from the previous day. I believe something small is missing. The result from my query is:
+------------+-------------------------+
| dt         | count(distinct c.event) |
+------------+-------------------------+
| 2019-02-01 |                       4 |
| 2019-02-02 |                       4 |
| 2019-02-03 |                       3 |
+------------+-------------------------+

I am not sure if LEAD / LAG function can help solve the issue.
Also is there a way that I could achieve this without using any joins.
Table creation and insertion queries:
create table events (dt Date, event varchar(5));

insert into events values('2019-02-01', 'u1');
insert into events values('2019-02-01',  'u2');
insert into events values('2019-02-01',  'u3');
insert into events values('2019-02-01',  'u4');
insert into events values('2019-02-01',  'u1');
insert into events values('2019-02-02',  'u5');
insert into events values('2019-02-02',  'u1');
insert into events values('2019-02-02',  'u6');
insert into events values('2019-02-02',  'u4');
insert into events values('2019-02-03',  'u8');
insert into events values('2019-02-03',  'u9');
insert into events values('2019-02-03',  'u6');

A: You can use row_number to find when is the first day the event appear.
SQL DEMO
WITH ranks as (
    SELECT *, row_number() over (partition by event order by dt) as rn
    FROM events
)
SELECT dt, COUNT(event)
FROM ranks
WHERE rn = 1
GROUP BY dt

OUTPUT
|         dt | count |
|------------|-------|
| 2019-02-01 |     4 |
| 2019-02-02 |     2 |
| 2019-02-03 |     2 |

A: Here's a solution for older versions: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=12ba0196cf90994d3c9d853ac62405fe
CREATE TABLE events
    (`dt` varchar(10), `event` varchar(2))

INSERT INTO events
    (`dt`, `event`)
VALUES
    ('2019-02-01', 'u1'),
    ('2019-02-01', 'u2'),
    ('2019-02-01', 'u3'),
    ('2019-02-01', 'u4'),
    ('2019-02-01', 'u1'),
    ('2019-02-02', 'u5'),
    ('2019-02-02', 'u1'),
    ('2019-02-02', 'u6'),
    ('2019-02-02', 'u4'),
    ('2019-02-03', 'u8'),
    ('2019-02-03', 'u9'),
    ('2019-02-03', 'u6')

SELECT dt, COUNT(*) total FROM
(SELECT event, MIN(dt) dt
      FROM events
      GROUP BY event) x
GROUP BY dt

Actually, the subquery is all you need; the rest can be handled in application code.


text:
Q: Pass Information with URL redirection We are working on an existing application where web services (tomcat) as well as UI (nginx) applications are hosted on separate containers. One of the service application is used for sending login request (SAML request) to identity provider (ping). Here are the steps for user login to the system:

*

*User loads the application (domain URL: https://ui.domain.com), it loads the UI where it checks for logged in user (JWT token string generated for user/role) on local storage and when not found, it redirects to ping (IDP) for authentication.

*Once authenticated with ping, it calls the spring controller which is configured for the success URL on service application (https://api.domain.com/auth-service/auth).

*This controller service (/auth), gets the SAML response sent by ping and processes it further to get user details and generates the JWT token for the user and redirects the user to UI (https://ui.domain.com).

Problem Statement:
To pass the token to UI, the JWT token string is added to URL by using
   redirectAttributes.addAttribute("auth-token", token);
With the above, it shows up in the address bar like: https://ui.domain.com/?auth-token=
This has raised a concern with respect to security as the token is displayed on address bar and exposed which can be decoded to get user information.
Current Approach (tried):

*

*Before redirection from controller to UI, tried to set cookie
Cookie cookie = new Cookie("auth-token", token);
cookie.setMaxAge(-1);
cookie.setPath("https://ui.domain.com");
response.addCookie(cookie);

However we couldn't find the cookie from UI.

*

*We tried to set it to response header too.
response.addHeader("auth-token", token);
Since it is a redirection, the adding to response doesn't help.
Further trials:
We are also putting a thought about changing the approach of authentication controls where after ping authentication is done, the success URL can be replaced with UI url rather than service URL, i.e.
Current: saml.sso.default-success-url= https://api.domain.com/auth-service/auth
Proposed: saml.sso.default-success-url= https://ui.domain.com/
With the above, the SAML response supposed to go directly to UI (after ping authentication is successful).
However we couldn't get the response in UI and it also behaves like ping is doing a redirection to UI and due to the same reason, UI doesn't get it.
Any ideas and suggestions over this would be great.


text:
Q: c# how to while loop textboxes so it changes textbox every loop? I'm pretty new to c# and I'm struggling with this,
I'm trying to make a program that can send "items" to the names I type in the textboxes all at once with SQL stored produce.
I want to while loop textboxes so it changes from textBox1 to textBox2 and so on when it loops. I want to do this cause I have 45 texBoxes and a loop should be good I guess.
this is what I've tried:
int x = 1;
while (x < 46)
{
    cmd.CommandText = "EXECUTE usp_GiftItem @sendUser, @SendNickname, @receiver, @itemname, @text, @paymentType, @bOutput";
    cmd.Parameters.Clear();
    cmd.Parameters.Add("@SendUser", SqlDbType.VarChar).Value = "123";
    cmd.Parameters.Add("@SendNickname", SqlDbType.VarChar, 50).Value = textBox89.Text;
    cmd.Parameters.Add("@receiver", SqlDbType.VarChar, 50).Value = textbox(x).Text;
    cmd.Parameters.Add("@itemname", SqlDbType.VarChar).Value = textBox80.Text;
    cmd.Parameters.Add("@text", SqlDbType.VarChar, 1024).Value = textBox88.Text;
    cmd.Parameters.Add("@paymentType", SqlDbType.VarChar).Value = "0";
    cmd.Parameters.Add("@bOutput", SqlDbType.VarChar).Value = "1";
    cn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show("Item sent", "Success");
    cn.Close();
    x++;
}

The problem is at @recivers value
I hope you there is a solution to this.
Thank you, Much appreciated

A: TextBox[] textBoxes = new TextBox[] { textBox1, textBox2, ... };
while(x ...)
{
    something[x] = textBoxes[x].Text;
}

A: You can simplify things if you do some preparation first. To example, you can create an array of items, where index of item is a TextBox number and item itself is an object what will be used to generate bold part: cmd.Parameters.Add( "@blablabla", type, num ).Value .
So:
 public class MyData
 {
     public string Text;
     public SqlDbType Type;
     public int Number;

     public MyData(string text, SqlDbType type, int number = 0)
     {
         Text = text;
         Type = type;
         Number = number;
     }
 }

 MyData[] data = new MyData[45] { new MyData("@bOutput", SqlDbType.VarChar), new MyData(...), ... };
 TextBox[] control = new TextBox[45] {textBox1, textBox2, ... };

 for(int i = 0; i < 45; i++)
     cmd.Parameters.Add(data[i].Text, data[i].Type, data[i].Number).Value = control[i].Text;

There are still things to improve, to example, instead of enumerating TextBox'es you may want to find them on the form (form1.Controls). Instead of generating data[] - it can be a part of TextBox.Tag, where you parse it and then generate parameters. Processing of the Number can be optional, etc..
But this should give you an idea.


text:
Q: So,I made this simple C program to give output,so it is correct for positive and zero integer values but it is coming wrong for negative even and odd How to get out of this first if else construct because when I input Negative values,because the condition here is checked and then it goes to the last else statement where this just prints zero
 #include<stdio.h>
      int main() {
         int x;
      scanf("%d", &x);

 if(x>0)
{

    printf("Positive");
    {
        if(x%2==0)
        {

            printf("Even");

        }
        else
        {

            printf("Odd");
        }

    }

I want this to be executed when I input negative values,but I'm unable to do so
    if(x<0)
    {

 printf("Negative");

        {

            if(x%2==0) {

                printf("Even");

            }
            else {

                printf("Odd");

            }

        }

    }

}

else {

    printf("Zero");

}
return 0;
}

A: Just reindent your code you will find strange { like the one after  printf("Positive");
Juste removing this strange { and fixing your coding style will be:
#include<stdio.h>
int main() {
    int x;
    scanf("%d", &x);

    if ( x > 0 ) {
        printf("Positive");
        if ( x % 2 == 0 ) {
            printf("Even");

        } else {
            printf("Odd");
        }
    } else if( x < 0 ) {
        printf("Negative");
        if( x % 2 == 0 ) {
            printf("Even");
        } else {
            printf("Odd");
        }
    }
    else {
        printf("Zero");
    }
    return 0;
}

easier to read, easier to debug

A: It seems the problem is an incorrect nesting of compound statements.
I can suggest the following solution.
#include <stdio.h>

int main( void )
{
    enum { Negative = -1, Zero = 0, Positive = 1};

    printf( "Enter a number: " );

    int x = 0;
    scanf( "%d", &x );

    int sign = ( 0 < x ) - ( x < 0 );

    switch (sign)
    {
    case Negative:
        printf( "Negative " );
        break;
    case Zero:
        puts( "Zero" );
        break;
    case Positive:
        printf( "Positive " );
        break;
    }

    if (sign != 0)
    {
        puts( x % 2 == 0 ? "even." : "odd." );
    }
}

The program output might look like
Enter a number: 10
Positive even.


text:
Q: httpwebrequest getresponse() does not return any content whereas fiddler shows content I created the GetCourses() method where I am using HttpWebRequest to request data from the Url shown.  If I copy paste the url in a browser, the browser will show xml data.  I also used fiddler to do the some request.  On fiddler it says that the data is encoded and i have to decode it. So, I clicked on the decode and I can see the XML. However, using the code below I get back Content-Length=-1.
public static void GetCourses()
    {
        try
        {
            HttpWebRequest requestForItCourse =
               (HttpWebRequest)WebRequest.Create("http://www.mnsu.edu/schedule/direct.php?action=courses&term=20135&subject=it");
            requestForItCourse.AutomaticDecompression = DecompressionMethods.GZip|DecompressionMethods.Deflate;
            HttpWebResponse responseFromMnsuDirectPhp =
                (HttpWebResponse)requestForItCourse.GetResponse();

            Stream dataStream = responseFromMnsuDirectPhp.GetResponseStream();
            responseFromMnsuDirectPhp.Close();
//Parse and insert courses into the database
        }
        catch (Exception ex)
        {

        }
    }

A: You need read the response stream before close the response.
Try this:
HttpWebRequest requestForItCourse = (HttpWebRequest)WebRequest.Create("http://www.mnsu.edu/schedule/direct.php?action=courses&term=20135&subject=it");
requestForItCourse.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
HttpWebResponse responseFromMnsuDirectPhp = (HttpWebResponse)requestForItCourse.GetResponse();

StreamReader dataStream = new StreamReader(responseFromMnsuDirectPhp.GetResponseStream());
string data = dataStream.ReadToEnd();

responseFromMnsuDirectPhp.Close();
dataStream.Close();

A: This worked when I ran it. You need to read the stream before closing it. As a side note, many people prefer to have their Streams automatically closed by using the using keyword.
try
{
    HttpWebRequest requestForItCourse = (HttpWebRequest)WebRequest.Create("http://www.mnsu.edu/schedule/direct.php?action=courses&term=20135&subject=it");
    requestForItCourse.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    HttpWebResponse responseFromMnsuDirectPhp =
                (HttpWebResponse)requestForItCourse.GetResponse();

    string raw_xml;
    using(var sr = new StreamReader(responseFromMnsuDirectPhp.GetResponseStream()))
    {
        raw_xml = sr.ReadToEnd();
    }

    //Parse and insert courses into the database
}
catch (Exception ex)
{

}


text:
Q: Showing that $G$ is sequentially closed in $X^*$ with the $\sigma(X^*,X)$ topology. Let be $X$ Banach space. Let $Y$ be a linear subspace of $X^*$ such that $Y$ is dense for $\sigma(X^*,X)$.
Let $\sigma(Y)$ be the sigma algebra on $X$ generated by sets of the form
$$\{x\in X:(\langle x, x_1^*\rangle,\ldots,\langle x, x_n^*\rangle)\in B\},\;\;\;\;(1)$$
for all $n\geq 1$ where $x_1^*,\ldots,x_n^*\in Y$ and $B$ is a Borel subset of $\mathbb{R}^n$. Let
$$G=\{x^*\in X^*: \text{ the map } x\to\langle x,x^*\rangle \text{ is }\sigma(Y)\text{-measurable}\}.$$
I want to show that $G$ is sequentially closed in $\sigma(X^*,X)$.
I would try to show that if $\{x_n^*\}$ is a sequence in $G$ such that $x_n^*\stackrel{*}{\rightharpoonup} x_0^*\in X^*$ then $x_0^*\in G$. For this I would need to show that for every Borel subset $B$ of $\mathbb{R}$, the set $(x_0^*)^{-1}(B)\in\sigma(Y)$. Now, weak$^*$ convergence implies that for all $x\in X$ we have $\langle x,x_n^*\rangle\to\langle x, x_0^*\rangle.$ But how to proceed from here?
I'm finding it difficult to write $(x_0^*)^{-1}(B)$ as countable unions/intersections of sets of the form (1).  Any hints?

A: You can repeat the argument in measure theory that shows that pointwise limits of measurable functions are measurable.
Assume for now that $x_n^*$ is real.
First, let $s_0^*=\sup_nx_n^*$, in the sense that $s_0^*(x)=\sup_nx_n^*(x)$. This is measurable:
$$
(s_0^*)^{-1}(a,\infty)=\{x:\ s_0^*(x)>a\}=\bigcup_n\{x:\ x_n^*(x)>a\}=\bigcup_n(x_n^*)^{-1}(a,\infty)\in\sigma(Y).
$$
As $\inf M=-\sup(-M)$, you also get that the infimum is measurable.
Next you go for $\limsup$: you have $\limsup_n x_n^*=\inf_m\sup_{n>m}x_n^*$, so measurable.  Now, if $x_n^*\to x_0^*$, you have $$x_0^*=\lim_nx_n^*=\limsup_nx_n^*, $$ so measurable.
In the general case, $x_n^*=\operatorname{Re}x_n^*+i\operatorname{Im}x_n^*$ is a linear combination of measurable, so measurable.

A: Your approach is already a good start.
Here is a sketch for the rest.
There is, however, a simplification: If you want to show that a map $f:X\to \mathbb R$
is measurable, it suffices to check that the preimages of sets of the form $(-\infty,c)$
for $c\in\mathbb R$ are measurable.
Thus you need to check the measurability of the set
$$
A_c:=(x_0^*)^{-1}((-\infty,c))=\{x \in X : \langle x,x_0^*\rangle < c\}
$$
is measurable.
For this, one can show the equivalence
$$
\langle x,x_0^*\rangle < c
\Leftrightarrow
\exists N_x\in\mathbb N \forall n\geq N_x : \langle x,x_n^*\rangle < c.
$$
Using this equivalence, one can rewrite $A_c$ as a
countable union of a countable intersection of measurable sets.
If I am not mistaken, this method should work for all sigma algebras on $X$.


text:
Q: Why does PHP substr() change ASCII carriage return byte? I was going to use a long string to manipulate a large number of bit flags, keeping the result string in Redis. However, stumbled upon a php bug (?). A byte that contains bits 00001101 read using substr() returns an unexpected value:
$bin = 0b00001101;  // 13 - ASCII Carriage return
$c = substr($bin, 0, 1);    // read this character
printf("Expectation: 00001101, reality: %08b\n", $c); // 00000001

Ideone
Is the assumption that substr() is binary-safe wrong? Also tried mb_substr(), setting encoding to 8bit with exactly the same result.

A: You're setting $bin to an integer 13
Using substr() against $bin is casting $bin to a string ("13")
You're reading the first character of that string ("1")
Using printf() with %b, you're explicitly casting that string back to an integer 1

the argument is treated as an integer, and presented as a binary number.

EDIT
This code should give the result that you're expecting
$bin = 0b00001101;  // 13 - ASCII Carriage return
$c = substr(chr($bin), 0, 1);    // read this character
printf("Expectation: 00001101, reality: %08b\n", ord($c)); // 00001101


text:
Q: M2.3-ce Failed to set ini option "session.save_path" when use memcached for session OS-Ubuntu18.04 I configured php7.2-fpm with memcached for session
session.save_handler = "memcached"
session.save_path = "127.0.0.1:11211"

Checked with cache-test.php. It was OK.
Configured Magento
app/etc/env.php
    'session' => [
            'save' => 'memcached',
            'save_path' => '127.0.0.1:11211'
    ],

But storefront page throws error
InvalidArgumentException: Failed to set ini option "session.save_path" to value "127.0.0.1:11211". in /home/magento/shop1/vendor/magento/framework/Session/SessionManager.php:632 Stack trace: #0 ...

I tried to use socket, but it didn't help either.
Could you advise how to fix it, please?

A: It seems https://devdocs.magento.com/guides/v2.3/config-guide/memcache/memcache_magento.html the guide is outdated.
It works without 'save_path' => '127.0.0.1:11211' in magento config.
app/etc/env.php
    'session' => [
            'save' => 'memcached',
    ],


text:
Q: $U(2,1)$ is quasi-split Let $$w = \begin{pmatrix} & & 1 \\ & -1 & \\ 1 & & \end{pmatrix}$$
Let $k = \mathbb{R}, K = \mathbb{C}$.  Let $G = \textrm{GL}_3$ as a group over $K$.  How can I show the existence of an algebraic group over $\mathbb{R}$ whose $\mathbb{R}$-points are
$$\{ x \in G(K) : w \space ^t \overline{x}^{-1}w = x \}$$
where the bar denotes entrywise complex conjugation?  How can I show the group is quasi-split, and compute a maximal split and anisotropic torus?

A: Let $\Gamma = \textrm{Gal}(K/k)$ with nontrivial element $\sigma$.  We have that $\Gamma$ acts on $\textrm{Aut}(G)$ by $\gamma.\phi(x) = \gamma \circ \phi \circ \gamma^{-1}$.  Define a map $c: \Gamma \rightarrow \textrm{Aut}(G)$ by setting $c(\gamma)(x) = w \space ^t x^{-1} w$.  Then $c$ is easily seen to be a one-cocycle, which is to say
$$ c(\gamma_1 \gamma_2) = c(\gamma_1) \gamma_1. c(\gamma_2)$$
for all $\gamma_i \in \Gamma$.  General theory of forms tells us that there exists an algebraic group $H$ over $k$, such that $H \times_k \overline{k} = G$, and the difference between action of $\Gamma$ on $G$ coming from $H$, and the usual action of $\Gamma$ on $G$, produces $c$.  In other words,
$$c(\sigma)(x) = \overline{\sigma.x}$$
for all $x \in G$ and $\gamma \in \Gamma$.  Thus as an algebraic group coming from $H$, $\Gamma$ acts on $G$ by $\sigma.x = w \space ^t \overline{x}^{-1}w$.   This group $H$ is called $U(2,1)$.
$U(2,1)$ is quasi-split:
Let $B, T$ be the usual Borel subgroup and maximal torus of $G$.  To say that they are defined over $\mathbb{R}$ (for the algebraic group coming from $U(2,1)$) is to say that they are stabilized by $\Gamma$.  One checks that
$$\sigma. \begin{pmatrix} x \\ & y \\ & & z \end{pmatrix} = \begin{pmatrix} \overline{z}^{-1} \\ & \overline{y}^{-1} \\ & & \overline{x}^{-1} \end{pmatrix}$$
and so $T$ is defined over $\mathbb{R}$, with $$T(\mathbb{R}) = \begin{pmatrix} re^{i \theta} \\ & e^{i \phi} \\ & & \frac{1}{r} e^{i \theta} \end{pmatrix}$$
Similarly, $B$ is defined over $\mathbb{R}$.  Its unipotent radical $U$ satisfies
$$U(\mathbb{R}) = \{ \begin{pmatrix} 1 & b & c \\ & 1 & \overline{b} \\ & & 1 \end{pmatrix} : |b|^2 = 2 \textrm{Re}(c) \}$$
Maximal split and anisotropic tori:
Let $e_1, e_2, e_3$ be the usual basis for $X(T)$.  Then $\Gamma$ acts as a group of automorphisms of $X(T)$ by $\gamma.\chi = \gamma \circ \chi \circ \gamma^{-1}$.  So it is easy to see that $\sigma.e_1 = -e_3, \sigma.e_3 = -e_1$, and $\sigma.e_2 = -e_2$.
Define
$$X^{\Gamma} = \{ \chi \in X(T) : \sigma.\chi = \chi \}$$
which has basis $e_1 - e_3$, and
$$X_0 = \{ \chi \in X(T) : \chi + \sigma.\chi = 0\}$$
which has basis $e_1 + e_3, e_2$.  Then the maximal split torus of $T$ is
$$A_0 = \bigcap\limits_{\chi \in X_0} \textrm{Ker } \chi = \begin{pmatrix} x \\ & 1 \\ & & x^{-1} \end{pmatrix}$$
and the maximal anisotropic torus is
$$T_0 =  \bigcap\limits_{\chi \in X^{\Gamma}} \textrm{Ker } \chi = \begin{pmatrix} 1 \\ & x \\ & & 1 \end{pmatrix} $$
Relative roots:
Let $\tilde{\Delta} = \{e_1 - e_2, e_2 - e_3\}$ be the base corresponding to $B$.  Let $\delta$ be the basis of $X(A_0)$ given by restriction of $e_1$ (or $-e_3$) to $A_0$.  Then the restriction of $\tilde{\Delta}$ to $X(A_0)$ is $\{\delta\}$.  In particular, no elements of $\tilde{\Delta}$ restrict to zero, so this gives another argument for why $U(2,1)$ is quasi-split.
Moreover, the root $e_1 - e_3$ restricts to $2 \delta$.  Thus $\Phi(A_0,G) = \{ \pm \delta, \pm 2 \delta \}$, and so the root system for $U(2,1)(\mathbb{R})$ is nonreduced.


text:
Q: Not seeing message properties that I set explicitly (Spring/JMS/MQ) Two separate processes are communicating via JMS over MQ.
The writer sets a string property:
new MessageAction() {
    public void actOn(Message message) throws JMSException {
        logger.debug("Setting message property (GmmThreadId, CASHFLOW-1234)");
        message.setStringProperty("GmmThreadId", "CASHFLOW-1234");
    }
});

This MessageAction is executed, as shown in the logs:
Setting message property (GmmThreadId, CASHFLOW-1234)

The reader uses a message selector to obtain this message. (using Spring's JmsTemplate v1 - an old version I know, but it's baked into our vendor's framework and we're compelled to use it.)
template.receiveSelected(queue, "GmmThreadId = 'CASHFLOW-1234' or GmmThreadId IS NULL");
The only messages on the queue are ones for which the logs show that the writer set the message property. In the logs for the reader, I enumerate the properties and also try to log the value of GmmThreadId. It also shows that the property GmmThreadId does not exist.
message property JMS_IBM_PutDate = 20111003
message property JMSXAppID = WebSphere MQ Client for Java
message property JMS_IBM_Format = MQSTR
message property JMS_IBM_PutApplType = 28
message property JMS_IBM_MsgType = 8
message property JMSXUserID = MUSR_MQADMIN
message property JMS_IBM_PutTime = 23551798
message property JMSXDeliveryCount = 2
message had GmmThreadId property of null

Note, if my message selector is only "GmmThreadId = 'CASHFLOW-1234'" then nothing is dequeued.
Using WebSphere MQ Explorer to view the message, I cannot find anywhere to view the application set message properties. The message type is MQSTR, if that makes any difference.
Both reader and writer applications are running in WebSphere v6.
Where am I going wrong?

A: As indicated by this thread the message properties will be suppressed if the destination type is 'MQ'. For me, this is configured in the WebSphere App Server console. I changed the queue type to 'JMS' and the message properties were persisted.


text:
Q: React-native open apps I have written a few apps with react-native and I would like to have a "Main" app to link to all those apps.
How can I open those apps from the "Main" app?
PS: All my apps are not and will not be uploaded to either app store or play store so app id or play id are not a solution

A: You can add  url in info.plist files and create URL for specific app. You can use Linking class of react-native to open the page.
there is demo for android and ios Read this documentation
For Android you can use this link:
Android deep link


text:
Q: Able to print, but can not scan from my printer I am using Artisan 725 on my Macbook and when I try to scan it says that the printer is not able to communicate - "Communication error has occurred." However, it will let me print.
Has anybody else had a similar issue with this printer/scanner and found a way to resolve it?

A: This is because the Epson Artisan 725 is considered an MFP or Multi-Function Printer.  This means it's actually two separate devices that just share the same footprint.  So, it is entirely conceivable that the printer drivers are readily available from Apple while the scanner driver isn't.
Heading over to their Support Page, it appears that they have both printer AND scanner drivers for macOS (Sierra) so you would need to install that driver for your scanner to work.


text:
Q: How to know event in kaplan Meier? Below is the Kaplan-Meier curve for  analysis of minutes from hospital admission to patient being setup in an ICU bed.

*

*For this analysis, what's the event? What's the time origin?

*Describe what the line on the Kaplan Meier Curve shows (what is on each axis, how can you read this to interpret it, etc.).

*Based on the way you found the median survival time, explain under what circumstances the median survival time would be undefined.

My proposed answers are;

*

*Assuming that events are ICU admission, the date of admission to the hospital (with hours and minutes0 will be time origin.

*X axis title should be "time to ICU dmission (minutes)", y axis title should be "No ICU admission". Each downword step represents admission to ICU (event happened).

*As I obtained median survival time visually from the curve (~ 75 minutes), the median will be not reached (undefined) if it doesn't reach below 50% of the y axis.
My edited plot is as follows;

Please let me know if my thoughts are correct.
Appreciate your precious advice.


text:
Q: Python округлить до 50 или 100 Как в python округлить число 478 до 500, а 472 до 450?

A: Чтобы округлить до 50, можно умножить на 2 и округлить до 100:
def round50(n):
    return round(n * 2, -2) // 2

Пример:
>>> round50(478)
500
>>> round50(472)
450

<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/3.4.0/www/src/brython.js"></script><body onload="brython()"><script type="text/python">
def round50(n):
    return round(n * 2, -2) // 2

def show(n):
    print(f"{n} -> {round50(n)}")

show(478)
show(472)

# try your own input
from browser import document
@document["mybutton"].bind("click")
def on_click(event):
    show(int(document["zone"].value))
</script>
<input id="zone" value="478"><button id="mybutton">round50</button></body>

A: Округление до числа, кратного x:
round(i/x)*x

Вот пример работы для x=50:
a = [400, 425, 449, 450, 451, 499, 500]

for i in a:
    print("{} => {}".format(i, round(i/50)*50))

Вывод:
400 => 400
425 => 400
449 => 450
450 => 450
451 => 450
499 => 500
500 => 500


text:
Q: QTabWidget tabPosition when using stylesheets I'm currently using stylesheets to theme an application.
Here is the stylesheet I use for QTabWidget:
/*QTabBar et QTabWidget*/
QTabBar::tab {
    background: qlineargradient(spread:pad, x1:0.5, y1:0, x2:0.5, y2:1, stop:0 rgba(73, 73, 74, 255), stop:1 rgba(40, 40, 40, 255));
    border: 1px solid rgb(190, 190, 190);
    max-height: 0.6em;
    min-width: 0.6em;
    padding: 5px;
    margin-left: -1px;
    margin-right: -1px;
}
QTabBar::tab:selected, QTabBar::tab:hover {
    background: qlineargradient(spread:pad, x1:0.5, y1:1, x2:0.5, y2:0, stop:0 rgba(39, 117, 219, 255), stop:1 rgba(107, 171, 249, 255));
}

QTabBar::tab:last {
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    margin-right: 0px;
}

QTabBar::tab:first {
    border-top-left-radius: 3px;
    border-bottom-left-radius: 3px;
    margin-left: 0px;
}

QTabBar::tab:only-one {
    border-radius: 3px;
    margin: 0px;
}

With this, when tabPosition is set to North or South, no problem. But with East or West, the TabBar's border is not properly styled.
Do someone know how to style a TabBar with tabPosition set to east/west?

A: From the Qt stylesheet reference page:

The :top, :left, :right, :bottom pseudo states depending on the
  orientation of the tabs.

So, for example, to apply your first css rule to the horizontal QTabBars:
QTabBar::tab:top, QTabBar::tab:bottom {
    background: qlineargradient(spread:pad, x1:0.5, y1:0, x2:0.5, y2:1, stop:0 rgba(73, 73, 74, 255), stop:1 rgba(40, 40, 40, 255));
    border: 1px solid rgb(190, 190, 190);
    max-height: 0.6em;
    min-width: 0.6em;
    padding: 5px;
    margin-left: -1px;
    margin-right: -1px;
}


text:
Q: Extension getting current open apps I want to launch apps with my extension, but I need to check if it's already open, so I don't reopen it or open a new app window.
Is there anyway I can do it?
Thanks.

A: Use chrome.windows.getAll to list all windows of app type and chrome.management.launchApp to launch an app if its window wasn't found.
Required permissions in manifest.json: "tabs", "management".
function launchApp(id, callback) {
    chrome.windows.getAll({
        windowTypes: ['app'],
        populate: true
    }, function(windows) {
        if (windows.some(function(w) { return w.tabs[0].url.indexOf(id) > 0 })) {
            if (callback) {
                callback({state: 'already running'});
            }
            return;
        }
        chrome.management.launchApp(id, function() {
            if (callback) {
                callback({state: 'launched'});
            }
        });
    });
}

Usage:
var appID = 'lkbbjdgfngikaledbinmnhkappgpnklb';
launchApp(appID, function(state) {
    console.log(state);
});


text:
Q: GHCI unable to recognize packages installed with Cabal on windows 10 I am a beginner with Haskell and for an assignment I needed to install System.Random. So I installed the package using Cabal through command line (originally with cabal install random and then with cabal install --lib random), however, when I run GHCI it doesn't recognize that the package is installed. When I run it I get this error:
Could not find module `System.Random'
    Use -v to see a list of the files searched for.
  |
3 | import System.Random
  | ^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.

I tried a few things to fix this, however, none of them seem to work. I tried to copy the files from the cabal directory where the package is saved and place them in the same folder as my project but I received this error.
     File name does not match module name:
    Saw: `Main'
    Expected: `Random'
  |
1 | #if __GLASGOW_HASKELL__ >= 701
  | ^
Failed, no modules loaded.

I then attempted to run ghc with "ghc -iC:\DirectoryToPackage AssignmentThatCallsPackage.hs" and this gave the same error as above. I also attempted this solution given here ghc can't find my cabal installed packages the second answer to make the package global but when I tried to run the line "runhaskell Setup install" it gave me an access denied error. I feel I have tried other solutions, but I can't remember what else I tried at the moment. I have been stuck on this for a while now so any help would be appreciated. Thank you in advance.


text:
Q: Event USB detection with udevadm monitor My purpose is to detect the event generated after the detection/remove of a USB.( OS:Linux and language C/C++).
for that , I used the package Udevadm to get this event, and I get the output below:
UDEV  [9494.049740] add      /devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host10/target10:0:0/10:0:0:0/block/sdb (block)
ACTION=add
DEVLINKS=/dev/disk/by-id/usb-WIKO_Mass_Storage_0123456789ABCDEF-0:0 /dev/disk/by-path/pci-0000:02:03.0-usb-0:1:1.0-scsi-0:0:0:0
DEVNAME=/dev/sdb
DEVPATH=/devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host10/target10:0:0/10:0:0:0/block/sdb
DEVTYPE=disk
ID_BUS=usb
ID_INSTANCE=0:0
ID_MODEL=Mass_Storage
ID_MODEL_ENC=Mass\x20Storage\x20\x20\x20\x20
ID_MODEL_ID=0001
ID_PATH=pci-0000:02:03.0-usb-0:1:1.0-scsi-0:0:0:0
ID_PATH_TAG=pci-0000_02_03_0-usb-0_1_1_0-scsi-0_0_0_0
ID_REVISION=0000
ID_SERIAL=WIKO_Mass_Storage_0123456789ABCDEF-0:0
ID_SERIAL_SHORT=0123456789ABCDEF
ID_TYPE=disk
ID_USB_DRIVER=usb-storage
ID_USB_INTERFACES=:080650:
ID_USB_INTERFACE_NUM=00
ID_VENDOR=WIKO
ID_VENDOR_ENC=WIKO\x20\x20\x20\x20
ID_VENDOR_ID=0bb4
MAJOR=8
MINOR=16
SEQNUM=2394
SUBSYSTEM=block
UDEV_LOG=3
UDISKS_PRESENTATION_NOPOLICY=0
USEC_INITIALIZED=9493993109

Is there a way to get the type of "the event", the "Action", and the "DEVNAME", without parsing all the output in variable String and after that collect the important information?


text:
Q: Entry point for test suite with multiple files in Cabal project? New to Cabal, so sorry if this is obvious, but I obviously want to have more than one file in my Cabal project's test suite, yet the .cabal file is insisting on being given an entrypoint. What do I put for this?
For example, if I have two modules in my library and want to test each in their own test file. One is no more important than the other, so how do I go about making one of the files an entrypoint?

A: You could make two test suites.
test-suite A
    main-is: test-module-A.hs

test-suite B
    main-is: test-module-B.hs

Or you could make a single suite that imports both test modules.
test-suite both
    main-is: test-both.hs
    other-modules: TestA, TestB


text: Q: отображение модуля "Новинки" в меню и на главной одновременно Доброе утро всем. как сделать чтобы модуль "Новинки" был ссылкой в меню? чтобы одновременно отображались первые 8 товаров на главной(limit 8), но так же в меню был раздел и при переходе отображало все товары из новинок с убранным лимитом. подскажите,как реализовать,спасибо!


text:
Q: Android Studio | How to use On Click to switch between a fragment and activity I am trying to use a button to switch between the fragment I am working on to a new activity. I am using the On Click listener to try switch. As well as using start activity. I think I may have to use fragment manager but I am unsure of how to use this.
This is the code I have.
addPlayers.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(TeamManagementFragment.this,AddPlayer.class));
    }
});

The error message I have is "Cannot resolve constructor"
Your help would be greatly appreciated :).
Many thanks,
Edward.

A: I suppose that AddPlayer is an Activity.
So you can use getActivity() instead of TeamManagementFragment.this

A: Assuming AddPlayer is your other activity you want to start, use the context from the View v argument as your first argument to the new Intent creation instead of using the current TeamManagementFragment instance since they are not a valid context.
addPlayers.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(v.getContext(), AddPlayer.class));
    }
});

See the docs page for Context to see which classes inherit from it :
https://developer.android.com/reference/android/content/Context.html

A: well I guess you didn't get the concept of activities and fragments. a fragment is basically a view which is hosted by an activity, and it's alive as long as the container activity lives. you can not use an intent to switch between these two.

A: Try this as you are currently in fragment:
addPlayers.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
    getActivity().startActivity(new Intent(getActivity(),AddPlayer.class));
    }
});


text:
Q: How to Perform MalformedURLException / 404 Not Found How do I make my program return MalformedUrlException and not just a generic Exception?
I am making a simple function that reads a URL a user enters in the console and it returns the content from the URL. I need it to check if the URL is a valid URL or if it's not a working URL.
Example urls:
http://google.com/not-found.html
http:/google.com
I created two catch exceptions but it seems like the overall exception is always returned instead of MalformedUrlException.
    public static String getUrlContents(String theUrl) {
    String content = "";
    try {
        URL url = new URL(theUrl);
        //Create a url connection object
        URLConnection urlConnection = url.openConnection();
        //wrap the url connection a buffered reader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while((line = bufferedReader.readLine()) != null) {
            content += line + "\n";
        }
        bufferedReader.close();
    } catch (MalformedURLException e) {
        System.out.println("The following url is invalid'" + theUrl + "'");
        //logging error should go here
    } catch (Exception e) {
        System.out.println("Something went wrong, try agian");
    }
    return content;
}

A: First, java.net.MalformedURLException is not the case for a "not found" resource:

public class MalformedURLException extends IOException
Thrown to indicate that a malformed URL has occurred. Either no legal
  protocol could be found in a specification string or the string could
  not be parsed.

I understand that you want to catch a situation when the URL results in a not found return code (404). To do this you need to examine the HTTP response code.
The easiest way is to use java.net.HttpURLConnection:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/HttpURLConnection.html

public abstract class HttpURLConnection extends URLConnection
A URLConnection with support for HTTP-specific features. See the spec
  for details.
Each HttpURLConnection instance is used to make a single request but
  the underlying network connection to the HTTP server may be
  transparently shared by other instances. Calling the close() methods
  on the InputStream or OutputStream of an HttpURLConnection after a
  request may free network resources associated with this instance but
  has no effect on any shared persistent connection. Calling the
  disconnect() method may close the underlying socket if a persistent
  connection is otherwise idle at that time.

You can check the response code by calling getResponseCode(). If the result is less than 400, you got a valid response, otherwise there was a client error (4xx) or a server error (5xx).
Something like this:
public static String getUrlContents(String theUrl) {
    String content = "";
    try {
        URL url = new URL(theUrl);
        //Create a url connection object
        URLConnection urlConnection = url.openConnection();
        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) urlConnection;
            if (conn.getResponseCode() < 400) {
                // read contents
            } else {
                System.out.println(conn.getResponseMessage());
                // treat the error as you like
            }
        } else {
            // not a HTTP connection, treat as you like
        }
    } catch (MalformedURLException e) {
        System.out.println("The following url is invalid'" + theUrl + "'");
        //logging error should go here
    } catch (Exception e) {
        System.out.println("Something went wrong, try agian");
    }
    return content;
}

I have not checked the code, but I think you can get the overall idea.


text:
Q: event defaults to flash.events and not external libaray in flash SO i am trying to access the TOUCH_DOWN and TOUCH_UP constants of the tuio library through the TouchEvent method however flash keeps defaulting the TouchEvent method to the flash.events TouchEvent and i can't figure out why. has anyone else had this problem maybe with another external library?

A: Did you mean "defaulting" at compile time, or defaulting at runtime?
Try using the fully qualified name of the TouchEvent class, like so: org.tuio.TouchEvent.TOUCH_DOWN, or explicitly use import org.tuio.TouchEvent;.
Also, the tuio event will only be dispatched by an org.tuio.TouchContainer.
And this I can only guess, since I don't know the source code, but if the constants use the same String value (i.e. "touchDown") as flash.events.TouchEvent, listener methods for both events will be triggered at runtime.  So you can always only listen to one event with the same String value at a time.


text:
Q: .NET TrackBar MouseDown follow cursor? I currently use this code to fix the bug where if you click somewhere on the Horizontal TrackBar it jumps to the middle then to the end of the TrackBar. So this code fixes that bug, which now jumps to the location you click.
But still a problem remains when I keep my mouse down and move it around the TrackBar the slider should follow but it just resets to beginning position, how do I make it follow right on top of cursor? would I need a timer control for that?
Private Sub tbTest_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tbTest.MouseDown
    Dim dblValue As Double

    'Jump to the clicked location, bug FIX.
    dblValue = (Convert.ToDouble(e.X) / Convert.ToDouble(tbTest.Width)) * (tbTest.Maximum - tbTest.Minimum)
    tbTest.Value = Convert.ToInt32(dblValue)
End Sub

A: Make the method handle both the MouseDown() and MouseMove() events like this:
Private Sub tbTest_MovePointer(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tbTest.MouseDown, tbTest.MouseMove
    If e.Button = Windows.Forms.MouseButtons.Left Then
        Dim dblValue As Double

        'Jump to the clicked location, bug FIX.
        dblValue = (Convert.ToDouble(e.X) / Convert.ToDouble(tbTest.Width)) * (tbTest.Maximum - tbTest.Minimum)
        tbTest.Value = Convert.ToInt32(dblValue)
    End If
End Sub

*Note the multiple events listed after the Handles keyword at the end of the first line.  I also added a check to ensure the left mouse button is down.


text:
Q: How can I get Google Chrome to show my home page whenever a new tab is opened? Using the latest Chrome stable version, is there a way either, by editing some config file or via an extension, that will allow me to specify that my home page be opened each time I click the NEW TAB button?
I'd prefer my homepage open rather than the Speed Dial interface - it's a local html file.

A: New Tab Redirect is an extension that does exactly what you want.


text:
Q: Django model property does not working - Django class Country(models.Model):
    status        = models.BooleanField()
    country_name  = models.CharField(max_length=100, null=True, blank=True)
    country_flag  = models.CharField(max_length=10, null=True, blank=True)

class Offers(models.Model):
    @property
    def flag_from(self):
        return self.country.country_flag

    status  = models.BooleanField()
    country = models.ForeignKey('Country',  db_index=True, on_delete=models.PROTECT)
    .....other_normal_fields

So when i'm trying to get one row, and print my custom field Doesn't shows only when print it directly:
line=Offers.objects.get(pk=1)
print(line)
### here shows only normal fields
print(line.flag_form)
### now ok

also when i convert line to dict custom field dissappear, but i need it there
How it can be fixed?

A: Given a comment of yours perhaps this answers your question.
def getOfferDictionary(pk):
    line = Offers.objects.get(pk=pk)
    lineDict = {
        'status': line.status,
        'country': line.country.country_name,
        'flag_from': line.flag_from,
        # other properties you need
    }
    return lineDict

Keep in mind however this really isn't a good way of doing this, I recommend formatting the data locally to suit the views need instead of creating such a small reformatting, for which personally I cannot see a use

A: flag_from is a property of the Offers model, and not a field stored in the database. So, when you call print(line), Django is simply displaying the fields that are stored in the database for the Offers model.
You can add it to the dictionary using the property name as the key so:

line = Offers.objects.get(pk=1)
some_dict = {
    'status': line.status,
    'country': line.country.country_name,
    'flag_from': line.flag_from,
}
print(some_dict)

Note: Django by default add s as the suffix to the model so it is better to name it is as Offer instead of Offers.


text:
Q: mongo local server uninstallition I'm try to uninstall mongod but it's give
message of file / package missing
during installation it's show message
of no newly file install ...............
dz-gg-04@dz-gg-04:~$ sudo apt-get install -y mongodb
Reading package lists... Done
Building dependency tree
Reading state information... Done
mongodb is already the newest version (1:3.6.3-0ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 26 not upgraded.
dz-gg-04@dz-gg-04:~$ mongod
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] MongoDB starting : pid=4627 port=27017 dbpath=/data/db 64-bit host=dz-gg-04
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] db version v3.6.3
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] git version: 9586e557d54ef70f9ca4b43c26892cd55257e1a5
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.1.0g  2 Nov 2017
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] modules: none
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] build environment:
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten]     distarch: x86_64
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2018-10-19T15:25:00.599+0530 I CONTROL  [initandlisten] options: {}
2018-10-19T15:25:00.600+0530 I STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
2018-10-19T15:25:00.600+0530 I CONTROL  [initandlisten] now exiting
2018-10-19T15:25:00.600+0530 I CONTROL  [initandlisten] shutting down with code:100
dz-gg-04@dz-gg-04:~$ mongo
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
2018-10-19T15:26:04.016+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2018-10-19T15:26:04.016+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:251:13
@(connect):1:6
exception: connect failed
dz-gg-04@dz-gg-04:~$ sudo service mongod start
Failed to start mongod.service: Unit mongod.service not found.
dz-gg-04@dz-gg-04:~$ ^C
dz-gg-04@dz-gg-04:~$ ^C
dz-gg-04@dz-gg-04:~$ ^C
dz-gg-04@dz-gg-04:~$ ^C
dz-gg-04@dz-gg-04:~$ ^C
dz-gg-04@dz-gg-04:~$ sudo service mongod start

A: exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating

Create the directory /data/db


text:
Q: C++ does not compile by uncommenting move operator I have the following code:
template <typename T>
struct X {
    X() : x(5) {}

    template <template <typename> class S>
    X(const S<T> & y) : x(y.x) {}

    // Uncomment and it does not compile anymore
    // X(X&& z) : x(z.x) {}

    T x;
};

int main ()
{
    X<int> y;
    auto x = y;
    return 0;
}

Could you explain why it does not compile once the specified code is uncommented?

A: Copy constructor is implicitly declared as deleted because you declared a move constructor.
Add a default (or user defined) copy constructor and it would compile fine:
X(const X<T>&)=default;

A: Humam Helfawi got the point.
I try to complete his answer.
Svalorzen: look at this code
#include <iostream>

template <typename T>
struct X {
    X() : x(5) {}

    template <template <typename> class S>
    X (const S<T> & y) : x(y.x)
     { std::cout << "templated constructor" << std::endl; }

    X (const X<T> & y) : x(y.x)
     { std::cout << "copy constructor" << std::endl; }

    T x;
};

int main ()
{
    X<int> y;
    auto x = y;
    return 0;
}

The output is "copy constructor".
When the compiler find a matching templated function and a matching plain (no templated) function, choose the plain as more specific.
Now delete the definition of the copy contructor
#include <iostream>

template <typename T>
struct X {
    X() : x(5) {}

    template <template <typename> class S>
    X (const S<T> & y) : x(y.x)
     { std::cout << "templated constructor" << std::endl; }

    T x;
};

int main ()
{
    X<int> y;
    auto x = y;
    return 0;
}

and you get your example without the move constructor and with the cout ("templated constructor") added.
You can see that the output is empty.
That's because the compiler choose the copy contructor that, as default version, is implicitly present.
When you add the move constructor, you incidentally mark as deleted the copy constructor. But the copy constructor is ever present (even as marked as deleted) and the compiler consider it. So, when the compiler try to implement "x = y", match your your templated constructor, match the copy constructor, choose the copy constructor (more specific), see that is deleted and give error.
When you add
X (const X<T> &) = default;

you permit the compiler to use the copy constructor.
p.s.: sorry for my bad English.