Q: What's the point of adding extra GB of drive space to the Ubuntu partition beyond what the OS needs? I'm installing alongside windows.  My HD has ~1 TB of space.  I'm assuming when installing, if I ask the installer to partition 400 GB of space for Ubuntu, this would leave ~600 GB of space for Windows.
But how is this 400 GB used?  Will it be used for me to save any random files I end up saving? (e.g. music, photos, apps, etc.?)
Or will it be used for some weird tech reason that I, as a casual user, am not aware of or concerned with?

A:
But how is this 400 GB used?

That is up to you.
Theoretically you could create a 250 Gb swap file and reserve 10 Gb for the OS files and 140 for /home/. Not that I would advice it but it is possible.
For the basic system (ie. Ubuntu itself with kernel etc etc) 10 Gb is more than enough (ie create a 10Gb partition and call it / during installation).. Your personal documents can be stored on a separate partition on those 400 Gb (ie create a 380Gb partition and call it /home during installation). The remainder can be used for swap.

A: In the default configuration that partition will contain the OS and your home directory including all your personal data, documents and media (if you decide to save them there).
More experienced users often have a separate partition for their home directory, which can be much larger than the one for the root directory.


Q: How can I implement session expiry based on users inactivity in django framework? I am using django request.session.set_expiry() to expire session for a logged in user. But it expires session even though user is active.
    if user is not None:
      login(request, user)
      request.session.set_expiry(60)


Q: Post API using Ratpack and Groovy giving 405 Error and RxJava methods not working I am building an API using Ratpack and Groovy. The POST API is always giving:

405-Method not Found Error

This is a snippet from POST Endpoint Handler. In this code, promiseSingle, then, observe, map, doOnNext, doOnError, etc.
RxJAVA functions are not working. Is there any reason why RxJava methods are not working?
saveJsonAsData(context, id)
            .promiseSingle()
            .then { Data updateddata ->
                context.response.headers
                    .add(HttpHeaderNames.LOCATION, "/api/save/${updateddata.id}/${updateddata.value}")
                context.response.status(HttpResponseStatus.CREATED.code())
                    .send()
            }
    }

    protected Observable<Data> saveJsonAsData(GroovyContext context, String id) {
        context.request.body.observe()
            .map { TypedData typedData -> extractData(context, typedData) }
            .doOnNext { Data data ->
                data.id = id
                validatorWrapper.validate(data)
            }
            .flatMap(data.&save as Func1)
            .doOnError { Throwable throwable -> log.error("Error saving data", throwable) }
    }

A: The issue is not so much with Rx as it is with the usage of the Context.
You should try to keep the response handling logic within your Handler, that is don't pass the Context around, rather get the objects you need and pass them to your services.
As an example
path('myendpoint') { MyRxService service ->
  byMethod {
    get {
      // do something when request is GET
    }
    post {
      request.body.map { typedData ->
        extractItem(typeData) // extract your item from the request first
      }.flatMap { item ->
          service.saveJsonAsItemLocation(item).promiseSingle() // then once it's extracted pass the item to your "saveJsonAsItemLocation" method
      }.then { ItemLocationStore updatedItem ->
          response.headers.add(HttpHeaderNames.LOCATION, "/itemloc/v1/save/${updatedItem.tcin}/${updatedItem.store}")
          context.response.status(HttpResponseStatus.CREATED.code()).send()
      }
    }
  }
}

My guess is that you have something like this:
get {
 // get stuff
}

post {
  // post stuff
}

The reason this doesn't work is that Ratpack doesn't use Routing Table for handling incoming requests, instead it uses chain delegation. The get {} binds to root path and GET http method and post {} binds to root path and POST http method. Because get {} matches the path, Ratpack considers the handler matched and since the handler is for GET it considers it a 405.
There are chain methods available that binds regardless of HTTP Method such as all {} and path {}. Chain#all will handle all paths and methods where as Chain#path(String) matches against specific path.
Hope this helps.


Q: Seeding random number generators in parallel programs I am studing the multiprocessing module of Python.
I have two cases:
Ex. 1
def Foo(nbr_iter):
    for step in xrange(int(nbr_iter)) :
        print random.uniform(0,1)
...

from multiprocessing import Pool

if __name__ == "__main__":
    ...
    pool = Pool(processes=nmr_parallel_block)
    pool.map(Foo, nbr_trial_per_process)

Ex 2. (using numpy)
 def Foo_np(nbr_iter):
     np.random.seed()
     print np.random.uniform(0,1,nbr_iter)

In both cases the random number generators are seeded in their forked processes.
Why do I have to do the seeding explicitly in the numpy example, but not in the Python example?

A: numpy 1.17 just introduced [quoting] "..three strategies implemented that can be used to produce repeatable pseudo-random numbers across multiple processes (local or distributed).."
the 1st strategy is using a SeedSequence object. There are many parent / child options there, but for our case, if you want the same generated random numbers, but different at each run:
(python3, printing 3 random numbers from 4 processes)
from numpy.random import SeedSequence, default_rng
from multiprocessing import Pool

def rng_mp(rng):
    return [ rng.random() for i in range(3) ]

seed_sequence = SeedSequence()
n_proc = 4
pool = Pool(processes=n_proc)
pool.map(rng_mp, [ default_rng(seed_sequence) for i in range(n_proc) ])

# 2 different runs
[[0.2825724770857644, 0.6465318335272593, 0.4620869345284885],
 [0.2825724770857644, 0.6465318335272593, 0.4620869345284885],
 [0.2825724770857644, 0.6465318335272593, 0.4620869345284885],
 [0.2825724770857644, 0.6465318335272593, 0.4620869345284885]]

[[0.04503760429109904, 0.2137916986051025, 0.8947678672387492],
 [0.04503760429109904, 0.2137916986051025, 0.8947678672387492],
 [0.04503760429109904, 0.2137916986051025, 0.8947678672387492],
 [0.04503760429109904, 0.2137916986051025, 0.8947678672387492]]

If you want the same result for reproducing purposes, you can simply reseed numpy with the same seed (17):
import numpy as np
from multiprocessing import Pool

def rng_mp(seed):
    np.random.seed(seed)
    return [ np.random.rand() for i in range(3) ]

n_proc = 4
pool = Pool(processes=n_proc)
pool.map(rng_mp, [17] * n_proc)

# same results each run:
[[0.2946650026871097, 0.5305867556052941, 0.19152078694749486],
 [0.2946650026871097, 0.5305867556052941, 0.19152078694749486],
 [0.2946650026871097, 0.5305867556052941, 0.19152078694749486],
 [0.2946650026871097, 0.5305867556052941, 0.19152078694749486]]

A: If no seed is provided explicitly, numpy.random will seed itself using an OS-dependent source of randomness. Usually it will use /dev/urandom on Unix-based systems (or some Windows equivalent), but if this is not available for some reason then it will seed itself from the wall clock. Since self-seeding occurs at the time when a new subprocess forks, it is possible for multiple subprocesses to inherit the same seed if they forked at the same time, leading to identical random variates being produced by different subprocesses.
Often this correlates with the number of concurrent threads you are running. For example:
import numpy as np
import random
from multiprocessing import Pool

def Foo_np(seed=None):
    # np.random.seed(seed)
    return np.random.uniform(0, 1, 5)

pool = Pool(processes=8)
print np.array(pool.map(Foo_np, xrange(20)))

# [[ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.64672339  0.99851749  0.8873984   0.42734339  0.67158796]
#  [ 0.64672339  0.99851749  0.8873984   0.42734339  0.67158796]
#  [ 0.64672339  0.99851749  0.8873984   0.42734339  0.67158796]
#  [ 0.64672339  0.99851749  0.8873984   0.42734339  0.67158796]
#  [ 0.64672339  0.99851749  0.8873984   0.42734339  0.67158796]
#  [ 0.11283279  0.28180632  0.28365286  0.51190168  0.62864241]
#  [ 0.11283279  0.28180632  0.28365286  0.51190168  0.62864241]
#  [ 0.28917586  0.40997875  0.06308188  0.71512199  0.47386047]
#  [ 0.11283279  0.28180632  0.28365286  0.51190168  0.62864241]
#  [ 0.64672339  0.99851749  0.8873984   0.42734339  0.67158796]
#  [ 0.11283279  0.28180632  0.28365286  0.51190168  0.62864241]
#  [ 0.14463001  0.80273208  0.5559258   0.55629762  0.78814652] <-
#  [ 0.11283279  0.28180632  0.28365286  0.51190168  0.62864241]]

You can see that groups of up to 8 threads simultaneously forked with the same seed, giving me identical random sequences (I've marked the first group with arrows).
Calling np.random.seed() within a subprocess forces the thread-local RNG instance to seed itself again from /dev/urandom or the wall clock, which will (probably) prevent you from seeing identical output from multiple subprocesses. Best practice is to explicitly pass a different seed (or numpy.random.RandomState instance) to each subprocess, e.g.:
def Foo_np(seed=None):
    local_state = np.random.RandomState(seed)
    print local_state.uniform(0, 1, 5)

pool.map(Foo_np, range(20))

I'm not entirely sure what underlies the differences between random and numpy.random in this respect (perhaps it has slightly different rules for selecting a source of randomness to self-seed with compared to numpy.random?). I would still recommend explicitly passing a seed or a random.Random instance to each subprocess to be on the safe side. You could also use the .jumpahead() method of random.Random which is designed for shuffling the states of Random instances in multithreaded programs.

A: Here is a nice blog post that will explains the way numpy.random works.
If you use np.random.rand() it will takes the seed created when you imported the np.random module. So you need to create a new seed at each thread manually (cf examples in the blog post for example).
The python random module does not have this issue and automatically generates different seed for each thread.


Q: IE not clearing subsequent floats I'm trying to get two divs to float to opposite sides of the page, with text flowing between them.  The top of the second (left-aligned) div should be even with the bottom of the first (right-aligned) div.  The code below works fine in FF, Chrome, Opera, etc. fine, but they do not clear properly in IE.  Both divs appear at the top of the text.
If I move the left-aligned div low enough within the text, it works fine in IE, but that's not really a sustainable solution.
I've found multiple pages on IE CSS float bugs, but I haven't found anything speaking directly to this.
CSS
div {
    width: 200px;
    margin-top: 10px;
    border-style: solid;
    border-width: 1px;
    position: relative;
}
.wrapper {
    width: 600px;
    border-color: #FF0000;
}
.right {
    float: right;
    border-color: #00FF00;
}
.left {
    float: left;
    clear: both;
    border-color: #0000FF;
}

HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<link rel="stylesheet" href="float.css" />

        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Nulla pretium tempor leo. Vivamus mi risus, dapibus ac,
        consectetur quis, pellentesque eget, sem.

            Proin malesuada. Ut vel lorem. Cras rhoncus nisl accumsan
            turpis tristique consequat. Sed lacinia ligula at nibh.
            Morbi in quam. Morbi commodo nibh.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nulla pretium tempor leo. Vivamus mi risus,
    dapibus ac, consectetur quis, pellentesque eget, sem.
    Maecenas est dui, imperdiet nec, fermentum ut,
    pretium a, orci. Quisque hendrerit interdum orci.
    Nulla sit amet risus non enim ultrices bibendum.
    Aenean arcu purus, rhoncus at, vestibulum vel,
    volutpat et, nunc. Integer eget risus eget purus viverra
    congue.

Nullam vel libero ut purus semper ullamcorper.
    Pellentesque mattis tincidunt odio. Nullam pulvinar
    orci at dolor. Sed volutpat eros ac elit.
    Praesent porttitor libero sed felis. Vivamus lobortis
    pellentesque diam.
    Proin laoreet massa ac metus. Integer faucibus lorem
    molestie nibh. Integer id massa. Integer ligula ipsum,
    pellentesque id, interdum at, pretium eget, orci.
    Proin malesuada. Ut vel lorem.

A: IE7 and IE6 have a variety of problems with elements that have both float and clear on them. In IE7, using clear on an element with float only clears the float below other floats floated in the same direction.
A modified version of the easyclearing fix may do the trick, but don't get your hopes up. See this page for details: New clearing method needed for IE7?.
Bottom line is that you're probably not going to get this to work in IE6/7 without cheating: moving the div down in the text, embedding the divs in paragraphs, etc.

A: I'm fairly sure this is one of those rare bugs in ie6 that doesn't have a pure CSS solution.
Try using the ie7 javascript - it may fix the problem for you: http://code.google.com/p/ie7-js/


Q: What is causing my site to load and add "#" at the end? I think there might be something in my .htaccess file that is causing my page to load and then "bounce" back to the top adding # at the end of my domain, like this: example.com/#
Here is my htaccess file:
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Start Category Redirects

Redirect permanent /check-out-this-page-tration http://example.com/this-page/

Redirect permanent /rewards http://example.com/example-reward-coupons-page/

Redirect permanent /p-photo-entries http://example.com/2012-contest-photos/

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>

# BEGIN WordPress
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]

# END WordPress

Any ideas on what I should remove or change?

A: URL fragments are used by the client (a web browser) to help determine how to handle the content that it's trying to display.
This can be anchors to jump to a certain part of a page, or used by javascript to send information between other scripts. This is not your htaccess file as fragments are never sent to the server (where your htaccess file lives).
Try selectively removing javascript (especially scripts that you load from 3rd party sites that share links like "Add To Any"), otherwise make sure you have no links in your content that look like this:
some/path/file.html#


Q: Não deixar usuário fechar aplicação / ou realizar uma ação antes de fechar Pessoal na minha aplicação o usuário faz um pedido, esse pedido ganha um Status de novo, quero que quando ele feche a aplicação em quanto está realizando o pedido, o status seja alterado para cancelado e seja enviado para o servidor.
Tentei implementar isso no onDestroy mas não funcionou.
Quando falo fechar a aplicação é quando ele exibe todas aplicações abertas e arrasta pro lado a aplicação, aí ele acaba fechando.
Ou se possível até não deixar ele encerrar a aplicação.


Q: What is the origin of the use of the letter/symbol $c$ for the speed of light? A cow-orker recently "informed" me that the reason we call the speed of light $c$ is that c stands for "causality.
I would guess that can't be the case, because I think the symbol $c$ was used to represent the speed of light as early as the days of Faraday and certainly in Maxwell's papers, while the idea that light propagation and causality are related came into being decades later, with relativity.
But I'm not absolutely certain that Maxwell used the symbol $c$.
At any rate, does anyone know when using the symbol $c$ to represent the speed of light came into common practice?

A: The origin can be traced back to the experiments (and subsequent papers) by Weber and Kohlrausch (1856). The paper can be found here
Although Weber constant had a magnitude around $\sqrt2c$, the same can be taken to be one of the first time the constant be denoted as 'c'.
Later (1894) Paul Drude modified the Weber's constant in such a way we use today.
Later  Planck, Lorentz, Einstein etc contributed to the popularity of this notation.
To dig on the exact 'meaning', I found this:

Weber apparently meant c to stand for "constant" in his force law, but there is evidence that physicists such as Lorentz and Einstein were accustomed to a common convention that c could be used as a variable for velocity.  This usage can be traced back to the classic Latin texts in which c stood for "celeritas" meaning "speed".  The uncommon English word "celerity" is still used when referring to the speed of wave propagation in fluids.  The same Latin root is found in more familiar words such as acceleration and even celebrity, a word used when fame comes quickly.

Source : http://math.ucr.edu/home/baez/physics/Relativity/SpeedOfLight/c.html
so ... 'celeritas'


Q: Routers in versions 3.4.X Since I upgraded from version 3.3.3 to version 3.4 I'm have problems with routers:
File "/urls.py", line 23, in

urlpatterns = router.urls

File "~/Library/Python/2.7/lib/python/site-packages/rest_framework/routers.py", line 81, in urls
self._urls = self.get_urls()

File "~/Library/Python/2.7/lib/python/site-packages/rest_framework/routers.py", line 358, in get_urls
view = self.get_api_root_view(api_urls=urls)

TypeError: get_api_root_view() got an unexpected keyword argument 'api_urls'

A: You likely have overridden get_api_root_view without providing the api_url argument since it's already part of DRF: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/routers.py#L292

A: I had the same error.  I found I had an older version of drf-extensions.  I have a feeling drf-extensions overrides the get_api_root_view method, and when it's not in sync with your version of Django Rest Framework, this can cause a problem (ie. drf-extensions is passing a parameter that DRF no longer expects, but in previous versions was acceptable).
If it's not drf-extensions specifically, it's probably something else that's overriding get_api_root_view as Linovia suggested.


Q: multi language site and search engines I'm developing a site for a company that has clients from all over the world and the site will be served in two languages: Italian (local) and English.
Once a visitor visits the site I check the IP, if  its coming from Italy I show the site in Italian , if it's not I show it in English. Of course they will have the option to manually override the language.
What exactly happens when the search engine bots inspect the site to index the pages?

*

*usually the crawlers always have USA based IPs

*even if the crawlers "click" on the "change language" link to show Italian pages since they can't accept cookies (and so sessions) I can't keep the language set or keep trace of what has been chosen

So the question is , how can you handle this situation in a way that search engines scan both the languages and also index them?

A: Google actually has an article in their Webmaster guidelines on this subject.  You may want to take a look, as they specifically address the issues you have raised: http://www.google.com/support/webmasters/bin/answer.py?answer=182192

A: I'd use subdomains:
eng.mysite.com/whatever
it.mysite.com/whatever

Then have a sitemap which points to the home page of each of those language subdomains, and they should all be crawled just fine.

A: You can use the following approach:

*

*Scan the Accept-Language header ($_SERVER['HTTP_ACCEPT_LANGUAGE']) for languages that the user agent prefers.  This is usually more reliable than checking the IP address for their country.

*Check the User-Agent header ($_SERVER['HTTP_USER_AGENT']) to see if the request comes from a search engine, such as "Googlebot" and "Yahoo! Slurp".


Q: How do I fix this Python ModuleNotFoundError I am trying to figure out what is causing this file called builder.py to not run on mac even though it runs on windows. Code:
import cffi
import glob
import platform

# relative to build dir
LIB_BASE = '../libs/'
# compiling libraries statically to get a single binary
EXTRA_SRC = [LIB_BASE + 'subhook/subhook.c']

pltsysname = {'Windows': 'win32', 'Darwin': 'osx', 'Linux': 'elf'}
pltsrc = pltsysname[platform.system()]
pltsrc = LIB_BASE + 'plthook/plthook_{}.c'.format(pltsrc)
# EXTRA_SRC.append(pltsrc)  # disabled until it is actually useful

LIBDIRS = []
if platform.system() == 'Windows':
LIBDIRS.append('../libs/SDL/lib/x86/')

CDEFS = 'generated internals SDL XDL subhook xternPython'.split()

def readfile(name):
with open(name, 'r') as f:
    content = f.read()
return content

def build():
ffibuilder = cffi.FFI()

for fname in CDEFS:
    ffibuilder.cdef(readfile('cdefs/{}.h'.format(fname)))

ffibuilder.embedding_api('uint32_t kickstart();')
ffibuilder.embedding_init_code(readfile('remote.py'))

ffibuilder.set_source(
    '_remote', readfile('cdefs/remote.c'), sources=EXTRA_SRC,
    libraries=['SDL2'], library_dirs=LIBDIRS,
    define_macros=[('SUBHOOK_STATIC', None)])

ffibuilder.compile(tmpdir='build', target='remote.bin')

if __name__ == '__main__':
build()

When ever I run it I expect it to run but instead it comes up with the following error:
Traceback (most recent call last):
File "/Users/alexanderlee/Desktop/sbpe-1.6.1/builder.py", line 1, in <module>
import cffi
ModuleNotFoundError: No module named 'cffi'
>>>

How do I fix it?

A: It's probably because you only installed cffi on your Windows, so you probably need to install it on your Mac also.
You can follow rules on the docs:

pip install cffi

A: cffi is a third-party module.  It's installed on your Windows computer but not on your Mac.


Q: Mysql C++ Driver - Get prepared statement query after created I use prepared statements quite heavily in my c++ application.  The problem that I'm having is that when a mysql query throws an error (i.e. foreign key constraint),
I would like to somehow be able to get that query so I can debug.
Here is a small code example from MysqlWrapper.cpp
(A class that I have written that wraps the C++ Driver)
    long MysqlWrapper::Insert(sql::PreparedStatement *stmt)
    {
        try
        {
            stmt->execute();
            ...
            //return inserted id
        }
        catch(sql::SQLException &ex)
        {
            // How can I get the query being executed by stmt?
        }
    }

A: Prepared statements are not worth the problems at MySQL, they are not much faster than classic SQL statements. They are not compiled as in other RDBMS.
I think in this case it would be better to use a batch insert instead of a prepared statement.


Q: Get objects outside an array of objects I have a bit of a complex mix of objects and arrays and I was looking for way to flatten the arrays so it's less complex when I try to render it.
Basically I have some input fields and there's an option to add custom fields with custom label and value, but the way it's stored in DB the label is customLabel and the value is the array of all the custom fields that were added
    const keyTerms = [
    {label: 'pre-set label', value: 'some value'},
    {label: 'pre-set label', value: 'some value'},
    {label: 'customLabel', value: [{}, {}]}
    ];

In my React component I'm mapping through that array to display the objects, but when I hit the object that has an array as a value, I get an error since the component is expecting an string instead of an array
    {keyTerms.map(keyTerm => <Component keyTerm={KeyTerm} />}

Inside the Component I tried to check if keyTerm.value is an array to map through it
Array.isArray(keyTerm.value)
? keyTerm.value.map(ele => (
   <>
     {keyTerm.label}
     <Description>{keyTerm.value}</Description>
   </>
))
: (
   <>
     {keyTerm.label}
     <Description>{keyTerm.value}</Description>
   </>
)

But that solution didn't work, it's passing the first check and always going to the else block then throwing this error:
Uncaught Error: Objects are not valid as a React child (found: object with keys {label, description, __typename}). If you meant to render a collection of children, use an array instead.

Is there a way to take the objects from inside the third object value array and put them in the outside array?

A: Try the code below: (however it may be worth it to create a reusable component out of the label/description fields so it’s not duplicated)
Array.isArray(keyTerm.value)
? keyTerm.value.map(ele => (
   <>
     {ele.label}
     <Description>{ele.value}</Description>
   </>
))
: (
   <>
     {keyTerm.label}
     <Description>{keyTerm.value}</Description>
   </>
)


Q: Homework Sales calculator Yesterday I submitted this problem, got terrific responses but my code still didn't work. I modified my code based on another student's code that works, but my code still won't calculate but it validates in javascript. Any suggestions. This homework is due TONIGHT!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4       /loose.dtd">

<title>Price Calculator</title>

Price Calculator

    <form name="form" id="form">

Price: <input type="text" id="cost" name="cost" value="" onchange=
       "fixOrder" />

Tax:   <input type="text" id="tax" name="tax" value="" onchange=
       "fixOrder" />

Total: <input type="text" id="total" name="total" value="" disabled=
       "disabled" />

    </form>

A: You need to change the onchange to
fixOrder()

A: JS Fiddle
Your onchange event is onchange="fixOrder" which is not really doing anything.  If you change it to fixOrder() you will call the function fixOrder when the change event is fired.

Furthermore:

*

*I don't think const is a reserved word in JavaScript.  I don't think JS has constants.  You should change that line from const TAX to var TAX;

*Unlike parseInt, which takes two arguments (string and base/radix), parseFloat only takes one argument (string), so you can remove the , 10 from it

I imagine you want something like:
function fixOrder() {
    var TAX = 0.0975;
    var numPrice;
    var total;
    var tax;

    numPrice = parseFloat(document.getElementById("cost").value);
    tax      = parseFloat(document.getElementById("tax").value);
    total    = parseFloat(document.getElementById("total").value);

    numPrice = numPrice + (tax || numPrice * TAX);
    total    = numPrice;
    var dec  = new Number((total+'').split('.')[1])  || 0;
    total    = document.getElementById("total").value =
                  "$" + Number(parseInt(total)
                      + '.'
                      + Math.round(
                          ( (dec+''.split('').reverse().join('') )/100 + '').split('').reverse().join('')
                        )).toFixed(2);
                        );

    if (isNaN(numPrice)) {
        alert("Sorry,you must enter a numeric value to place order");
        numPrice = 0;
    }
}

This will use the dollar amount of tax you enter, or if that doesn't exist, it will use the constant rate that you have supplied at the beginning (this was changed from .975 to .0975).
Also, notice the new calculation from total, we're taking the decimal part of the number, dividing it by 100 to get to two decimal places, reversing it back so it's in the proper order again, and then rounding it to the nearest 1 (cent).

HTML Body:

Price Calculator

  <form name="form" id="form">

Price: <input type="text" id="cost" name="cost" value="" onchange="fixOrder()" />

Tax:   <input type="text" id="tax" name="tax" value="" onchange="fixOrder()" />

Total: <input type="text" id="total" name="total" value="" disabled="disabled" />

  </form>

A: When calling a function in JavasScript by an event, you need to mention the () after the name of the function you want to call.


Q: Starting shell from android app to run separate executable I want to start shell from android application because i want to run an executable file and pass few arguments and expect output.
I tried ProcessBuilder and process and run at runtime listening to their io stream but android app does not allowing me to start shell is this permission issue??
I am getting all the time

runCommand error: Error running exec(). Command: [su] Working Directory: null Environment: null

Is there a way to run shell as an interface between running app as a process and process will be started from shell?
Shed some light on this issue thanks

A: Actually, when you use the "su" hack what you are getting is a shell that runs as root (if the device has been modified to support that)
If you don't want a root shell but an ordinary one running as your application's userid, you could presumably run /system/bin/sh or whatever it is on your device instead of su.


Q: Ugly looking java data structure I've created the following structure which maps unique double values to one or more pairs of integers:
   @SuppressWarnings("boxing")
   private static final HashMap<Double, Integer[][]> rules =
      new HashMap<Double, Integer[][]>() {
         private static final long serialVersionUID = 1L;
         {
            put(-0.6, new Integer[][] { { 1, 3 } });
            put(-0.3, new Integer[][] { { 2, 2 } });
            put(0.0, new Integer[][] { { 2, 4 }, { 3, 3 }, { 4, 2 } });
            put(0.3, new Integer[][] { { 4, 4 } });
            put(0.6, new Integer[][] { { 5, 3 } });
         }
   };

Can I rewrite this so it's simpler - i.e not have to deal with warnings (serialVersionUID, boxing), and it being so verbose?

A: Using a class for the pairs of integers should be the first. Or is this a coincidence, that all arrays containing a bunch of pairs?
The second thing is, that these initialization-data could be read from a configuration-file.
Edit: As I looked again on this code, I realized that Doubles as keys in a Map is somewhat risky. If you produce Doubles as a result of an mathematical operation, it is not clear, if they will be equal for the computer (even if they are equal in a mathematical sense). Floating-point-numbers are represented as approximation in computers. Most likely you want to associate the values with the interval (example 0.0-0.3) and not the value itself. You may avoid trouble, if you always use the same constants as keys in the array. But in this case you could use an enum as well, and no new programmer runs into trouble, if he uses his calculated doubles as keys in the map.

A: Create another class to hold your pairs of integers, and store them using a list:
Map<Double,List<MyPair>>

Are these to be arbitrary pairs of integers, or will the represent something? If the latter, then name appropriately. New classes are cheap in Java, and good naming will reduce maintenance costs.
Edit: why are you creating an anonymous subclass of HashMap?

A: using a static initializer would be slightly better in my opinion, although it does nothing about the verbosity:
private static final Map<Double, int[][]> rules;

static {
    rules = new HashMap<Double, int[][]>();

    rules.put(-0.6, new int[][] { { 1, 3 } });
    rules.put(-0.3, new int[][] { { 2, 2 } });
    rules.put(0.0, new int[][] { { 2, 4 }, { 3, 3 }, { 4, 2 } });
    rules.put(0.3, new int[][] { { 4, 4 } });
    rules.put(0.6, new int[][] { { 5, 3 } });

}

Another option using a special Pair class and Arrays.asList:
class Pair<A, B> {
  A a;
  B b;

  public Pair(A fst, B snd) {
  }

  // getters and setters here
}

private static final Map<Double, List<Pair<Integer, Integer>>> rules;

static {
    rules = new HashMap<Double, List<Pair<Integer, Integer>>>();

    rules.put(-0.6, Arrays.asList(new Pair(1, 3)));
    rules.put(-0.3, Arrays.asList(new Pair(2, 2)));
    rules.put(0.0, Arrays.asList(new Pair(2, 4), new Pair(3, 3), new Pair(4, 2));
    // etc
}

A: Can you wrap a class around Integer[][] called, say Point?
That would make you have a
HashMap<Double, List<Point>>

A: I would start with a MultiValueMap.  http://larvalabs.com/collections/.
This way you can do:
private static final MultiValueMap<Double, Integer[]> rules;
   static {
      MultiValueMap<Double, Integer[]> map = new MultiValueMap <Double, Integer[]>();

      map.put(-0.6, new Integer[] { 1, 3 });
      map.put(-0.3, new Integer[] { 2, 2 });
      map.put(0.0, new Integer[]  { 2, 4 }, new Integer[]{ 3, 3 }, new Integer[]{ 4, 2 } );
      map.put(0.3, new Integer[]  { 4, 4 } );
      map.put(0.6, new Integer[]  { 5, 3 } );
      rules = map;
   };

It looks also like you are aways using pairs of integers as the list of Keys.  It would probably clean your interface up if you refered to that as a RulePair or some other specified object.  Thus 'typing' your Integer array more specificially.

A: you could try also with a Builder; Java is not good as other languages for this kind of uses.. but here is FYI:
First shot
class RuleBuilder  {

    private Map<Double, Integer[][]> rules;

    public RuleBuilder() {
        rules = new HashMap<Double, Integer[][]>();
    }

    public RuleBuilder rule(double key, Integer[]... rows) {
        rules.put(key, rows);
        return this;
    }

    public Integer[] row(Integer... ints) {
        return ints;
    }

    public Map<Double, Integer[][]> build() {
        return rules;
    }
}

sample usage:
private static final Map<Double, Integer[][]> rules =
                new RuleBuilder() {{
                    rule(-0.6, row(1, 3));
                    rule(-0.3, row(2, 2));
                    rule(0.0, row(2, 4), row(3,3), row(4, 2));
                    rule(0.3, row(4, 4));
                    rule(0.6, row(5, 3));
                }}.build();

Second shot
In order to elimate the final "build()" call and double brace init you could try with:
class RuleBuilder2 extends HashMap<Double, Integer[][]>  {

    public RuleBuilder2 rule(double key, Integer[]... rows) {
       put(key, rows);
       return this;
    }

    public Integer[] row(Integer... ints) {
        return ints;
    }
}

in this case the code is a little better:
private static final Map<Double, Integer[][]> rules2 =
                new RuleBuilder2().
                    rule(-0.6, row(1, 3)).
                    rule(-0.3, row(2, 2)).
                    rule(0.0, row(2, 4), row(3,3), row(4, 2)).
                    rule(0.3, row(4, 4)).
                    rule(0.6, row(5, 3));

EDIT
Probably the names that I've used are not so meaningful; boxed/unboxed conversion is still a problem but this is a problem of Java

A: There's not much you can do here.  The warnings have to be suppressed; in practice, you never have to worry about serialVersionUID unless you are in fact planning to serialize this object.
The boxing can (and probably should) be removed by using a typed collection as described in other answers here.  To remove the boilerplate, you'll have to use a method.  For example:
private static void put (double key, int x, int y) {
  rules.put(key, new Point(x,y));
}


Q: Nautilus not starting promptly Rarely but very annoyingly Nautilus will stop responding from the Launcher. I have experienced this on two very different machines: a rack server (dual SSD, RAID 1, 8 real threads) as well as a notebook (single SSD, 4 thread, 8 hyperthread).
The busy icon will be displayed and Nautilus will not start. On the server, eventually Nautilus will work, perhaps 30 seconds later. On the notebook it didn't work after 30 seconds so I rebooted.
When this happens there is nothing else going on that can account for the sluggishness.
Sometimes the problem persists indefinitely, that is, until reboot.
What is the fix for this problem?
Edit: This is probably relevant:
https://bugs.launchpad.net/ubuntu/+source/nautilus/+bug/1569970
Edit This problem was first noticed with 16.04 and it is still a problem with 20.04. This problem is seen on machines set with swapping disabled or swappiness set to the very lowest possible value.

A: Yes, this brings back memories (from my time on 16.04).
Whenever Nautilus went unresponsive (not starting, just spinner), I went with a quick Ctrl+Alt+t & killall nautilus, which brought satisfactory results. But this is mentioned in the launchpad link that you added.
Regarding Gnome desktop on 20.04, in this post alternatives are also mentioned, such as nautilus -q and even reloading the Gnome-shell via the Run command dialog: Alt+F2 then r then Enter.
I considered this forced restart of the application a sufficient remedy, because 1.) it evaded the need to reboot, 2.) all in all, the glitch did not happen too often.
Back in the day I was not Linux-savvy enough to look up logs for clues. But I would assert for certain that the swap had never played a role in my cases, as I have plenty of physical memory and according to indicator-applet and later gnome-shell-extension-system-monitor my swap never had to be used.

Update:
You could try this:
sudo apt-get install --reinstall nautilus-data

Update 2:
Yet another way to force restart Nautilus (apparently more popular?):
# Get the PID with:
ps awx | grep nautilus

# Then:
sudo kill -TERM <PID here>

Additionally: do you have the habit of using plain sudo nautilus? (Admittedly I was guilty of it.) If you do too, it would be a priority to part with that habit, because it can only cause trouble.

A: Try to reinstall Nautilus
Here is how to do it:
sudo apt autoremove nautilus
sudo apt install nautilus


Q: How to get snapshot from Sonatype I'm trying to get the snapshot release for atmosphere that is available for org.atmosphere and can't seem to get it...
<repositories>
    <!-- Added to get the Atmosphere 1.1.0-SNAPSHOT, can be removed when 1.1.0 is released -->
    <repository>
        <id>oss.sonatype.org-snapshot</id>
        <url>http://oss.sonatype.org/content/repositories/snapshots</url>
        <releases><enabled>false</enabled></releases>
        <snapshots><enabled>true</enabled></snapshots>
    </repository>
</repositories>

There are no atmosphere versions that appear to be picked up by adding the new repository.
<dependency>
    <groupId>org.atmosphere</groupId>
    <artifactId>atmosphere-runtime</artifactId>
    <version>1.1.0-SNAPSHOT</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

I'm told by the primary atmosphere developer that this should work

A: Works fine for me. What error are you getting?
pom.xml
<?xml version="1.0"?>
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>example</artifactId>
  <version>1.0</version>
  <repositories>
    <!-- Added to get the Atmosphere 1.1.0-SNAPSHOT, can be removed when 1.1.0 is released -->
    <repository>
      <id>oss.sonatype.org-snapshot</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>
  <dependencies>
    <dependency>
      <groupId>org.atmosphere</groupId>
      <artifactId>atmosphere-runtime</artifactId>
      <version>1.1.0-SNAPSHOT</version>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
</project>

Update
$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building example 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ example ---
[INFO] org.example:example:jar:1.0
[INFO] \- org.atmosphere:atmosphere-runtime:jar:1.1.0-SNAPSHOT:compile
[INFO]    +- org.atmosphere:atmosphere-compat-jbossweb:jar:1.1.0-SNAPSHOT:compile
[INFO]    +- org.atmosphere:atmosphere-compat-tomcat:jar:1.1.0-SNAPSHOT:compile
[INFO]    +- org.atmosphere:atmosphere-compat-tomcat7:jar:1.1.0-SNAPSHOT:compile
[INFO]    \- eu.infomas:annotation-detector:jar:3.0.1:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.044s
[INFO] Finished at: Mon Apr 29 21:46:45 IST 2013
[INFO] Final Memory: 9M/301M
[INFO] ------------------------------------------------------------------------

A: Remove content of $HOME/.m2/repository/org/atmosphere/cpr and try again :)


Q: ImageIcon color issue when I fetch from assets in flutter I'm starting to learn flutter and at the moment, I'm trying to show an image from assets, but it's color going to change and I don't know why.
 IconButton(
        icon: ImageIcon(AssetImage("assets/icons/library.png")),
        onPressed: (){

        },
      ),

This is original red icon

And after fetching from assets it's looks like

A: I've used this before, the image must be of a PNG type, and it should be background is empty.
Or using it in another way, like this:
InkResponse(
        icon: Image.asset("assets/icons/library.png",width: 30,height: 30,),
         onTap: (){

         },
      ),


Q: Bot doesn't assign role in reaction role command So I've been trying to follow a tutorial on how to set up a reaction role command. Even though I do get the embed with the reactions that I wanted, when I react to it the bot doesn't assign the roles. After comparing the code to the tutorial I'm still not sure on what the problem here is.
This is the code:
module.exports = {
    name: 'reactionrole',
    description: "Sets up a reaction role message!",
    async execute(message, args, Discord, client){
        const channel = '851809318843187262';
        const yellowTeamRole = message.guild.roles.cache.find(role => role.name === "2D simp");
        const blueTeamRole = message.guild.roles.cache.find(role => role.name === "3D simp");

        const yellowTeamEmoji = '<:wings:851814106146144326>';
        const blueTeamEmoji = '<:crowshine:851814012290203680>';

        let embed = new Discord.MessageEmbed()
            .setColor('#e42643')
            .setTitle('Choose a team to play on!')
            .setDescription('Choosing a team will allow you to interact with your teammates!\n\n'
                + `${yellowTeamEmoji} for yellow team\n`
                + `${blueTeamEmoji} for blue team`);

        let messageEmbed = await message.channel.send(embed);
        messageEmbed.react(yellowTeamEmoji);
        messageEmbed.react(blueTeamEmoji);

        client.on('messageReactionAdd', async (reaction, user) => {
            if (reaction.message.partial) await reaction.message.fetch();
            if (reaction.partial) await reaction.fetch();
            if (user.bot) return;
            if (!reaction.message.guild) return;

            if (reaction.message.channel.id === channel) {
                if (reaction.emoji.name === yellowTeamEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(yellowTeamRole);
                }
                if (reaction.emoji.name === blueTeamEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(blueTeamRole);
                }
            } else {
                return;
            }

        });

        client.on('messageReactionRemove', async (reaction, user) => {

            if (reaction.message.partial) await reaction.message.fetch();
            if (reaction.partial) await reaction.fetch();
            if (user.bot) return;
            if (!reaction.message.guild) return;

            if (reaction.message.channel.id === channel) {
                if (reaction.emoji.name === yellowTeamEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(yellowTeamRole);
                }
                if (reaction.emoji.name === blueTeamEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(blueTeamRole);
                }
            } else {
                return;
            }
        });
    }
}


Q: html img tag within button tag not picking up javascript applied to button tag I have a dynamic formset where the user can click a button to remove forms from the formset before clicking submit. I've achieved this by applying some javascript to the button tag. This is a django app.
My issue arises when I add a trash can icon as the button's image. The image itself is not clickable and dynamic (i.e. removing the form when clicked), but the button area around the image is. I would like the entire thing to be clickable.
When trying to click the trash icon itself, nothing happens, and the console logs this error:
Uncaught TypeError: Cannot set properties of null (setting 'checked') at HTMLButtonElement.removeIngredient
When tracing this error, I encounter the following in the chrome console sources tab:
This image corresponds with the javascript below
HTML
<button class="remove-button" id="remove-ingredient" type="submit"><img src="{% static 'inventory/trash-icon.png' %}"></button>

CSS
.remove-button  {
    border: none;
    width: 100%;
    background-color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

.remove-button img {
    height: 20px;
    width: 20px;
}

.remove-button:hover {
    cursor: pointer;
}

Javascript
    function removeBtnListener () {
        const removeIngredientBtns = document.getElementsByClassName('remove-button')

        for (let i = 0; i < removeIngredientBtns.length; i++) {
            removeIngredientBtns[i].addEventListener('click', removeIngredient)
        }
    }

    function removeIngredient (event) {
        if (event) {
            event.preventDefault()
        }

        let ingredientFormToBeRemoved = event.path[1]
        let indexString = ingredientFormToBeRemoved.id
        let array = indexString.split('-')
        let indexNum = array[2]
        let deleteCheckbox = document.getElementById(`id_ingredientquantity_set-${indexNum}-DELETE`)
        deleteCheckbox.checked = true
        ingredientFormToBeRemoved.setAttribute('class', 'hidden')
    }

Here is an image of the formset. By clicking the area around the trash can icon (red outline), the form is removed. By clicking the trash can icon itself (green arrow), nothing happens.
Does anyone know how to make this work so the entire element removes the form properly when clicked?


Q: Google Web App Multiple Google Accounts Error I am creating a web app using Google Apps Script, and have run into kind of a wall.
Sometimes the users using the web app use it while being logged in with multiple Google accounts. There is a known error that shows up when a user attempts to access a google web app while being logged in with multiple accounts: Can't log in to Google Apps Scripts
The known solutions are:

*

*Log out of all accounts and log in as just one.

*Use incognito mode, thus being logged in as just one user

*Use a separate browser for separate Google Accounts.

Unfortunately, none of these solutions are fitting for the current situation. I myself know how to deal with the error, but how do I programmatically inform the user of these solutions?
What I am trying to do is to intercept this error page, and put out my own error, that could instruct the user to log out of their other accounts. I am deploying the web app using Google Sites, but have not had any luck with it there.
Thanks for any help!

A: Check the Issue Tracker

Unexpected "authorization is required" error from google.script.run after installing Sheets add-on while logged into multiple gmail.com accounts

*

*Comment #114, has a workaround for add-ons

*Comment #117, has another workaround for add-ons

You haven't mentioned what you are trying to accomplish, but there may be a workaround there.
Another idea might be to make an intermediate page that will serve as a sort of "landing page" that can remind your users about this issue and then re-direct them to the Web App. If you use cookies or the local storage API, then you could have it redirect immediately if they have seen it within the last few days.
Current known status of the bug
I seem to remember seeing somewhere, though I can't find it now, that the Apps Script team were planning on starting work to fix this in 2021.


Q: 'tags' parameter at Python Softlayer API call SoftLayer.VSManager.list_instances() not working as expected I am implementing a cloud bursting system with Softlayer instances and Slurm. But I got a problem with Python Softlayer API.
When I try to get a list of some specific instances with the API call SoftLayer.VSManager.list_instances() I use the parameter 'tags', since I tagged the instances to classify them. But it does not work as expected.
It is supposed to find instances whose 'tagReferences' field matches with the value of the parameter 'tags' you passed in the API call.
However, I get a list with all the nodes whose 'tagReferences' field is not empty. Whatever is the value I pass as 'tags' parameter.
I have the following nodes:

*

*hostname: 'node000' tags: 'slurm, node'

*hostname: 'node005' tags: 'test'

I run this script:
import os
import SoftLayer

os.environ["SL_USERNAME"] = "***"
os.environ["SL_API_KEY"] = "******"

client = SoftLayer.Client()
mgr = SoftLayer.VSManager(client)

for vsi in mgr.list_instances(tags = 'slurm'):
  print vsi['hostname']

This is the output I get:
node000
node005

I tried passing different values as 'tags' parameter (see below), but I always get the same result shown above, even with the last one.
Set of values passed as 'tags' parameter:
slurm, node
slurm
node
test
random

Did I miss anything?
I wrote a ticket to Softlayer support team but they believe my script should work and they assured me that the tags feature does work. Even they told me explicitly to come here to ask because they have no idea of what is happening.

A: According the documentation of the method that you are using, you need to send a list of tags, so change the string by a list like this:
client = SoftLayer.Client()
mgr = SoftLayer.VSManager(client)

for vsi in mgr.list_instances(tags = ['mytag']):
  print (vsi['hostname'])

Regards


Q: cheap reverse dns lookup Currently, I am running asp.net on a 4.0 Framework. I found one section of my code that is truly expensive for me to use.  I currently get the IP Address and the reverse dns for users accessing my site, however, I am trying to keep performance in mind.
Is there a cheaper alternative to this?
return System.Net.Dns.GetHostEntry(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).HostName;

A: Since the ServerVariables indexer returns a string, your code snippet calls the GetHostEntry string overload. Its documentation describes a three-step lookup algorithm, with two separate queries. The GetHostEntry IPAddress overload documentation doesn't describe any similar process, so perhaps it saves a query. Then again, it seems to provide the same info (all IP address and host names), so maybe it's the same, but just documented differently.


Q: how to sort and group by by it's count I have the following:
SELECT DISTINCT s.username, COUNT( v.id ) AS cnt
FROM  `instagram_item_viewer` v
INNER JOIN  `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN  `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >=  '2014-08-01'
GROUP BY (
s.id
)
ORDER BY cnt DESC

Basically I have an instagram_item_viewer with the following structure:
id  viewer_id  item_id  created

It tracks when a user has viewed an item and what time. So basically I wanted to find shops that has the most items viewed. I tried the query above and it executed fine, however it doesn't seem to give the appropriate data, it should have more count than what it is. What am I doing wrong?

A: First, with a group by statement, you don't need the DISTINCT clause. The grouping takes care of making your records distinct.
You may want to reconsider the order of your tables. Since you are interested in the shops, start there.
Select s.username, count(v.id)
From instagram_shop s
  INNER JOIN instagram_shop_picture p ON p.shop_id = s.shop_id
INNER JOIN instagram_item_viewer v ON v.item_id = p.id
  AND v.created >= '2014-08-01'
WHERE s.expirydate IS NULL
  AND s.isLocked = 0
GROUP BY s.username

Give thata shot.

A: As mentioned by @Lennart, if you have a sample data it would be helpful. Because otherwise there will be assumptions.
Try run this to debug (this is not the answer yet)
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM  `instagram_item_viewer` v
INNER JOIN  `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN  `instagram_shop` s ON p.shop_id = s.id
    AND s.expirydate IS NULL
    AND s.isLocked =0
    AND v.created >=  '2014-08-01'
GROUP BY (
    s.username, p.id
)
ORDER BY cnt DESC

The problem here is the store and item viewer is too far apart (i.e. bridged via shop_picture). Thus shop_picture needs to be in the SELECT statement.
Your original query only gets the first shop_picture count for that store that is why it is less than expected
Ultimately if you still want to achieve your goal, you can expand my SQL above to
SELECT x.username, SUM(x.cnt) -- or COUNT(x.cnt) depending on what you want
FROM
    (
    SELECT s.username, p.id, COUNT( v.id ) AS cnt
    FROM  `instagram_item_viewer` v
    INNER JOIN  `instagram_shop_picture` p ON v.item_id = p.id
    INNER JOIN  `instagram_shop` s ON p.shop_id = s.id
        AND s.expirydate IS NULL
        AND s.isLocked =0
        AND v.created >=  '2014-08-01'
    GROUP BY (
        s.username, p.id
    )
    ORDER BY cnt DESC
) x
GROUP BY x.username


Q: ¿Cómo puedo redireccionar a una parte específica de mi página después de algún proceso en el controlador? Quiero que despues de que mi codigo, ha hecho ciertos procedimientos me redireccione a un div en especifico de mi index lo he intentado de esta manera pero no haya la pagina:
request.getRequestDispatcher("index.jsp#contenedor3").forward(request,response);

A: La redireccion a determinada posicion solo puedes realizarla desde el lado del cliente.
Podrias usar librerias como ser
jquery.scrollTo
Entonces no necesitas definir un ancla de html, sino que le indicas al id de cual div o control en tu página te quieres desplazar.
En el ejemplo veras como el div esta bien abajo despues de varios parrafos, pero el $.scroolTo() mueve el scroll a la posicion del div para dejarlo visible

$(function(){

  $.scrollTo("#div1");

});

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

linea

 contenido div

A: Primero que nada, al utilizar esto
request.getRequestDispatcher("index.jsp#contenedor3").forward(request,response);

Estás ejecutando un forward, no un redirect. Esto no te permitirá ubicarte en la posición que deseas. Si utilizas forward, tu mejor opción será hacer el forward a tu vista JSP directamente, en este caso index.jsp, y luego al cargar la página ejecutar un código JavaScript que te permita navegar al anchor. Puedes hacerlo de esta manera.
$(document).ready = () {
    window.location = '#contenedor3'; //asumiendo que tu anchor funciona
};

En vista que estás utilizando forward, puedes agregar un atributo en tu request para este caso particular, de manera que solo cuando se acceda a la página mediante el procesamiento de este request. Podrías tener algo así.
En tu controller:
request.setAttribute("anchor", "contenedor3");
request.getRequestDispatcher("index.jsp#contenedor3").forward(request,response);

En tu vista (jsp):
<c:if test="${anchor eq 'contenedor3'}">

</c:if>

La otra opción, si es viable, es utilizar un redirect hacia tu página y anchor.

A: La forma en que lo pude solucionar fue usando

HttpSesion session=request.getSession();
  session.setAttribute("NombreParametro","ValorDeParametro");
  response.sendRedirect("index.jsp#contenedor1");


Q: Getting the Image to display in a Custom ButtonImage Control c# I'm new to c# and i'm trying to create a ButtonImage Control. I've managed to get most of the code to work including TextAlignment and image resource selection, but the image won't display. I've tried adding TextImageRelation property as well as the ImageAlignment property to no effect - not even sure if I've done everything correctly. I've spent hours searching MSDN and the internet, please help, tnx. Heres the code:
namespace ImageButton
{
    //[System.ComponentModel.DefaultBindingProperty("ButtonText")]
    public partial class ImageButton : UserControl
    {
        private String name = "btn1";
        private String btnText = "Button1";
        private TextImageRelation textImage = TextImageRelation.Overlay;
        private ContentAlignment alignmentValue = ContentAlignment.MiddleRight;
        private ContentAlignment imageAlignmentValue = ContentAlignment.MiddleLeft;

        public ImageButton()
        {
            InitializeComponent();
        }
        //
        // Properties
        //
        [Description("Sets the Text Label"),
         Category("Custom")]
        public String ButtonText
        {
            get
            {
                return btnText;
            }
            set
            {
                btnText = value;
                btn1.Text = btnText;
            }
        }
        [Description("Sets the Button Image"),
         Category("Custom")]
        public Image Image
        {
            get;
            set;
        }
        [Description("Specifies the relationship of text to Image."),
         Category("Custom")]
        public TextImageRelation TextImageRelation {
            get{
                return textImage;
            }
            set{
                textImage =value;
                btn1.TextImageRelation = textImage;
            }
        }
        [Category("Custom"),
         Description("Specifies the alignment of text.")]
        public ContentAlignment TextAlignment
        {
            get
            {
                return alignmentValue;
            }
            set
            {
                alignmentValue = value;
                btn1.TextAlign = alignmentValue;
                //Invalidate();
            }
        }
        [Category("Custom"),
         Description("Specifies the alignment of text.")]
        public ContentAlignment ImageAlignment
        {
            get
            {
                return imageAlignmentValue;
            }
            set
            {
                imageAlignmentValue = value;
                btn1.ImageAlign = imageAlignmentValue;
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            StringFormat style = new StringFormat();
            style.Alignment = StringAlignment.Far;
            switch (alignmentValue)
            {
                case ContentAlignment.MiddleLeft:
                    style.Alignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    style.Alignment = StringAlignment.Far;
                    break;
                case ContentAlignment.MiddleCenter:
                    style.Alignment = StringAlignment.Center;
                    break;
            }
            // Call the DrawString method of the System.Drawing class to write
            // text. Text and ClientRectangle are properties inherited from
            // Control.
            e.Graphics.DrawString(
                Text,
                Font,
                new SolidBrush(ForeColor),
                ClientRectangle, style);
        }
    }
}

A: Solved:
instead of:
    public Image Image{ get; set;}

as other ppl have suggested, I used
    public Image Image{
        get { return image; }
        set
        {
            image = value;
            btn1.Image = image;
        }
    }


Q: Make the PopupMenu appear at the selected Item of a TreeView in VB6 I hava a TreeView in VB6 that uses a PopupMenu when a Node is right clicked. As the VB6 PopupMenu defaults its position to the mouse coordinates the menu appears at the right place.
What I want to accomplish is that the Popupmenu appears at the right place too on a KeyDown event when a TreeView Node is selected. How can I do this?

A: You need to obtain coordinates of the item. For that you need to first obtain its handle. And when you get the rect, you must translate it to form coordinates.
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByRef lParam As Any) As Long
Private Declare Function MapWindowPoints Lib "user32.dll" (ByVal hwndFrom As Long, ByVal hwndTo As Long, ByRef lppt As Any, ByVal cPoints As Long) As Long

Private Type RECT
  Left As Long
  Top As Long
  Right As Long
  Bottom As Long
End Type

Private Type RECTF
  Left As Single
  Top As Single
  Right As Single
  Bottom As Single
End Type

Private Const TV_FIRST As Long = &H1100&
Private Const TVM_GETITEMRECT As Long = (TV_FIRST + 4)
Private Const TVM_GETNEXTITEM As Long = (TV_FIRST + 10)
Private Const TVGN_CARET As Long = &H9&

Private Function GetSelectedItemRect(ByVal tv As TreeView, ByRef outRect As RECTF) As Boolean
  Dim hItem As Long
  hItem = SendMessage(tv.hwnd, TVM_GETNEXTITEM, TVGN_CARET, ByVal 0&)

  If hItem Then
    Dim r As RECT
    r.Left = hItem

    If SendMessage(tv.hwnd, TVM_GETITEMRECT, 1, r) Then
      MapWindowPoints tv.hwnd, Me.hwnd, r, 2

      outRect.Left = Me.ScaleX(r.Left, vbPixels, Me.ScaleMode)
      outRect.Top = Me.ScaleY(r.Top, vbPixels, Me.ScaleMode)
      outRect.Right = Me.ScaleX(r.Right, vbPixels, Me.ScaleMode)
      outRect.Bottom = Me.ScaleY(r.Bottom, vbPixels, Me.ScaleMode)

      GetSelectedItemRect = True
    End If
  End If

End Function

Usage:
Dim r As RECT

If GetSelectedItemRect(TreeView1, r) Then
  PopupMenu whatever, , r.Right, r.Top
End If


Q: Bayesian Inference Using Functions of Parameters Assume $\mathbf{X}$ has a pdf that depends on the two parameters $\mu, \sigma$ given by $h(\mathbf{x}|\mu, \sigma)$.  Traditionally, Bayes' theorem allows the computation of the posterior pdf $g(\mu, \sigma|\mathbf{x})$ via
$$
g(\mu, \sigma|\mathbf{x}) \propto h(\mathbf{x}|\mu, \sigma)\cdot g(\mu, \sigma).
$$
Suppose, however, that I wish to reparameterize the pdf of $\mathbf{X}$ via $h(\mathbf{x}|f_1(\mu, \sigma), f_2(\mu, \sigma))$ for some functions $f_1$ and $f_2$ of the original parameters.  I would still like to specify my prior in terms of the original parameters, like
$$
g(\mu, \sigma|\mathbf{x}) \propto h(\mathbf{x}|f_1(\mu, \sigma), f_2(\mu, \sigma))\cdot g(\mu, \sigma),
$$
but I'm not sure this is permissible.  Would I have to compute the pdf $\tilde{g}$ of $f_1(\mu, \sigma), f_2(\mu, \sigma)$ and then use
$$
g(\mu, \sigma|\mathbf{x}) \propto h(\mathbf{x}|f_1(\mu, \sigma), f_2(\mu, \sigma))\cdot \tilde{g}(f_1(\mu, \sigma), f_2(\mu, \sigma))
$$
instead?
Example: Suppose each $X_i \sim \mathcal{N}\left( \left(\mu - \frac{\sigma^2}{2}\right)\Delta t, \sigma^2 \Delta t \right)$ and is independent for $i=1,\dots,N$.  Here, $\Delta t$ is just some fixed constant.  In the notation above, $f_1(\mu,\sigma) = \left(\mu - \frac{\sigma^2}{2}\right)\Delta t$ and $f_2(\mu,\sigma) = \sigma^2 \Delta t$ (so $f_2$ is not dependent on $\mu$ in this case).  I'd like to specify the marginal pdfs of $\mu$ and $\sigma$ and maximize the posterior pdf $g(\mu,\sigma|\mathbf{x})$.

A: To answer the more broad question,
$$
g(\mu, \sigma|\mathbf{x}) \propto h(\mathbf{x}|f_1(\mu, \sigma), f_2(\mu, \sigma))\cdot g(\mu, \sigma)
$$
would be correct and in most instances the functional notation is implied so we write
$$
g(\mu, \sigma|\mathbf{x}) \propto h(\mathbf{x}|\mu, \sigma)\cdot g(\mu, \sigma)
$$
regardless.  Using your notation,
$$
g(f_1(\mu, \sigma), f_2(\mu, \sigma)|\mathbf{x}) \propto h(\mathbf{x}|f_1(\mu, \sigma), f_2(\mu, \sigma))\cdot \tilde{g}(f_1(\mu, \sigma), f_2(\mu, \sigma))
$$
would also be acceptable, and may be preferred if you can invert $f_1$ and $f_2$ to simulate $g(\mu|\sigma,\mathbf{X})$ and $g(\sigma|\mu,\mathbf{X})$ from $g(f_1(\mu, \sigma), f_2(\mu, \sigma)|\mathbf{x})$ which I do below using your example.
In practice, the parameters of the likelihood are almost always expressed as functions of multiple other parameters relevant to the model being analysis.  For example the likelihood of a non-linear regression model $y_i = f(x_i,\boldsymbol{\beta})+\varepsilon_i$ may be written as $\prod_{i=1}^n h(y_i|x_i,\boldsymbol{\beta},\sigma^2)$ where $h(y_i|x_i,\boldsymbol{\beta},\sigma^2) \equiv N(f(x_i,\boldsymbol{\beta}),\sigma^2)$.
It is certainly true that $f_1$ and $f_2$ make life harder because it is more challenging if not impossible to find conjugate priors.  However, we can usually use Monte Carlo techniques to simulate the posterior distribution anyway for these cases.
Take your example for instance.  This looks like a continually compacted return of a stock where that stock price follows geometric brownian motion, in which case $\Delta t$ is not a random variable but is in fact known.  So without loss of generality, let $\Delta t=1$.
One option would be to use substitution by letting $\mu_* = \bigg(\mu-\frac{\sigma^2}{2} \bigg)$ so that $X_i \sim N(\mu_*,\sigma^2)$. Choose the appropriate conjugate priors for $\mu_*$ and $\sigma^2$ (i.e. normal-gamma) so that the posterior distribution of the parameters is known and has a closed form.  Then you can simply simulate $\mu=\mu_*+\frac{\sigma^2}{2}$ from that posterior distribution to obtain a Monte Carlo sample from the posterior distribution of $\mu$.
An alternative approach would be to specify a normal prior for $\mu$ so that the conditional posterior $g(\mu|X,\sigma^2)$ is conjugate normal.  You can then use a Gibbs sampling type approach where $g(\sigma^2|X,\mu)$ would have to be drawn using a Metropolis-Hastings step.


Q: Relations between Laplacian and Fourier transform I have been thinking this question for a couple of days. To be more specific, I want to derive an explicit expression of Fourier transform under some coordinate chart of a manifold. What I do have right now is the Riemannian metric and associated Laplace-Beltrami operator under this chart. Does anyone have some suggestions on what I can do to obtain the expression of the Fourier transform starting from the Laplacian? For example, if the coordinate chart is $(x,y,z)$ and Laplace-Beltrami operator is given by
$$
\Delta = \frac{\partial^2}{\partial x^2}+\frac{\partial^2}{\partial y^2}-2c\frac{\partial^2}{\partial x\partial y}+\frac{\partial}{\partial z}\left(f(z)\frac{\partial}{\partial z}\right)
$$
where $c$ is some constant and $f(z)$ is a smooth function of $z$, what will be the expression for the Fourier transform? Thank you in advance!


Q: Context with filtering for daterange is not working I am having a view that is working and properly returning results as long as I am not filtering for dates. As soon as I start to add a filter e.g. booking_time__range = (start_date, end_date) no results are returned in my template. I have no tried to find the error by myself for several days, now I need the wisdom of the crowd.
My Model:
from django.db import models
from django.utils import timezone
from users.models import Account
from organization.models import Organization, Office

class Booking(models.Model):
    LOCATION_OPTIONS = (
            ('H', 'Home Office'),
            ('O', 'Office'),
            ('N', 'Not indicated'),
    )
    account             = models.ForeignKey(Account, on_delete=models.CASCADE)
    organization        = models.ForeignKey(Organization, on_delete=models.CASCADE)
    office              = models.ForeignKey(Office, on_delete=models.CASCADE)
    booking_time        = models.DateTimeField(default=timezone.now)
    location            = models.CharField(max_length=1, choices=LOCATION_OPTIONS)
    class Meta:
            unique_together = ('account', 'booking_time',)

My View:
def overview_view(request):

    context = {}

    if request.method == 'GET':
        start_date = None
        end_date = None
        if request.is_ajax():
            booking_times = request.GET.get('day')
            start_date = datetime.strptime(booking_times, "%Y-%m-%d")
            end_date = start_date + timedelta(days=4)
            start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc)
            end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc)

        context['bookings']=Booking.objects.filter( Q(organization_id=request.user.organization_id), Q(booking_time__range = (start_date, end_date))
        context['office'] = Office.objects.filter(organization_id__exact=request.user.organization_id)

        return render(request, 'overview/overview.html', context)
   return render(request, 'overview/overview.html', context)

Both start_date and end_date are datetime.datetime format. As soon as I remove Q(booking_time__range = (start_date, end_date) results will show. But I really need this filter.
My template:
    {{ office.office_name }}
    {% for booking in bookings %}

{{ booking.account.first_name }} {{ booking.account.last_name }}

                {% if booking.get_location_display == 'House' %}

 {{ booking.get_location_display }}

                {% elif booking.get_location_display == 'Home' %}

 {{ booking.get_location_display }}

                {% else %}

 {{ booking.get_location_display }}

                {% endif %}

    {% endfor %}
{% endfor %}

Thank you very much for your help.


Q: Why is double tap still being picked up in this IOS code? Background
- I have a map (MapKit) with a callout (custom view added to an annotation view)
- I have managed to ensure that the "long press" gesture made over the callout view does not get picked up (see below, using "shouldReceiveTouch")
Issue
What I can't do is do the same thing (i.e. ignore) a double-click over the callout view, in that the MapKit map still somehow picks this up and zooms in.  I've tried putting the Double Tap gesture in to trap it however it doesn't seem to be working.
Mapkit View Delegate Code
Setup of Gesture Recognisers
// Gesture Recogniser (Long Press)
let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
longPressGR.minimumPressDuration = 1
longPressGR.delegate = self
self.mapView.addGestureRecognizer(longPressGR)

// Gesture Recogniser (Double Tap)
let doubleTapGR = UITapGestureRecognizer(target: self, action: "doubleTapAction:")
doubleTapGR.numberOfTapsRequired = 2
doubleTapGR.delegate = self
self.mapView.addGestureRecognizer(doubleTapGR)

Implement the "shouldReceiveTouch" for UIGestureRecognizerDelegate
extension GCMapViewHelper : UIGestureRecognizerDelegate {
 func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
    guard let touchesView = touch.view else { fatalError("ERROR: Touch event received was nil") }

    for annotation in self.mapView.selectedAnnotations {
        if annotation is GCAnnotation {
            let annotationView = self.mapView.viewForAnnotation(annotation)
            if let annotationView = annotationView {
                if (touchesView.isDescendantOfView(annotationView)) {
                    return false
                }
            }
        }
    }
    return true
 }
}

EDIT: It seems the issue is the double-tap gesture recognizer is NOT picking up the double tap...any ideas?  i.e. this is not working..
doubleTapGR.numberOfTapsRequired = 2

EDIT 2 Here is a simplified view of the issue re code example:
With the code below in terms of what I see in the console output from print statements:
* "longPressAction" - This appears/works
* "tapAction" - This does NOT appear, even when I double tap over the MKMapView.  So this is my isssue here.
import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var mapview: MKMapView!

    func longPressAction() {
        print("longPressAction")
    }

    func tapAction() {
        print("tapAction")  // ** Not appearing in console **
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Gesture Recogniser (Long Press)
        let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction")
        longPressGR.minimumPressDuration = 1
        self.mapview.addGestureRecognizer(longPressGR)

        let tapGR = UITapGestureRecognizer(target: self, action: "tapAction")
        tapGR.numberOfTapsRequired = 2
        self.mapview.addGestureRecognizer(tapGR)

        //tapGR.requireGestureRecognizerToFail(longPressGR)

    }

}

A: While it's not a direct answer to your question - I have a workaround for you.
If you add your gesture recognizers to your custom annotation view then you can capture both long press and double tap over the annotation view and any associated callout.
Some example code I wrote to try this:
import UIKit
import MapKit

class StarAnnotation : NSObject, MKAnnotation {
    let title: String?
    let coordinate: CLLocationCoordinate2D

    init(title: String, coordinate: CLLocationCoordinate2D) {
        self.title = title
        self.coordinate = coordinate
        super.init()
    }
}

class StarAnnotationView : MKAnnotationView, UIGestureRecognizerDelegate {
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        self.image = UIImage(named: "star")

        // Gesture Recogniser (Long Press)
        let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
        longPressGR.minimumPressDuration = 1
        longPressGR.delegate = self
        self.addGestureRecognizer(longPressGR)

        // Gesture Recogniser (Double Tap)
        let doubleTapGR = UITapGestureRecognizer(target: self, action: "doubleTapAction:")
        doubleTapGR.numberOfTapsRequired = 2
        doubleTapGR.delegate = self
        self.addGestureRecognizer(doubleTapGR)

    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func doubleTapAction(recognizer: UITapGestureRecognizer) {
        if recognizer.numberOfTapsRequired == 2 {
            print("double tapped")
        }
    }

    func longPressAction(recognizer: UILongPressGestureRecognizer) {
        print("long pressed")
    }
}

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // set up map view and sample annotation
        let operaHouseCoord = CLLocationCoordinate2D(latitude: -33.8587, longitude: 151.2148)
        let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
        let operaHouseAnnotation = StarAnnotation(title: "Opera House", coordinate: operaHouseCoord)
        mapView.region = MKCoordinateRegion(center: operaHouseCoord, span: span)
        mapView.delegate = self
        mapView.addAnnotation(operaHouseAnnotation)
    }

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? StarAnnotation {
            let identifier = "star"
            if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? StarAnnotationView {
                dequeuedView.annotation = annotation
                return dequeuedView
            } else {
                let view = StarAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                view.canShowCallout = true
                return view
            }
        }
        return nil
    }
}


Q: about bounded boxes of objects i'm trying to compose a dataset for the detection of soccer players, ball etc.. in a soccer game, i'm using alexeyAB Darknet framework,
So in the labeling phase in each image there are at least 8 players a ball and other stuff, at some point it is logical to think about the fact that i will have enough instances per player, but not enough for the ball and the goalkeeper for example,
so can i only marking bounded boxes the ball and other things avoiding to do it with the players to not waste time?

A: If you are training the model on your own dataset, I would recommend limiting the number of labels/classes in your data to what you seek. For example if you only want your model to see balls, goal-posts and Not players, simply keep the classes as balls and goal-posts. (This reminds me of a classification problem where 0 stands for balls and 1 stands for goal-post). P.S you mentioned object detection and Not Localization, which is the purpose of the YOLO models.


Q: How can I customize the arguments to a kubernetes system pod such as kube-apiserver in Kind? I want to customize the arguments to kube-apiserver so that I can inspect the requests being made, so that I can debug a failing request. However, I'm not sure what I need to modify. I know that kube-apiserver can't be being deployed with helm, because helm requires an API server in order to do its job. So it must be being deployed via some other bootstrapping method, but looking at the kind source code I can't figure out what that method is.

A: The kube-apiserver is configured with a static manifest file, which is stored in /etc/kubernetes/manifests/kube-apiserver.yaml.
So find out the ID of the container that is the Kubernetes control plane node in kind:
docker ps|grep cluster-control-plane

Get a shell in it:
docker exec -it 4aeedccce928 bash

Install an editor (e.g. emacs) and edit the aforementioned file to add/remove/replace the desired arguments:
apt-get update
apt-get install emacs-nox
emacs /etc/kubernetes/manifests/kube-apiserver.yaml

Kubernetes will detect the file change and automatically restart the server, which can be validated with:
ps -Afl|grep kube-apiserver

If it crashes on startup, you can find the logs using
apt-get install less
less /var/log/pods/kube-system_kube-apiserver-cluster-control-plane_*/*/*.log

If the container fails to start at all, there will not be any log file there - check the manifest file for syntax errors by referring to the Kubernetes documentation.


Q: Django filter a prefetched queryset returning an empty list In my app I have some Users and Groups, that are related by a many to many relation through GroupMember.
class User(models.Model):
    ...

class Group(models.Model):
    ...
    users = models.ManyToManyField(User, through='groups.GroupMember', related_name='groups')

class GroupMember(models.Model):
    ...
    user = models.ForeignKey(User, related_name='group_members', on_delete=models.CASCADE)
    group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE)

Now I am trying to build an endpoint that retrieves a list of user instances that are in any one of the groups that your user is in. So if user A and B are in group1, user A and C are in group2, and C and D are in group3, retrieving the users as A would return B and C (since those are in groups with A).
That filter part can be done in multiple ways, but the part where I am stuck is how to show which groups were the cause of the relation. I tried to use prefetch_related with a custom filter, to fetch only the groups that have user A in them, like this:
User.objects.exclude(id=user.id).annotate(
    # Annotate the amount of groups related between the users
    related_group_count=Count('groups', filter=Q(groups__users=user))
).filter(
    # Only users that have at least 1 relation with this user
    related_group_count__gt=0
).prefetch_related(
    # Prefetch the specific groups to show
    Prefetch('groups', User.groups.all(), to_attr='related_groups'),
)

The returned users will not have any related_groups, it will be an empty qs. When I include the request user (by removing the exclude part on the query), the groups will be available for that user, but still not any other. This is my current response (including the requesting user "A"):
{
    "first_name": "A",
    "related_groups": [
        {
            "name": "group1",
        },
        {
            "name": "group2",
        }
    ]
},
{
    "first_name": "B",
    "related_groups": []
},
{
    "first_name": "C",
    "related_groups": []
}

But I'm trying to achieve this:
{
    "first_name": "B",
    "related_groups": [
        {
            "name": "group1",
        }
    ]
},
{
    "first_name": "C",
    "related_groups": [
        {
            "name": "group2",
        }
    ]
}

The problem lies with the filter on the Prefetch queryset, but I can't figure out what I'm doing wrong or if this is even possible. I tried different way of filtering (also with Group.objects.filter(users=user)) or even annotating the group members, counting if the given user is in that group and filtering on that, but with no success...

Note: This only happens when filtering the prefetch as described above: User (is group member) -> Group -> User (group member). It looks like the filter is "overwriting" the user in the queryset with the initial user (A).
In my project I work with multiple group-like concepts, one of which has 2 different kind of members (lets say, in context of this question a second GroupMember type model, with an additional many to many relation in the group model to user). When using User (group member) -> Group -> User (other kind of member), the prefetch actually works as expected. This issue is only when prefetching using the same through-model in relation to the user.

A: I managed to get this to work, by using a separate queryset that gets the group ids. This way the prefetch filter will not use the requesting user id to filter, which resulted in empty lists for all other users.
group_ids = user.groups.values('pk')

User.objects.exclude(id=user.id).filter(
    groups__in=group_ids
).prefetch_related(
    Prefetch('groups', Group.objects.filter(id__in=group_ids), to_attr='related_groups'),
)


Q: Set fixed size of a QDialog without cutting text I currently set a QDialog to have a fixed size using the following code
dlg->setWindowModality(Qt::WindowModal);
dlg->setFixedSize(dlg->size());

Now as a result of this code whatever size I save my ui form in QT Designer. It sticks to that size.This however ends up being a issue in some systems and displays. Where my Qlabels begin to cut from the sides due to the shortage of space.I wanted to know what would be the proper way of doing this ? How would I determine which size would accommodate the layout on the form.The form itself has a horizontal layout which has multiple layouts in it ??

A: Try
dlg->adjustSize();
dlg->setFixedSize(dlg->sizeHint());


Q: R: Tabulate each column of a sparse matrix against a vector I have a logical sparse matrix, say m, (which can be any of Matrix, slam, or SparseM matrices if that makes things faster) that I want to do the following on:
for (col in 1:ncol(m)) {
  print(table(m[ , col], logicalV)
}

where logicalV is a fixed logical vector of the same length as rows in m. Think of this as creating a confusion matrix per feature in the sparse m.
The dimensions I am dealing with for m are: (15 ~ 40K) x (75 ~ 125K). This makes just the step of accessing the columns m[ , col] really slow.
What I am looking for is a fast solution here. Any ideas?
Edit:
Based on the comments, here is an outline of what I am really trying to achieve. I have a bunch of feature selection metrics like information gain, binormal separation, etc. which are all functions of the confusion matrix (i.e. table(m[ , col], logicalV)) as they are functions of the counts of true positives / negatives and false positives / negatives. So for each column and logicalV, I need to know counts of both TRUE, both FALSE, and either TRUE. Does that help?


Q: How to get n unique numbers uniformly from a given range? I have a integer range [0, Z). I need to obtain n (where n <= Z) random numbers from this range, but they have to be unique. So I know I can just code up rejection sampling to do this, but I'm wondering if there's a one line python function that can do this for me?

A: why not use random sampling without replacement
import numpy as np

n = 25
a = range(26)
out = np.random.choice(a, size=n, replace=False)

len(np.unique(out))
>>>25


Q: java servlet compile error 1.i added the path C:\Program Files (x86)\Java\jdk1.6.0_01\bin for java and C:\TOMCAT\apache-tomcat-7.0.55\lib for tomcat.
2.i have started startup.bat in C:\TOMCAT\apache-tomcat-7.0.55\bin and it works fine.
3.it displays in 8084 port(localhost:8084/).
4.i created a MyServlet.java file in Directory E.
5.i wanted to compile it through command line(javac MyServlet.java) bt errror comes.
i have tried and tried bt.. :( ..plz help me to fix it.
MyServlet.java code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends  HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResposne response)
                 throws ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("
Hello Readers
");
out.println("");
}
}

and cmd errors:
E:\>javac MyServlet.java
MyServlet.java:1: package javax.servlet does not exist
import javax.servlet.*;
^
MyServlet.java:2: package javax.servlet.http does not exist
import javax.servlet.http.*;
^
MyServlet.java:7: package javax.servlet does not exist
import javax.servlet.ServletException;
                ^
MyServlet.java:8: package javax.servlet.http does not exist
import javax.servlet.http.HttpServlet;
                     ^
MyServlet.java:9: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletRequest;
                     ^
MyServlet.java:10: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletResponse;
                     ^
MyServlet.java:12: cannot find symbol
symbol: class HttpServlet
public class MyServlet extends  HttpServlet
                            ^
MyServlet.java:14: cannot find symbol
symbol  : class HttpServletRequest
location: class MyServlet
public void doGet(HttpServletRequest request,HttpServletResposne response)
              ^
MyServlet.java:14: cannot find symbol
symbol  : class HttpServletResposne
location: class MyServlet
public void doGet(HttpServletRequest request,HttpServletResposne response)
                                         ^
MyServlet.java:15: cannot find symbol
symbol  : class ServletException
location: class MyServlet
                 throws ServletException
                        ^
10 errors

A: Declaring Class
public class MyServlet extends  HttpServlet

instead of
public MyServlet extends  HttpServlet

A: you forget the keyword class when define a class, just put the class before the class name


Q: Formatting text using PDFsharp I want to apply style to
string "Helloword"
and have style properties
like fontFamily='Verdana',  fontStyle='bold', FontSize='12', textDecoration='underline', textAlign='center', fontColor='#FF0000', x=100 and y=100.
I want to display this string in PDF using PDFsharp. can anyone suggest me how to do that?
I'm using XFont and XGraphics.DrawString method but I'm not able to apply all above styles.

A: The string is slightly incorrect, but I hope all other requirements are met:
// Create a font
XFont font = new XFont("Verdana", 12, XFontStyle.Bold | XFontStyle.Underline);

// Draw the text
gfx.DrawString("Hello, World!", font, new XSolidBrush(XColor.FromArgb(255, 0, 0)),
  100, 100,
  XStringFormats.Center);


Q: Ruby on Rails routing by resources with many-to-many relationship Ok, this gives me some headaches!
I have a many-to-many relationship with a link table that has a few attributes on its on:
user linked to items through ownings
The active-record part is clear to me. But what are my resources here? Clearly there are users and items. Items are going to be managed on their own. I want to link users to items from the users view having a link to a page where the items of the user are shown (and can be remove from that particular user) and a link to a page where new links between the user and an existing item can be created (also entering the link table attributes).
Would you manage that by putting more user defined methods/routings in the user controller or would you have another controller as subresource of the user controller?
What confuses me is that resourceful routing takes you by the hand and says, that on a theoretical basis you have these x methods, that is probably all you gonna need. And than the rails routing guide for example has a hole lot more text to show you what else you can do to tweak around with resourceful routing. But at that point I feel left alone since I don't know what to tweak! Only two hints are given: Do not nest resources more levels deep than one and do not ad user defined methods a lot.
Do you know what to do or what book/guide would you recommend for these kind of questions.


Q: $x\sqrt{1-\frac{y(x+1)}{(x+y+1)^2}} = y\sqrt{1-\frac{z(y+1)}{(y+z+1)^2}} = z\sqrt{1-\frac{x(z+1)}{(z+x+1)^2}}$
If $x,y,z > 0$, and $$x\sqrt{1-\frac{y(x+1)}{(x+y+1)^2}} = y\sqrt{1-\frac{z(y+1)}{(y+z+1)^2}} = z\sqrt{1-\frac{x(z+1)}{(z+x+1)^2}}$$
Prove $x=y=z$.

I try it by Mathematica but can not solve, and Maple give a solution, but so complicated. I want to use inequality, but never find the solution.

A: Let $$f(x,y)=x^2\Bigg(1-\frac{(x+1)y}{(x+y+1)^2}\Bigg)$$
Then the hypothesis says that $f(x,y)=f(y,z)=f(z,x)$. Note that for $x\neq y$ and $x,y$ positive,
$$
\frac{f(y,x)-f(x,y)}{y-x}=\frac{x^3+y^3+2(x^2+y^2)+xy(2(x+y)+3)+x+y}{(x+y+1)^2} > 0 \tag{1}
$$
Similarly, if we expand $\frac{f(x_2,y)-f(x_1,y)}{x_2-x_1}$, we find that it is equal to $\frac{P(x_1,x_2,y)}{(x_1+y+1)^2(x_2+y+1)^2}$ where $P$ is a polynomial in $x_1,x_2,y$ with positive coefficients. So for $x_1\neq x_2$ and $x_1,x_2,y$ positive, we have
$$
\frac{f(x_2,y)-f(x_1,y)}{x_2-x_1}> 0 \tag{2}
$$
We can now proceed with the proof. Suppose that $x<y$. Then $f(y,x)>f(x,y)$ by (1),but $f(x,y)=f(z,x)$ by hypothesis, so $f(y,x)>f(z,x)$. By (2) we deduce $y>z$. Then $f(y,z)>f(z,y)$ by (1),but $f(y,z)=f(x,y)$ by hypothesis, so $f(x,y)>f(z,y)$. By (2) we deduce $x>z$.
At this point we have $y>x>z$. Then $f(x,z)>f(z,x)$ by (1),but $f(z,x)=f(y,z)$ by hypothesis, so $f(x,z)>f(y,z)$ which contradicts (1).
This shows $x\geq y$. Similar arguments show that $y\geq z$ and $z\geq x$, and finally $x=y=z$.


Q: setState update a mounted or mounting component Here is my code:
import React, { Component } from 'react';
import styled from 'styled-components';

const BtnBox = styled.ul`
display:flex;
width:50vw;
align-items:center;
justify-content:flex-start;
font-weight:900;
font-size:5vw;
letter-spacing:-0.5vw;
`;
const MyBtn = styled.li`
width:30%;
font-size:5vw;
display:flex;
align-items:center;
justify-content:flex-start;
cursor:pointer;
`;

class SignAndLog extends Component {
  constructor(props) {
    super(props);
    this.state = { Scolor: 'black', Lcolor: 'grey' };
    this.chooseFun = this.chooseFun.bind(this);
    localStorage.setItem('fuck', this.state.Scolor);
  }

  chooseFun(e) {
    const myName = e.target.dataset.name;
    if (myName === 'sign') {
      this.setState({
        Scolor: 'black',
        Lcolor: 'grey'
      });
      localStorage.setItem('status', myName);
    } else {
      this.setState({
        Scolor: 'grey',
        Lcolor: 'black'
      });
      localStorage.setItem('status', myName);
    }
  }

  render() {
    return (
      <BtnBox>
        <MyBtn onClick={this.chooseFun} data-name="sign" style={{ color: this.state.Scolor }}>註冊</MyBtn>
        <MyBtn onClick={this.chooseFun} data-name="log" style={{ color: this.state.Lcolor }}>登入</MyBtn>
      </BtnBox>
    );
  }
}

export default SignAndLog;

And when I click both my MyBtn , it always not work , and in F12 console area shows that:

app.js:3880 Warning: setState(...): Can only update a mounted or
  mounting component. This usually means you called setState() on an
  unmounted component. This is a no-op.

Please check the code for the SignAndLog component.
Can any body tell me where I should fix?
PS:due to my ESlint , I cannot console.log() , so I use localStorage.setItem to be my console.log()

A: follow this article! and you will get better understanding of how to setState.
I prefer to use the fat arrow function.
try this out!

import React, { Component } from 'react';
import styled from 'styled-components';

const BtnBox = styled.ul`
display:flex;
width:50vw;
align-items:center;
justify-content:flex-start;
font-weight:900;
font-size:5vw;
letter-spacing:-0.5vw;
`;
const MyBtn = styled.li`
width:30%;
font-size:5vw;
display:flex;
align-items:center;
justify-content:flex-start;
cursor:pointer;
`;

class SignAndLog extends Component {
  constructor(props) {
    super(props);
    this.state = { Scolor: 'black', Lcolor: 'grey' };
    localStorage.setItem('fuck', this.state.Scolor);
  }

  chooseFun =(e)=> {
    const myName = e.target.dataset.name;
    if (myName === 'sign') {
      this.setState({
        Scolor: 'black',
        Lcolor: 'grey'
      });
      localStorage.setItem('status', myName);
    } else {
      this.setState({
        Scolor: 'grey',
        Lcolor: 'black'
      });
      localStorage.setItem('status', myName);
    }
  }

  render() {
    return (
      <BtnBox>
        <MyBtn onClick={(e)=>this.chooseFun(e)} data-name="sign" style={{ color: this.state.Scolor }}>註冊</MyBtn>
        <MyBtn onClick={(e)=>this.chooseFun(e)} data-name="log" style={{ color: this.state.Lcolor }}>登入</MyBtn>
      </BtnBox>
    );
  }
}

export default SignAndLog;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


Q: Behaviour of "containsAll" with duplicates The official documentation (archive) of containsAll only says "Returns true if this list contains all of the elements of the specified collection.". However, I just tested this:
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(1);
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(1);
list2.add(2);
System.out.println(list1.containsAll(list2));

The result is true, even though list1 does not contain a second 2.
So what is the official, completely defined behaviour of containsAll? Does it act as if all duplicates were removed from both lists? I remember reading somewhere that it can cause problems with duplicates, but I don't know the exact case.

A: The List.containsAll method behaves just as documented: it returns true if all the elements of the given collection belong to this collection, false otherwise. The docs say nothing about the order or cardinality of the elements.
The documentation for containsAll does not explicitly say how it determines whether an element belongs to the Collection. But the documentation for contains (which is implicitly specifying the semantics of "contains") does: it uses equals. Again, no mention of cardinality.
The containsAll method is declared in the Collection interface and re-declared in the List and Set interfaces, but it's first implemented in the Collection hierarchy by the AbstractCollection class, as follows:
public boolean containsAll(Collection<?> c) {
    for (Object e : c)
        if (!contains(e))
            return false;
    return true;
}

As far as I know, this implementation is inherited by most common classes that implement the Collection interface in the Java Collections framework, except for the CopyOnWriteArrayList class and other specialized classes, such as empty lists and checked and immutable wrappers, etc.
So, if you look at the code, you'll see that it fulfils the docs you quoted:

Returns true if this list contains all of the elements of the specified collection.

In the docs of the AbstractList.containsAll method, there's also an @implSpec tag, which says the following:

@implSpec
This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false.

With regard to possible optimizations, they're all relayed to the different implementations of the contains method, which is also implemented by AbstractCollection in a naive, brute-force-like way. However, contains is overriden in i.e. HashSet to take advantage of hashing, and also in ArrayList, where it uses indexes, etc.

A: You can iterate over one list and remove elements by value from another, then check if another list size == 0. If it is, then that means all second list elements were present in first list at least as many times as in the second list.
 public boolean containsAll(List<Character> source, List<Character> target) {

    for (Character character : source) {
        target.remove(character);
        if (target.isEmpty()) {
            return true;
        }
    }

    return target.size() == 0;
}

HashMap will be more efficient if lists are huge
 public static boolean containsAll(List<Character> source, List<Character> target) {
    Map<Character, Long> targetMap = target.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    for (Character character : source) {
        Long count = targetMap.get(character);
        if (count != null) {
            if (count > 1) {
                targetMap.put(character, --count);
            } else {
                targetMap.remove(character);
            }
        }
    }
    return targetMap.isEmpty();
}