text:
Q: can't connect to *.onion sites with python () I'm trying to access *.onion sites using python. Didn't success yet, though.
I've read a lot of stackoverflow questions&answers, tried a lot of different ways of resolving this problem: I tried using Python 2.7 and Python 3.5, tried using urllib, urllib2, requests (then I found out requests doesn't work with socks), pysocks, etc, but nothing seems to work.
Right now I'm at the point where I only get the following Error:
> <urlopen error [Errno 11001] getaddrinfo failed>

No, I don't have a firewall, and yes, I have a good internet connection, and yes, the site does exist.
I think the problem is that it's an *.onion link.
This is what I'm doing right now:
import socks
import socket
import urllib
import urllib.request

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
r = urllib.request.urlopen("http://xmh57jrzrnw6insl.onion")
r.read()

and this is what I'm getting:
---------------------------------------------------------------------------
gaierror                                  Traceback (most recent call last)
C:\Users\yella\Anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)
   1239             try:
-> 1240                 h.request(req.get_method(), req.selector, req.data, headers)
   1241             except OSError as err: # timeout error

C:\Users\yella\Anaconda3\lib\http\client.py in request(self, method, url, body, headers)
   1082         """Send a complete request to the server."""
-> 1083         self._send_request(method, url, body, headers)
   1084

C:\Users\yella\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers)
   1127             body = body.encode('iso-8859-1')
-> 1128         self.endheaders(body)
   1129

C:\Users\yella\Anaconda3\lib\http\client.py in endheaders(self, message_body)
   1078             raise CannotSendHeader()
-> 1079         self._send_output(message_body)
   1080

C:\Users\yella\Anaconda3\lib\http\client.py in _send_output(self, message_body)
    910
--> 911         self.send(msg)
    912         if message_body is not None:

C:\Users\yella\Anaconda3\lib\http\client.py in send(self, data)
    853             if self.auto_open:
--> 854                 self.connect()
    855             else:

C:\Users\yella\Anaconda3\lib\http\client.py in connect(self)
    825         self.sock = self._create_connection(
--> 826             (self.host,self.port), self.timeout, self.source_address)
    827         self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

C:\Users\yella\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)
    692     err = None
--> 693     for res in getaddrinfo(host, port, 0, SOCK_STREAM):
    694         af, socktype, proto, canonname, sa = res

C:\Users\yella\Anaconda3\lib\socket.py in getaddrinfo(host, port, family, type, proto, flags)
    731     addrlist = []
--> 732     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    733         af, socktype, proto, canonname, sa = res

gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
<ipython-input-72-1e30353c3485> in <module>()
----> 1 r = urllib.request.urlopen("http://xmh57jrzrnw6insl.onion:80")
      2 r.read()

C:\Users\yella\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    160     else:
    161         opener = _opener
--> 162     return opener.open(url, data, timeout)
    163
    164 def install_opener(opener):

C:\Users\yella\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    463             req = meth(req)
    464
--> 465         response = self._open(req, data)
    466
    467         # post-process response

C:\Users\yella\Anaconda3\lib\urllib\request.py in _open(self, req, data)
    481         protocol = req.type
    482         result = self._call_chain(self.handle_open, protocol, protocol +
--> 483                                   '_open', req)
    484         if result:
    485             return result

C:\Users\yella\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
    441         for handler in handlers:
    442             func = getattr(handler, meth_name)
--> 443             result = func(*args)
    444             if result is not None:
    445                 return result

C:\Users\yella\Anaconda3\lib\urllib\request.py in http_open(self, req)
   1266
   1267     def http_open(self, req):
-> 1268         return self.do_open(http.client.HTTPConnection, req)
   1269
   1270     http_request = AbstractHTTPHandler.do_request_

C:\Users\yella\Anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)
   1240                 h.request(req.get_method(), req.selector, req.data, headers)
   1241             except OSError as err: # timeout error
-> 1242                 raise URLError(err)
   1243             r = h.getresponse()
   1244         except:

URLError: <urlopen error [Errno 11001] getaddrinfo failed>

I'm very new to all this stuff, so I might be missing some really simple parts. But I'll be grateful for any help.
ps: when trying to access not an *.onion site, I get the following:
[WinError 10061] No connection could be made because the target machine actively refused it

A: I'm on Linux but the code you supplied didn't work for me.  From the looks of it the DNS resolution is not happening over Tor (based on error 11001 WSAHOST_NOT_FOUND).  I'm a little suspicious that it's actually using Tor because of the 10061 (connection refused) error too.
In any case, I was able to get it working with this:
import urllib2
import socks
from sockshandler import SocksiPyHandler

opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050, True))
print opener.open("http://xmh57jrzrnw6insl.onion").read()

PySocks says in their docs:

Note that monkeypatching may not work for all standard modules or for
  all third party modules, and generally isn't recommended.
  Monkeypatching is usually an anti-pattern in Python.

The monkey patching is the use of socket.socket = socks.socksocket.
If possible, use Requests with the socks5h:// protocol handlers for your proxies:
import requests
import json

proxies = {
    'http': 'socks5h://127.0.0.1:9050',
    'https': 'socks5h://127.0.0.1:9050'
}

data = requests.get("http://xmh57jrzrnw6insl.onion",proxies=proxies).text

print(data)


text:
Q: Python error in line passing parameter to command what does this error means?
TypeError: cannot concatenate 'str' and 'set' objects.
def main():
    print 'ffffffffffffffffffffffffff'
    try:
        print getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        opts, args = getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        print opts, args,'print'
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)

baseUrl = 'http://10.176.14.26:8080/client/api'
cmd = {'command : listTemplates', 'templatefilter : executable'}
api = 'Qo9Qwfatwz9ARB328Btn9PftzL2Cf5LOWd8OFyJmiM513tpTIm-zKxJoWkWqf353Df397xcLdKXGk8_JO8nM3Q'
secret = '-kgkBuBUrGFeIC4gUvngSK_3Ypmi7fuF8XdVXIusnyyiEP2YUcG3FnPUGJGy3rp3Bw5ZNnqgS-9tIfyV1QnK1g'

redpajama_set_name: RedPajamaStackExchange


text:
Q: PySerial permission denied when invoked by webserver I have a django application which connects to several serial devices on the server.
This application is running on Ubuntu 10.04.  The user "chero" is the owner of the webserver processes.  chero is a member of the dialout group.
Everything works as expected using the development server, or a python shell (running as user chero).
The webserver is cherokee, with uwsgi (also running as chero).  When the webserver tries to open a serial port I get: [error 13] permission denied.
I have verified that the webserver is indeed running as user chero by inserting this in the line before the serial port would be opened:
raise ValueError('user: ' + pwd.getpwuid( os.getuid() ).pw_name)
The webserver was able to open the port after I set permissions on /dev/ttyS* to 666, but that is not an ideal solution.
Is there some reason uwsgi or cherokee would prevent chero from being recognized as a member of the dialout group?


text:
Q: How to use localStroge in word Add-in I am developing a add-in using word javascript Api and i need to store some information locally so want to use the Local Storage but tried to strore the values it shows me below error:
Code: localStorage.setItem('favoriteflavor','vanilla');
Error: An internal error occurred in the Microsoft Internet extensions.


text:
Q: Add text to existing PDF using Python and PDFTron I'm trying to add text dynamically to an existing PDF with a font available in the system using pdfnetpython3 9.1.0 from the PDFTron SDK. I'm using the following Python code:
texts = ["test1", "test2"]
ewriter = ElementWriter()
ebuilder = ElementBuilder()
# not shown here: create PDFDoc object from PDF in disk
page = pdf_doc.GetPage(3)
ewriter.Begin(page)
element = ebuilder.CreateTextBegin(Font.Create(pdf_doc.GetSDFDoc(), "Inter", ""), 11)
ewriter.WriteElement(element)
for i, text in enumerate(texts):
    element = ebuilder.CreateTextRun(text)
    element.SetTextMatrix(1, 0, 0, 1, 0, 20*i)
    ewriter.WriteElement(element)
    i += 1
element = ebuilder.CreateTextEnd()
ewriter.WriteElement(element)
ewriter.End()  # save changes to the current page

However, the text shows up in Japanese characters in the saved PDF. Am I loading the font incorrectly by passing its name and an empty string as char_set ? I've followed the sample that loads the Helvetica font in https://www.pdftron.com/documentation/samples/py/UnicodeWriteTest .
I have tried to call PDFNet.AddFontSubst() with the Inter font file path as parameter before rendering the strings, but I got the same result.
I'm only able to load the font correctly if I provide a Font.StandardType1Font (e.g. Font.e_times_roman) instead of a font name to Font.Create() (this links to the .NET sdk, but .NET and Python SDK uses the same classes and methods names).


text:
Q: Walking positive square numbers and closing or opening doors Peter moves in a hallway with $N+1$ doors consecutively numbered from $0$ through $N$. All doors are initially closed. Peter starts in front of door $0$, and repeatedly performs the following steps:
First, he walks a positive square number of doors away from his position.
Then he walks another, larger square number of doors away from his new position.
He toggles the door he faces (opens it if closed, closes it if open).
And finally returns to door $0$.
We call an action any sequence of those steps. Peter never performs the exact same action twice, and makes sure to perform all possible actions that don't bring him past the last door.
Let $F(N)$ be the number of doors that are open after Peter has performed all possible actions. You are given that $F(5) = 1$, $F(100) = 27$, $F(1000) = 233$ and $F(10^6) = 112168$.
Find $F(10^{12})$.
I was presented this question and the only idea of solution discussed was programming, so I wanted to know if there is some other way to solve it.

A: most recent I've noticed on MSE Meta:
http://meta.math.stackexchange.com/questions/21383/project-euler-again
September 2015
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Magazine article by James Sommers :
http://www.theatlantic.com/technology/archive/2011/06/how-i-failed-failed-and-finally-succeeded-at-learning-how-to-code/239855/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
discussion on MO:
http://tea.mathoverflow.net/discussion/1226/project-euler-questions/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
discussion at Project Euler's own forum:
http://projecteuler.chat/viewtopic.php?f=5&t=2707
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
email letter from "hk", Novemeber 2011
Hi Will,
let me introduce myself to you. I'm hk at Project Euler.
The philosophy of Colin Hughes, the founder of Project Euler was the philosophy of inductive self learning.
Just Googling on the subject will reveal you quite a lot about this educational subject.
(The top item on my version of Google was this one: http://mate.calpoly.edu/media/files/Review_inductive_learning.pdf)
My personal view on this matter is: if you lack the attitude, when faced with a new problem, to break it down into smaller parts or to
investigate smaller cases you will never never become a successful scientist or academically schooled person.
The problem in question that raised attention to Project Euler is particularly fit for scaling down and discover some useful facts.
I think we are facing a cultural clash here:
The rationalisations shown to us by e.g. rbharvs are from the level: I have to be told how to do things.
I'm afraid that has to do with a failing educational system that shows students rules and formulas without giving them enough room to
experiment before formalising knowledge.
To do some  work that is new to you, be it research mathematics or toying around with problems for which all underlying maths is known, you will
need to doodle around with the problem or parts of it. How else can one do essentially new work?
Top down teaching that doesn't help their students to develop this kind of ability produces people that start shouting: tell me how to do it
and I will try to copy it.  Some people that are badly educated in the way I sketched are just using Project Euler  to develop those skills.
I hope that they will benefit from that in their professional life. Some have even indicated that it was Project Euler that ultimately made them decide to choose mathematics for their academic study despite the poor level of the mathematical education in their country.
The people that posed the questions at Math Overflow, in my opinion have shown to lack the mental attitude to do the necessary doodling around. (Take for instance the fact that one of them copied the radius 10^10. Some experimenting would have shown them that ______).
Well, you can consider this private communication as lunch talk if it doesn't interest you, but I hope I gave you some information about the philosophy of Project Euler. Feel free to paraphrase it to your wish when communicating with your colleagues at Math Overflow.
If you like to know more feel free to email me.
Thanks again for the effort you have invested in the case.
Regards
hk
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


text:
Q: How to normalize mortality in determining lethal concentration of toxins or pesticides? A certain set of pesticide concentrations is selected to dose the animals to determine its acute toxicity. Technically, with increasing concentrations, the mortality should increase, but that does not occur. In some cases, in higher dose category the mortality will be less than that of the preceding or earlier dose category. How to overcome this problem? If there is any way around like through mathematical formula or any paper that sheds light on this aspect please enlighten me.
The data is as follows: five treatments and seven fish per treatment

*

*First treatment: none dead

*Second treatment: two out of seven dead

*Third treatment: one out of seven dead

*Fourth treatment: all dead

*Fifth treatment: All dead

A: tl;dr A standard probit regression analysis should be fine. The only thing "wrong" with your data is that the sample sizes are a bit low, so the outcomes are highly variable.
This graph shows the probit regression along with the binomial confidence intervals for the individual points (code included below since it's a little bit complicated):

(This analysis assumes the doses are equally spaced, or equally spaced on a log scale, or in any case should be treated as equally spaced.)
You can see that the unusual result of 1/7 (14%) dead for dose 3, although it surprises you, is not even particularly inconsistent with the probit curve; the 95% confidence interval for a binomial probability with 1/7 deaths is (0.004, 0.58), while the predicted value from the probit is very close to 0.5. (It would unsurprising even if some of the individual binomial CIs didn't overlap with the curve, because we are making multiple comparisons.)
If the sample sizes were much larger, e.g. if you had 1000/7000 deaths instead of 1/7, so that the expected level of precision was much higher, then I would worry that something had gone wrong with the experiment.
The probit model can be fitted with base R (glm(prop_dead ~ dose, data = ..., weights = n_trials, family = binomial(link="probit"))) but you might find the drc package useful (or the dose.p function from the built-in MASS package, or this link).
dd <- data.frame(dead = c(0, 2, 1, 7, 7),
                 n = 7,
                 dose = 1:5)
dd$lwr <- dd$upr <- NA
for (i in seq(nrow(dd))) {
  bb <- binom.test(dd$dead[i], dd$n[i])
  dd$lwr[i] <- bb$conf.int[1]
  dd$upr[i] <- bb$conf.int[2]
}

library(ggplot2); theme_set(theme_bw())
(ggplot(dd)
  + aes(x = dose, y = dead/n)
  + geom_pointrange(aes(ymin = lwr, ymax = upr))
  + geom_smooth(method = "glm",
                method.args = list(family = binomial(link = "probit")),
                aes(weight = n))
)


text:
Q: django form returns null field error when submitting I have a model in my django project :
class Employee(models.Model):
    user = models.OneToOneField(User, related_name="EmployeeUser")
    workType = models.CharField(max_length=1)
    salary = models.IntegerField()
    Branch = models.ForeignKey(Branch)
    is_admin = models.BooleanField(default=False)

and in forms.py
class EmpForm(ModelForm):
    username = fields_for_model(User)['username']
    email = fields_for_model(User)['email']
    password = fields_for_model(User)['password']
    first_name = fields_for_model(User)['first_name']
    last_name = fields_for_model(User)['last_name']
    branch = fields_for_model(Employee)['Branch']
    is_admin = fields_for_model(Employee)['is_admin']
    salary = fields_for_model(Employee)['salary']

    def __init__(self, *args, **kwargs):
        super(EmpForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Employee
        fields = []

    def save(self, commit=True):
        username = self.cleaned_data.get('username', None)
        email = self.cleaned_data.get('email', None)
        password = self.cleaned_data.get('password', None)
        first_name = self.cleaned_data.get('first_name', None)
        last_name = self.cleaned_data.get('last_name', None)
        salary = self.cleaned_data.get('salary', 0)
        branch = self.cleaned_data.get('branch', 0)
        tmp_user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name,
                                        last_name=last_name)
        return Employee.objects.create(user=tmp_user, salary=0,     Branch=branch, workType='a', is_admin=False)

and in my admin.py:
class EmpAdmin(admin.ModelAdmin):
    ....
    form=EmpFrom
    def save_model(self, request, obj, form, change):
        if form.is_valid():
            obj.save()

The problem is that in django admin form when I want to enter a new Employee It throws an form exception that the salary field cannot be null but I have gave value to it.
[SOLEVED]
I just changed the :
class Meta:
        model = Employee
        fields = []

to
class Meta:
        model = Employee
        fields = ['first_name', 'last_name', 'username', 'password', 'branch', 'salary', 'is_admin']

and it worked


text:
Q: Jenkins - Disable sandbox for Jenkinsfiles from SCM Following script works if I run it without the sandbox. But if with Sandbox it fails for me: org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field groovy.util.slurpersupport.NoChildren value
I'm fine with deactivating the sandbox, cause I trust my own code. My problem is, that I can't run it when retrieving the pipeline code as a jenkins file from a SCM-Server. Pulling files from a Server permanently enables the Sandbox?
What of these actions, which I perform in this code, does trigger the sandbox mechanism? How can I figure that out?

*

*How can I run my code base which pulls it's code from a SCM without a sandbox?

*Or, how can I allow those exceptions?

*Is there a other way to call those methods like script.myDangerousMethod?

reproduce:
jenkins -> New Item -> "Pipeline"
copy&paste:
stage('only'){
    strXML = '<devices><property name="GivenName" value="123"/></devices>'
    def list2 = new XmlSlurper().parseText(strXML)
    println list2.device[0].@value.text()
}

[X]/[__]  Sandbox


text:
Q: What's the size limit per file on VSTS hosted git? Wondering what the size limit is per file in a VSTS hosted git repo, before you have to switch to use LFS instead.
Thanks

A: Microsoft limit activity by the resources consumed rather than a straight filesize limit and, since large files in a repo use more resources to process than in LFS, the limit is lower. See https://learn.microsoft.com/en-us/vsts/collaborate/rate-limits


text:
Q: Chi-square test for Homogeneity problem (cell count less than 2) My table of chi-square test for homogeneity has 3x5 cells, 3 samples to a likert scale item. Most cells in the table have a frequency count of less than two, so it is recommended to discard the column of which contains a cell with frequency of less than two. How will this affect my hypothesis if I discard the entire column just because a cell has a value of less than 2 or 0?

A: 1) Likert scale items are ordered. Chi-square ignores the information in that ordering. You're tossing away a lot of your power against interesting alternatives.
You would probably benefit from investigating some of the potential alternatives to straight homogeneity when you have ordered categories.
2) the usual requirement (which is usually too stringent in any case) isn't for a minimum observed count, it's for a minimum expected count
3) don't discard your valuable data, you have so little of it:
a) (not great, but better): you can combine it with an adjacent category (another small one if possible)
b) even better still, you can simulate from the distribution of the chi-square with the same margins, and with a large enough simulation, get accurate p-values. This is available right in the regular chisq.test command in R, for example
(or you could do an 'exact' test, whether based off the chi-square statistic or the fisher test. )

A: Use fisher's exact test instead which gives a more accurate p value than the chi squared for low sample populations hyper-geometric distributions (finite distribution parameters).
This link below tell of HYPGEOMDIST which is a pretty powerful excel function that should get you started.
http://www.real-statistics.com/binomial-and-related-distributions/hypergeometric-distribution/


text:
Q: Samba 3.6.12 and NIS We were able to use Samba and NIS on Samba 3.0.8 on Solaris 10 U5. When we update system to Solaris 10 U11, samba version became 3.6.12. And we are unable to authenticate like old style.
I did not include some parameters on below(create directory mask,etc...)
Old smb.conf
    [global]
    workgroup = WORKGROUPNAME
    server string =  Samba Server
    security = SERVER
    password server = dc6n, dc7n
    username map = /etc/sfw/username.map
    local master = No
    dns proxy = No
    wins server = dc6n, dc7n
    kernel oplocks = No
    host msdfs = No
    map archive = No
    oplocks = No
    level2 oplocks = No

old nsswitch.conf
    passwd files nis
    hosts  files nis

We try to set same configuration to Samba 3.6.12, but it did not work. So I decided to  use security = ADS with Kerberos. This is worked but the way we did not want. Because, only windows domain users were able to login and NIS users not.
New /etc/smb.conf
    workgroup = WORKGROUPNAME
    realm = domain.com
    security = ADS
    password server = dc6n.domain.com
    utmp = Yes
    idmap config *:backend = tdb
    idmap config *:range = 5000-9999
    idmap config NETADM:backend = tdb
    idmap config NETADM:range = 10000-90000
    idmap uid = 100000-500000
    idmap gid = 100000-500000
    template homedir = /home/%U
    template shell = /bin/tcsh
    winbind cache time = 1800
    winbind enum users = No
    winbind enum groups = No
    winbind use default domain = Yes
    winbind separator = /
    create krb5 conf = No
    local master = yes
    domain login = yes
    domain master = yes
    preferred master = yes

New /etc/nsswitch.conf
    passwd files winbind  nis
    hosts  files winbind  nis

New /etc/krb5.conf
    [libdefaults]
        domain.com = domain.com
        dns_lookup_kdc = true

    [realms]
        symantec.local = {
            kdc = dc6n.domain.com
            admin_server = dc6n.domain.com
        }

    [domain_realm]
    .domain.com = domain.com

I am able to get users info from AD and NIS with wbinfo and genent commands.
How can we authenticate like old style again?

A: Make sure you have an entry for winbind sessions in your /etc/pam.d/system-auth-ac file.


text:
Q: How to get list width by width all inside elements with jQuery Have this problem: i need to get list width by all of inside elements. So, i try to get each elements width and connect them in one peace. But now i have only one element width... Can u help me?
var list_width = [];
$('#js_films_block_top li').each(function() {
    list_width.push($(this).width());
});
console.log(list_width);

Thx for help.

A: Ok, i have good solution for this:
$('#js_films_block_top').each(function(){
    var t = $(this),
        tW = 0;
    $('li', t).each(function(){
        tW += $(this).outerWidth(true) + 5;
    });
    t.css('width', tW + t.outerWidth(true) - t.width());
});

thx, anyway.


text:
Q: Vanilla hello world app using web components I'm trying to build a simple web component without any external dependencies. Just two html files, one index.html and one webcomponent.html.
I have some personal html projects where I'd like to separate out the global html namespace into smaller files. I do not want ot use any external library like polymer for this. Neither I want to use any build system or webserver.
All the examples I found online either need an external build system or a library. Also they don't tend to work without a webserver. For instance, webcomponents/hello-world claims to use vanilla-js. But in fact, it does not as it depends on Bower.
Just two html files which work in my local edit-save-refresh development cycle. Is this actually possible? If so, how? If not, what's the closest compromise possible?

A: Here is a minimal Custom Element example with 2 files:
1. Create your custom elemnt in a separate file, for example hello-world.js:
class HelloWorld extends HTMLElement {
    connectedCallback () {
        this.innerHTML = 'hello, world!'
    }
}
customElements.define( 'hello-world', HelloWorld )

2. Import and use your custom element in the main, index.html file:
<html>
<head>
    <script src='hello-world.js'></script>
<body>
    <hello-world></hello-world>

A: Code:

class HelloWorld extends HTMLElement {
    constructor() {
      super();
      // Attach a shadow root to the element.
      let shadowRoot = this.attachShadow({mode: 'open'});
      shadowRoot.innerHTML = `<p>hello world</p>`;
    }
  }
  customElements.define('hello-world', HelloWorld);
  <hello-world></hello-world>


text:
Q: ScriptResource.axd and .Net 4 We have just converted our website to run on .NET 4 and upgraded our server (Web Server 2008 SP2 IIS7.0) to run the .NET 4 framework. Our site now displays the following problem on 50% of all computers that try to access it whereas the other 50% work perfectly. All worked fine under .NET 3.5
Sys.WebForms.PageRequestManagerServerErrorException: The requested name is valid, but no data of the requested type was found. ScriptResource.axd Code:0 Line:5 Char:89043

Our web.config has the following defined:
<system.webServer>
  <validation validateIntegratedModeConfiguration="false" />
  <directoryBrowse enabled="true" />
  <modules>
   <remove name="ScriptModule"/>
   <add name="ASPxHttpHandlerModule" type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.1, Version=10.1.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
   <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </modules>
  <handlers>
   <remove name="WebServiceHandlerFactory-Integrated"/>
   <remove name="ScriptHandlerFactory"/>
   <remove name="ScriptHandlerFactoryAppServices"/>
   <remove name="ScriptResource"/>
   <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </handlers>
 </system.webServer>

The site runs with an Application Pool defined as:
.NET Framework Version: v4.0
Managed Pipeline Mode: Integrated

We switched the site to download the Ajax scripts from  the MS Content delivery Network (ScriptManager EnableCdn="True") and still had  the same problem except this time we get the problem occurring in:
MicrosoftAkaxWebForms.debug.js Line: 868 Char:13

Have removed all our own scripts and the Ajax Control Toolkit to no avail. What is mystifying is that it works ok on 50% of machines and not on the other 50%. There is no commonality between the works/not works. Different o/s different browser mixes. e.g. works fine on one machine Win 7 / IE8 fails on one machine same o/s and browser...works fine on one machine XP Firefox3 fails on another same config.
Any help greatly appreciated (getting desperate!!)
Lastest update:
We reverted the site to .Net 3.5 without changing any code on the site and all works perfectly. Guess we will stick at 3.5 for the foreseeable future!!

A: Dont give up just yet, had a few headaches when I upgraded our site to 4.0 but nothing a few hours of hair pulling didnt resolve!
Looking at your web.config...
       <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

   <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

These modules are still referencing the old 3.5 libraries. Update your references to point at the new 4.0 versions of these libaries.
Please also look into the changes which have been made in 4.0 to minimise web.config settings. One way to get started would be to create a new 4.0 website work out what you need to add to the web.config to get up and running.
I'm using the AJAX control toolkit on our 4.0 sites and I dont have any of the handlers you have registered and I dont belive you need any of them (apart from maybe
 the DevExpress one).
Ta
Steve


text:
Q: How do i get rspec to read the dependencies in my gemspec? When I run 'rspec' or 'bundle exec rspec' it doesn't let me use the dependencies in my .gemspec file.  Do I have to repeat myself and break the DRY principle and display my gems in Gemfile and .gemspec??  (ps. I am doing this for my models files as a rails engine)
Gemfile:
gemspec

.gemspec:
  s.add_dependency "rails", "~> 3.2.13"
  s.add_dependency "mongoid"
  s.add_dependency "mongoid_commentable"

Example:
"bundle exec rspec"
Displays errors:
uninitialized constant Mongoid::Commentable
uninitialized constant Comment::Mongoid_Commentable
uninitialized constant Mongoid::Commentable

A: Gem dependencies are not autoloaded as opposed to using Bundler/Gemfile. Thus, you'll have to require the gems that you depend upon.


text:
Q: Is it possible for dropdown filter of jquery tablesorter to distinguish multiple values within the same cell? https://mottie.github.io/tablesorter/docs/example-widget-filter-custom.html gives a few examples - First Name column filters by cell content being the filter options, while City and Total have predefined options as filter values.
Sometimes, we need to use the cell contents as filter options because we don't know all the possibilities to use the predefined options, but these cell contents might contain multiple values. Imagine a column Category which lists one or more categories the row is associated to. They could be separated by a comma, new line, br tag, etc. How can we add a dropdown filter at the top listing each separate category without having to list them all? If we use the automatic dropdown, we get the cell contents as filter options: e.g. "Loan, Insurance" will be the filter option rather than two options - "Loan" and "Insurance". If these are separated by break tags, things start to look even uglier.
Thanks!

A: It sounds like you can use the filter_selectSource option to add options to the select in that column.
You can use the built-in getOptions function to obtain the current column values. If they are comma-separated, then you can join the array using commas and re-split the result (demo)
$(function() {
  $('table').tablesorter({
    theme: 'blue',
    widgets: ['zebra', 'filter'],
    widgetOptions: {
      filter_selectSource: function(table, column, onlyAvail) {
        var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
        return array.join(',').split(/\s*,\s*/);
      }
    }
  });
});

Edit: Also make sure to add a "filter-match" class ("filter-select" too) to only match the selected option. It defaults to exact matches otherwise.

Update: If the data is separated using
's then you'll need to add a custom parser to replace the
 with a comma, then you can use the same code (demo)
The header will require two more classes to set the parser and tell the filter widget to only use parsed data:
Animals

JS
$(function() {

  $.tablesorter.addParser({
    id: 'html',
    is: function() {
      return false;
    },
    format: function(str, table, cell) {
      var c = table.config,
        html = cell.innerHTML;
      if (html) {
        // replace
 with a comma
        html = html.replace(/\s*
\s*/g, ',')
        html = $.trim(c.ignoreCase ? html.toLocaleLowerCase() : html);
        html = c.sortLocaleCompare ? $.tablesorter.replaceAccents(html) : html;
      }
      return html;
    },
    type: 'text'
  });

  $('table').tablesorter({
    theme: 'blue',
    widgets: ['zebra', 'filter'],
    widgetOptions: {
      filter_selectSource: function(table, column, onlyAvail) {
        var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
        return array.join(',').split(/\s*,\s*/);
      }
    }
  });
});


text:
Q: Randomizar divs jQuery Fala galera!
Tenho o seguinte código. O que estou tentando é que apareça as 6 divs aleatoriamente. Já tentei de diversar formas mas sem resultado.
Se alguém puder ajudar agradeço.
PS: Não posso colocar as divs dentro do HTML, tem que ser via jquery.

var dfl1 = '
teste 1
'
var dfl2 = '
teste 2
'
var dfl3 = '
teste 3
'
var dfl4 = '
teste 4
'
var dfl5 = '
teste 5
'
var dfl6 = '
teste 6
'

var imagesdfl = [dfl1, dfl2, dfl3, dfl4, dfl5, dfl6];
$(imagesdfl[Math.floor(Math.random() * imagesdfl.length)]).appendTo('#load-content-d');

A: Utilizando a lib lodash, bastaria fazer o sort dinâmico com o comando shuffle. Veja abaixo como ficaria:

var dfl1 = $('
teste 1
');
var dfl2 = $('
teste 2
');
var dfl3 = $('
teste 3
');
var dfl4 = $('
teste 4
');
var dfl5 = $('
teste 5
');
var dfl6 = $('
teste 6
');

var arr = [];
arr.push(dfl1, dfl2, dfl3, dfl4, dfl5, dfl6);
arr = _.shuffle(arr);

$("#load-content-d").html(arr);

Com Java Script puro:
Código do sortear retirado daqui.

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var dfl1 = $('
teste 1
');
var dfl2 = $('
teste 2
');
var dfl3 = $('
teste 3
');
var dfl4 = $('
teste 4
');
var dfl5 = $('
teste 5
');
var dfl6 = $('
teste 6
');

var arr = [];
arr.push(dfl1, dfl2, dfl3, dfl4, dfl5, dfl6);
arr = shuffle(arr);

$("#load-content-d").html(arr);


text:
Q: Trouble with generics Why doesn't the following code compile? Is that a compiler bug or a language feature? What is the best workaround?
type A() as this =
    let a = this.GetTypedObject<int>()    // a
    let b = this.GetTypedObject<string>() // b

    member this.GetTypedObject<'T>() =
        Unchecked.defaultof<'T>

Unchecked.defaultof<'T> is used for example only, any function or constructor call could be used instead.
Compiler says that code becomes less generic at line (a) and refuses to compile line (b).
I cannot give exact compiler messages because I have them in Russian :).
Turning method GetTypedObject() into a let binding and removing <'T> ends up with another compiler warning which I don't like either. The only wokaround I found is to move GetTypedObject<'T>() into a base class and to make it public. Thanks in advance...

A: Note that you can simply add a type annotation to fix this:
type A() as this =
    let a = this.GetTypedObject<int>()    // a
    let b = this.GetTypedObject<string>() // b

    member this.GetTypedObject<'T>() : 'T =
                                   //^^^^
        Unchecked.defaultof<'T>

Member signatures get read first, then all the let and member bodies, when it comes to order of type inference.  By putting the return type in the declaration signature, it becomes visible to the lets.

A: Since type inference works top-to-bottom, it encounters GetTypedObject returning int before it even reaches the method definition and discovers it should be generic. (As Brian points out, members are read prior to let bindings...and there's a simpler fix for this.) I get the following nasty error:

A use of the function 'GetTypedObject' does not match a type inferred elsewhere. The inferred type of the function is     Test.A -> Microsoft.FSharp.Core.unit -> 'a.     The type of the function required at this point of use is     Test.A -> Microsoft.FSharp.Core.unit -> 'a     This error may be due to limitations associated with generic recursion within a 'let rec' collection or within a group of classes. Consider giving a full type signature for the targets of recursive calls including type annotations for both argument and return types.

If the usage appears after the method definition, it works.
type A() =
    member this.GetTypedObject<'T>() =
        Unchecked.defaultof<'T>

    member this.Test() =
      let a = this.GetTypedObject<int>()    // a
      let b = this.GetTypedObject<string>() // b
      ()

Here's a workaround:
type A() =
  let getTypedObject() = Unchecked.defaultof<_>
  let a : int = getTypedObject()    // a
  let b : string = getTypedObject() // b

  member this.GetTypedObject<'T>() : 'T = getTypedObject()


text:
Q: How to execute nested Javascript function I am troubleshooting a slider problem at the moment, however, I don't know javascript that well, I have isolated the .js file that is responsible for the slider functioning, there is a destroy function that I would like to fire off, the code looks like this
(function ($) {

$.pixelentity = $.pixelentity || {version: '1.0.0'};

$.pixelentity.peBackgroundSlider = {
    conf: {
        api: false,
        wait: false
    },
    paused: false
};

function PeBackgroundSlider(target, conf) {

    ...

    function destroy() {
        prevColor = currentColor = currentBW = jwindow = jthis = undefined;
        target.data("peBackgroundSlider", null);
        target = undefined;
    }
}

How would I fire off the destroy function in this scenario?

A: You can't as it is right now.
To call it you must "export" it as follows:
function PeBackgroundSlider(target, conf) {

...

function destroy() {
    prevColor = currentColor = currentBW = jwindow = jthis = undefined;
    target.data("peBackgroundSlider", null);
    target = undefined;
  }

  return { "destroy": destroy };
}

From the caller:
var ret = PeBackgroundSlider();

Now you can do:
ret.destroy();

Or, more concise:
  return destroy;

And:
innerDestroy = PeBackgroundSlider();

And finally:
innerDestroy();


text:
Q: Need css for half filled circle with complete border I want css for half filled circle with round border.
enter image description here

A: This is how you can achieve it in CSS.

.wrapper{
  width: 100px; height: 100px;
  border-radius: 50%;
  border: 3px solid black;
  overflow: hidden;
}

.one{
  display: inline-block;
  background-color: green;
  height: 100px; width:50px;
  border-right: 2px solid black;
}

.two{
  display: inline-block;
  background-color: white;
  height: 100px; width:50px;
}

A: <!DOCTYPE html>


text:
Q: Python: Integration of Interpolation I've got some question I cant solve:
#! /usr/bin/env python
import numpy as np
from scipy.interpolate import UnivariateSpline
from scipy.integrate import quad
import pylab as pl

x = ([0,10,20,30,40,50,60,70,...,4550,4560])
y = ([0,0,0,0,0,0,0,3,2,3,2,1,2,1,2,...,8,6,5,7,11,6,7,10,6,5,8,13,6,8,8,3])
s = UnivariateSpline(x, y, k=5, s=5)
xs = np.linspace(0, 4560, 4560)
ys = s(xs)

This is my code for making some Interpolation over some data.
In addition, I plotted this function.
But now I want to integrate it (from zero to infinity).
I tried
results = integrate.quad(ys, 0, 99999)

but it didnt work.
Can you give me some hints (or solutions) please? thanks

A: According to the documentation of quad, you need to give a function as first argument, followed by the lower and upper bounds of the integration range, and some extra arguments for your function (type help(quad) in your shell for more info.
You passed an array as first argument (ys), which is why it doesn't work. You may want to try something like:
results = quad(s, xs[0], xs[-1])

or
results = quad(s, 0, 9999)

A: As Pierre GM said, you have to give a function for quad (I think also you can use np.inf for the upper bound, though here it doesn't matter as the splines go to 0 quickly anyways). However, what you want is:
s.integral(0, np.inf)

Since this is a spline, the UnivariateSpline object already implements an integral that should be better and faster.


text:
Q: Extension Methods With View Bounds Dependent On Extended Object I'm trying to define some extension methods for a class as shown below.  One of the methods needs to accept an argument that is convertible to a path-dependent type that includes the extended object in its path.  Unfortunately, compilation fails at the call-site because the compiler doesn't seem to recognize that the reference to 'outer' in the view boudns definition refers to the same object as 'outer' at the call site.  Is there a way to fix this so that the commented line compiles?
import scala.language.implicitConversions

class Outer {
  class Inner {
  }

  class ConvertsToInner {
  }

  object ConvertsToInner {
    implicit def convert(source : ConvertsToInner) = new Inner()
  }
}

class Code {
  implicit class ExtendsOuter(val outer : Outer) {
    def extensionMethod[T <% outer.Inner](argument : T) { }
  }

  val outer = new Outer()
  val convertsToInner = new outer.ConvertsToInner()

  //does not compile!
  outer.extensionMethod(convertsToInner)
}

A: Replace extension method definition from:
def extensionMethod[T <% outer.Inner](argument : T) { }

to
def extensionMethod[T <% Outer#Inner](argument : T) { }


text:
Q: Preventing MVC annotations to be processed by JUnit I am building JUnit tests for my web application.
Part of these tests work on MVC controllers, so that the tests are annotated with @WebAppConfiguration which is correct. Other tests, however, work on backend resoruces that have nothing to see with the web context (in general, these components are designed in order to be able to run outside of a web context, with a simple Spring context).
Now that I am writing this question I also think that my problem with JUnit will reappear very soon when I will start my application in a non-web context, but better go step by step.
My test class is annotated with
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(initializers = CustomContextInitializer.class,
        locations =
        {
                "classpath:META-INF/context/data-context.xml",
                "classpath:META-INF/context/web-context.xml" //Nothing to do with MVC, don't be fooled by name. No web resource here
        })

However when I start the test I get an error about loading ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at [redacted for brevity]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'navigateController': Injection of autowired dependencies failed; [redacted for brevity]
    at [redacted for brevity]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.servlet.http.HttpServletRequest org.example.controllers.Controller.httpServletRequest; [redacted for brevity]
    at [redacted for brevity]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at [redacted for brevity]

I have redacted all traces for brevity.
The problem is simple: my classpath contains classes annotated with @Controller. At least one of them is bound to the HttpServletContext which is required.
I would like to tell Spring, at least now in JUnit environment, to skip MVC-related annotations when loading the context. I can skip all those beans. Basically I need to separate the data context (that contains only DB related classes and data access objects) from the web context (containing data managers implementing business logic) from the MVC context (containing web controllers and resources).
The XML file contains directive <context:component-scan base-package="org.example" />

A: Tag context:component-scan allows to set inclusion and exclusion filters.
In order to separate the components being scanned by mutliple context files, do the following.
Context A (everything except controllers)
<context:component-scan base-package="org.example">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

Context B (remaining controllers)
<context:component-scan base-package="org.example">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>


text:
Q: How can i change state in React for a single item inside map with onClick button? I'm trying to set state for one item whenever i click the button on it.
i have a map that runs on a list of products, it returns a card with a button in it.
i want to click on the button and then set the variable as it needs to be for the item.
for example:

    const [isShown, setIsShown] = useState(false) // the state. obviously, it's going to show the result on every card inside that map.

        let handleClick = (id: number) => {
            getAmountOfTimesPurchased(id) // a function that returns a number
        }

        return (
    <div>
    {products.map((product: IProduct) => {
                            return <Card key={product.id}>
                                <Card.Body>
                                    <Card.Text>
                                        <Card.Title>
                                            {product.name}
                                        </Card.Title>
                                        ${product.price}
                                        <br />
                                        {product.amount}
                                    </Card.Text>
                                </Card.Body>
                                <Card.Footer>
                                    <Button onClick={() => {
                                        handleClick(product.id)
                             }}>Purchased For:</Button>{isShown && timesPurchased}
                                </Card.Footer>
                            </Card>
                        })}
                        </div>

    )

so, how can I show the result only for the card that I'm clicking on?
thank you so much for your help in advance!

A: Instead of a single isShown state that is a boolean value that all rendered cards are using, store the id of the card that is clicked on and is associated with the fetched data.
Example:
const [isShownId, setIsShownId] = useState(null);

const handleClick = (id: number) => {
  getAmountOfTimesPurchased(id);
  setIsShownId(id);
};

return (
  <div>
    {products.map((product: IProduct) => {
      return (
        <Card key={product.id}>
          ...
          <Card.Footer>
            <Button
              onClick={() => {
                handleClick(product.id);
              }}
            >
              Purchased For:
            </Button>
            {isShownId === product.id && timesPurchased}
          </Card.Footer>
        </Card>
      );
    })}
  </div>
);


text:
Q: mongodb - count improve performance I studied the performance mongodb.  I have a collection of 500 millions documents. I created two indexes:
db.appels.createIndex({OPERATEUR_RECEVEUR:1});
db.appels.createIndex({DUREE_APPEL:1});

count on a field, is fast :
15 seconds :
db.appels.find ( {  "DUREE_APPEL" : { "$gt" : 42 } }).count();

2 seconds :
 db.appels.find({OPERATEUR_RECEVEUR:"MTN"}).count();

But count on two fields with an "and", is slow :
7 minutes  :
db.appels.find ( { $and : [ {  "DUREE_APPEL" : { "$gt" : 42 } }, {OPERATEUR_RECEVEUR:"MTN"} ] } ).count();

(This is the same time without a field index)
Finally, count on two fields with a "or" is impossible :
15 hours and kill query :
db.appels.find ( { $or : [ {  "DUREE_APPEL" : { "$gt" : 42 } }, {OPERATEUR_RECEVEUR:"MTN"} ] } ).count();

I can not use multi index because I have 100 columns. I use 1 node with debian 8, 2 SSD, 80 Go Ram, 12 Cpu, mongodb 2.4. How can I improve speed?

A: I found that it is the "count" is slow, not research.
On the same fields the response time is proportional to the number of result
"DUREE_APPEL" : { "$gt" : 42 } --> 198 757 639 record --> 32 seconds
"DUREE_APPEL" : { "$gt" : 800 } --> 11 479 097 record --> 1.9 seconds
"DUREE_APPEL" : { "$gt" : 5000 } --> 833 961 record --> 0.14 second
The indexes are not the only solution, how to solve this problem?
Is used the sharding (50 million lines with 10 node) could be a solution? : https://docs.mongodb.com/manual/sharding/
Pierre


text:
Q: Why does this script don't work in external js file? When I put this code in HTML file, my slideshow works, but when I put it in an external js file, the slideshow doesn't work. why?
https://imgur.com/a/7qrxQd9
............................................................
full code html: https://pastebin.com/YiZhpYzk
javascript file: https://pastebin.com/11BNhL7G
var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}

    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 1300);
}

A: Try placing the entry point of the link to your js document which includes the function in different places like just before the the  tag and make sure the link to your css is correct.


text:
Q: Custom post type max num pages not working I am using custom post type in Wordpress and can not achieve rendering pagination. My problem is variable pages:
global $wp_query;
$pages = $wp_query->max_num_pages;

Variable pages returns following:  Array ( [0] => ) 1
I am trying to get number. What I am doing wrong?
I am using Advanced custom fields.


text:
Q: 405 method not allowed, Django + ngrok, only on my local machine This is a legacy project that I'm working with other guys in my current job.
and is doing a very strange behavior that I cannot understand.
It's returning 405 http response status, which does not make sense, because this view already accepts POST requests

I would share a couple of snippets, I just detected that happens just in the comment that I would mark.
this is the view file, that actually accepts both methods GET and POST
@csrf_exempt
@load_checkout
@validate_cart
@validate_is_shipping_required
@require_http_methods(["GET", "POST"])
def one_step_view(request, checkout):
    """Display the entire checkout in one step."""

this is the decorator that modifies the response, and returns 405.
def load_checkout(view):
    """Decorate view with checkout session and cart for each request.
    Any views decorated by this will change their signature from
    `func(request)` to `func(request, checkout, cart)`."""
    @wraps(view)
    @get_or_empty_db_cart(Cart.objects.for_display())
    def func(request, cart):
        try:
            session_data = request.session[STORAGE_SESSION_KEY]
        except KeyError:
            session_data = ''
        tracking_code = analytics.get_client_id(request)

        checkout = Checkout.from_storage(
            session_data, cart, request.user, tracking_code)

        response = view(request, checkout, cart)  # in this response it returns 405.
        if checkout.modified:
            request.session[STORAGE_SESSION_KEY] = checkout.for_storage()
        return response

    return func

Any idea or clue when I can start to find out the problem?.
for the record: I didn't code this, this was working a couple of days ago, and its just happening in my local environment, on stage and production, and even the local of others developers are working just fine. I have all the requirements and the dependencies, and are updated.
BTW I'm using ngrok for tunneling

--

A: if your front-end use different HOST && PORT
you need to add CROS  in Django app


text:
Q: getting InflateException when Clicking on Pay Button Payfort PaymentGateway android SDK < Error inflating class com.shamanland.fonticon.FontIconView > I am integrating Payfort Payment gateway android sdk in my app, every thing is working fine till Payment on Last screen using sdk.
When Clicking on PAY button on the XML design provided by Payfort Team then I am getting
{
        if (isInEditMode()) {
            mOldValuesSaver = null;
        } else {
            setTypeface(FontIconTypefaceHolder.getTypeface());
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                mOldValuesSaver = new Runnable() {
                    @Override
                    public void run() {
                        saveOldValues();
                    }
                };
            } else {
                mOldValuesSaver = new Runnable() {
                    @Override
                    public void run() {
                        saveOldValuesJB();
                    }
                };
            }
        }
    }

In above method,the line(setTypeface(FontIconTypefaceHolder.getTypeface());) is throwing the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.payfort.payfort/com.example.payfort.payfort.MainActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class com.shamanland.fonticon.FontIconView

Any Help would be appreciated.
Please find the Logs below

/com.example.payfort.payfort E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.payfort.payfort, PID: 23352
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.payfort.payfort/com.example.payfort.payfort.MainActivity}:
  android.view.InflateException: Binary XML file line #15: Error
  inflating class com.shamanland.fonticon.FontIconView at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
  at android.app.ActivityThread.access$800(ActivityThread.java:151) at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
  at android.os.Handler.dispatchMessage(Handler.java:102) at
  android.os.Looper.loop(Looper.java:135) at
  android.app.ActivityThread.main(ActivityThread.java:5254) at
  java.lang.reflect.Method.invoke(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:372) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused
  by: android.view.InflateException: Binary XML file line #15: Error
  inflating class com.shamanland.fonticon.FontIconView at
  android.view.LayoutInflater.createView(LayoutInflater.java:633) at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
  at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at
  android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:504) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:414) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:365) at
  android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
  at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
  at
  com.example.payfort.payfort.MainActivity.onCreate(MainActivity.java:52)
  at android.app.Activity.performCreate(Activity.java:5990) at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
  at android.app.ActivityThread.access$800(ActivityThread.java:151) at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
  at android.os.Handler.dispatchMessage(Handler.java:102) at
  android.os.Looper.loop(Looper.java:135) at
  android.app.ActivityThread.main(ActivityThread.java:5254) at
  java.lang.reflect.Method.invoke(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:372) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused
  by: java.lang.reflect.InvocationTargetException at
  java.lang.reflect.Constructor.newInstance(Native Method) at
  java.lang.reflect.Constructor.newInstance(Constructor.java:288) at
  android.view.LayoutInflater.createView(LayoutInflater.java:607) at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
  at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at
  android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:504) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:414) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:365) at
  android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
  at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
  at
  com.example.payfort.payfort.MainActivity.onCreate(MainActivity.java:52)
  at android.app.Activity.performCreate(Activity.java:5990) at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
  at android.app.ActivityThread.access$800(ActivityThread.java:151) at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
  at android.os.Handler.dispatchMessage(Handler.java:102) at
  android.os.Looper.loop(Looper.java:135) at
  android.app.ActivityThread.main(ActivityThread.java:5254) at
  java.lang.reflect.Method.invoke(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:372) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused
  by: java.lang.IllegalStateException at
  com.shamanland.fonticon.FontIconTypefaceHolder.getTypeface(FontIconTypefaceHolder.java:13)
  at com.shamanland.fonticon.FontIconView.(FontIconView.java:129)
  at java.lang.reflect.Constructor.newInstance(Native Method) at
  java.lang.reflect.Constructor.newInstance(Constructor.java:288) at
  android.view.LayoutInflater.createView(LayoutInflater.java:607) at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
  at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at
  android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:504) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:414) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:365) at
  android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
  at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
  at
  com.example.payfort.payfort.MainActivity.onCreate(MainActivity.java:52)
  at android.app.Activity.performCreate(Activity.java:5990) at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
  at android.app.ActivityThread.access$800(ActivityThread.java:151) at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
  at android.os.Handler.dispatchMessage(Handler.java:102) at
  android.os.Looper.loop(Looper.java:135) at
  android.app.ActivityThread.main(ActivityThread.java:5254) at
  java.lang.reflect.Method.invoke(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:372) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

A: Just add
FontIconTypefaceHolder.init(getAssets(), "icons.ttf");

before setcontentview


text:
Q: Drop down box auto select I was wondering how one would go about having this code below to have the option from the user's profile to display the correct state. Right now it defaults to the blank line.
<select id="state" name="state" class="input-xlarge form-control">
<option value=""></option>
<?php
$result = $db->select("SELECT * FROM as_states ORDER BY statename ASC");
foreach($result as $country)
{
    echo "<option value=\"";
    echo $country['stateid'];
    echo "\">";
    echo $country['statename'];
    echo "</option>";
}
?>
</select>

Someone told me on here in the past how to do it this way (below), which is the older PHP version and wanted to know how to make it work in the above statement.
<?php
$sql="SELECT * FROM countries ORDER BY countrypicks DESC,countryname ASC";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result))
    {
    $countryid=$row["countryid"];
    $countryname=$row["countryname"];
    $selected = ($countryid == $merchcountry) ? 'selected="selected"' : '';
    $options.="<option value=\"$countryid\" $selected>$countryname</option>";
}
?>
<SELECT NAME="merchcountry">
<option>-------</option>
<? echo $options; ?>
</SELECT>

Thank you.

A: the html should look like
    <option value="id" selected>name</option>

(or selected="selected" if you need to be xhtml compatible )
so something like:
    echo "<option value=\"";
    echo $country['stateid'];
    if ( $country['stateid'] == $user_state ) echo " selected";
    echo "\">";
    echo $country['statename'];
    echo "</option>";

also:
    SELECT * FROM countries ORDER BY countrypicks DESC,countryname ASC

is overkill if you only need stateid and statename.


text:
Q: Spring REST, Kotin and default primitive parameters leads to an error I get an error:

Optional long parameter 'count' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type

when I try to invoke this REST controller.
    @RequestMapping("/api/audio/tracks", produces = arrayOf(APPLICATION_JSON_VALUE))
    interface SomeApi {

        @RequestMapping(method = arrayOf(GET))
        fun list(@RequestParam("count", defaultValue = "10") count: Long): Any
    }

Does not spring look at defaultValue?
How to solve this kind of problem?
!Kotlin defaults do not work either

A: I found solution in my situation:
The reason was because of an interface. When I placed @RequestParam("count", required = false, defaultValue = "10") in the implementation everything start working.


text:
Q: What is the purpose of the "START WITH" part of a SQL sequence? In oracle SQL, a sequence is dfined like so :
CREATE SEQUENCE sup_seq
    MINVALUE 1
    MAXVALUE 999
    START WITH 5
    INCREMENT BY 1
    CACHE 20;

What is the point of having the "START WITH" part ? If we have a minimum value , doesn't that imply that we start with that value? What is useful regarding START WITH ?

A: Normally, it would be pretty unusual to specify both MINVALUE and START WITH when defining a sequence and to have those values be different.  Personally, I don't think that I've ever explicitly specified a MINVALUE since I find START WITH to be more self-explanatory.
One case where two values would be useful would be a sequence that is set to cycle.  For example
CREATE SEQUENCE sup_seq
    MINVALUE 1
    MAXVALUE 999
    START WITH 5
    INCREMENT BY 1
    CACHE 20
    CYCLE;

would start with 5 (the start with), generate values through 999 (the maxvalue), and then restart at 1 (the minvalue).  That's not a particularly common use case but it's entirely possible.


text:
Q: How to find the Full path to a most recent added file using AppleScript? I'm using Automator appleScript to upload new pictures to my Instagram.
The script trigger when new file is added to a folder updates
on adding folder items to myFolder after receiving FileList
    repeat with aFile in FileList
        activate application "Uploader HD for Instagram"
        delay 0.5
        delay 0.5

        tell application "System Events"
            tell process "Uploader HD for Instagram"
                click menu item "Open..." of menu 1 of menu bar item "File" of menu bar 1
            end tell
        end tell

        delay 1

        tell application "System Events"
            keystroke "G" using {command down, shift down}
            delay 0.5
            keystroke myFolder
            delay 1
            delay 1
            keystroke return
            keystroke (ASCII character 31)
            delay 1
            keystroke return
            delay 1
            keystroke tab

        end tell

        tell application "System Events"
            tell process "Uploader HD for Instagram"
                click button "Post" of window "Uploader HD for Instagram"
                delay 1

                tell application "Uploader HD for Instagram"
                    quit
                end tell
            end tell
        end tell

        try

            tell application "Finder"

                delete (every item of folder myFolder whose name ends with ".jpg")

            end tell

        on error

            display dialog ("Error. Couldn't Move the File") buttons {"OK"}

        end try

    end repeat
end adding folder items to

I'm using the var myFolder to search the file using the "Go To the folder"
The var myFolder works but only gives me the path to the folder, and I need the path to the folder + File.ext
Any help will be much appreciated/
Thanks/.

A: If I well understand what you want to so, you want to open with Uploader HD application each file which is just added into a specific folder.
If this is correct, then just use Folder actions. each time new files will be added to the folder, the system will trigger the script, giving as argument only the files just added (and not the file already stored in that folder previously !). for each file added, you must just ask HD uploader to open it.
You must first assign the script bellow to your folder "Update" :
Copy / paste the script bellow into ScriptEditor and save it in your ~library/Scripts/Folder Action Scripts
Right click on your folder (updates") and add this folder action script.
on adding folder items to myFolder after receiving FileList
repeat with aFile in FileList
    tell application "Uploader HD for Instagram" to open aFile
end repeat
end adding folder items to

I can't test with Instagram uploader (I don't have it). It could happen that some applications are not answering to an "open" command. If this is the case you may have to replace the line "tell application...open aFile" by an other method to open it. You can use the variable aFile which contains the complete path to the added file. aFile is an alias type and (aFile as string) is the string which you can use in your goto dialog box.

A: Here is the final working code, what I was missing is POSIX
The var myFilePath defined with set includes the full path to the file
on adding folder items to myFolder after receiving FileList
    try
        repeat with i from 1 to number of items in FileList
            repeat with aFile in FileList
                activate application "Uploader HD for Instagram"
                delay 0.5
                delay 0.5

                tell application "System Events"
                    tell process "Uploader HD for Instagram"
                        click menu item "Open..." of menu 1 of menu bar item "File" of menu bar 1
                    end tell
                end tell

                delay 0.5
                set myFilePath to POSIX path of item i of FileList
                tell application "System Events"
                    keystroke "G" using {command down, shift down}
                    delay 0.5
                    keystroke myFilePath
                    delay 0.5
                    keystroke return
                    delay 0.5
                    keystroke return
                    delay 0.5
                    keystroke tab
                    keystroke "#Instagood #Instagram #Luxury #Babe #Model #Follow @CindyJordanLove"
                end tell

                tell application "System Events"
                    tell process "Uploader HD for Instagram"
                        click button "Post" of window "Uploader HD for Instagram"
                        delay 1

                        tell application "Uploader HD for Instagram"
                            quit
                        end tell
                    end tell
                end tell

                try

                    tell application "Finder"

                        delete (every item of folder myFolder whose name ends with ".jpg")

                    end tell

                on error

                    display dialog ("Error. Couldn't Move the File") buttons {"OK"}

                end try
            end repeat
        end repeat
    end try
end adding folder items to


text:
Q: improvement suggestions for parsing numpy array to single value I wrote a function to aggregate a 2D numpy integer n X m array to a 1 X 1 2D numpy array based a selected method. How can my function be improved to enhance speed/performance?
The methods are:

*

*min: return the lowest value

*max: return maximum value

*median: return most frequently occurring value.

*priority value: return specified priority value if its occurrence in the array exceeds a threshold th.

Additional requirements:

*

*if the values in the input value are all identical, then return that number

*an ignore value can be provided which is masked from the methods, but not the requirement above.

My current implementation:
import numpy as np

def array2val(arr, method, dt, prio=None, th=None, ignore=None):
    """
    Parse a Numpy array to a single output value based on method. Useful for aggregation
    :param arr: 2D numpy array
    :param method: [sum, min, max, median, priority]. priority means to give priority to a value if it occurs >= a threshold
    :param dt: datatype of output array
    :param prio: the value to be prioritized if method == priority
    :param th: occurrence treshold for the priority value. Return median if threshold is not exceeded
    :param ignore: value to ignore in all methods
    :return: 2D numpy array with shape (1,1) with value following above, unless the input array has all same values,
             then return that value. This trumps ignore values
    """

    # All values are the same, return this value
    if arr.std() == 0:
        return np.array([[arr[0, 0]]]).astype(dt)

    # Mask away ignored values if requested
    if ignore is not None:
        arr = np.ma.array(arr, mask=np.where(arr == ignore, True, False))
        v, c = np.unique(arr, return_counts=True)
        vals = v.data[~v.mask]  # Values with ignore value removed
        counts = c[~v.mask]     # Counts with ignore value removed
    else:
        vals, counts = np.unique(arr, return_counts=True)

    if method == 'median':
        out = vals[counts.argmax()]
        return np.array([[out]]).astype(dt)

    elif method == 'priority':
        if counts[np.where(vals == prio)] >= th:  # priority value is in the array and exceeds treshold
            return np.array([[prio]]).astype(dt)
        else:  # priority value does not exceed treshold or is not in the array at all.
            out = vals[counts.argmax()]  # default to most occuring value
            return np.array([[out]]).astype(dt)

    elif method == 'sum':
        return np.array([[arr.sum()]]).astype(dt)

    elif method == 'min':
        return np.array([[arr.min()]]).astype(dt)

    elif method == 'max':
        return np.array([[arr.max()]]).astype(dt)

    else:
        raise Exception('Invalid method for aggregation')


text:
Q: Bash - Proxy server using socat I'm trying to make an http proxy using socat, But I don't know why the request stop suddenly, and there isn't any content in the webpage.
it's just transfer the HTTP request from bowser to the web server. then back with the response.
socat TCP4-LISTEN:666,fork EXEC:"./httproxy.sh"

Redirect port 80 to 666
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 666

httproxy.sh
#!/usr/bin/env bash

function main() {
    REQUEST_HEADERS=()

    read -r line
    line=${line%%$'\r'}
    read -r REQUEST <<< "${line}"

    while IFS= read -r line; do
        line=${line%%$'\r'}
        [ -z "${line}" ] && break
        REQUEST_HEADERS+=( "${line}" )
    done

    printf "${REQUEST}\r\n" &> request.log
    for ((i = 0; i < ${#REQUEST_HEADERS[@]}; i++)); do
        [[ "${REQUEST_HEADERS[$i]}" =~ ^Host:[[:space:]](.*) ]] && IP=${BASH_REMATCH[1]}
        printf "${REQUEST_HEADERS[$i]}\r\n" &>> request.log
    done
    printf "$(cat request.log)\r\n\r\n\r\n" | nc ${IP} 80
}

main

Response :
HTTP/1.1 200 OK....
{HTTP Content}

Immediately after the content:
HTTP/1.1 405....

I've tested it with a lots of 'Http' web pages sometimes the html content arrived
.
Please help me.

A: Do NOT print variables by putting them in printf format string.
Instead of
printf "$var\r\n"

do
printf '%s\r\n' "$var"

As a rule of thumb, enclose the format string with single quotes, which will prevent any inadvertent variable or process substitution.
Of course, the same goes for your printf "$(cat request.log)\r\n\r\n\r\n"
Why?

*

*If var starts with - (minux sign), printf will understand your format string as an option. This will never happen with an HTTP GET request.

*If var contains a % character, which is very common in HTTP requests, printf will interpret it as a format directive.

Besides, you probably add too many empty lines \r\n after the request. One seems enough since you append request.log with lines that already end with \r\n:
{ cat request.log; printf '\r\n'; } | nc ...

(it's possible you don't even have to add any empty line since the request should already end with one)


text:
Q: Inside Dynamics memory management i am student and want to know more about the dynamics memory management. For C++, calling operator new() can allocate a memory block under the Heap(Free Store ). In fact, I have not a full picture how to achieve it.
There are a few questions:
1) What is the mechanism that the OS can allocate a memory block?? As I know, there are some basic memory allocation schemes like first-fit, best-fit and worst-fit. Does OS use one of them to allocate memory dynamically under the heap?
2) For different platform like Android, IOS, Window and so on, are they used different memory allocation algorithms to allocate a memory block?
3) For C++, when i call operator new() or malloc(), Does the memory allocator allocate a memory block randomly in the heap?
Hope anyone can help me.
Thanks

A: malloc is not a system call, it is library (libc) routine which goes through some of its internal structures to give you address of a free piece of memory of the required size. It only does a system call if the process' data segment (i.e. virtual memory it can use) is not "big enough" according to the logic of malloc in question. (On Linux, the system call to enlarge data segment is brk)
Simply said, malloc provides fine-grained memory management, while OS manages coarser, big chunks of memory made available to that process.
Not only different platforms, but also different libraries use different malloc; some programs (e.g. python) use its internal allocator instead as they know its own usage patterns and can increase performance that way.
There is a longthy article about malloc at wikipedia.


text:
Q: Converting UTC timestamp to ISO 8601 in Ruby I have a timestamp that is in UTC
"2010-10-25 23:48:46 UTC"
I need to convert it into ISO 8601
"2010-10-29 06:09Z"
The documentation is confusing as hell - what is the easiest way to do that?

A: Note: you have to convert (parse) a time string into a time object before you can apply the to_time method.
ruby-1.9.2-p180 :016 > "2010-10-25 23:48:46 UTC".to_time.iso8601
NoMethodError: undefined method `to_time' for "2010-10-25 23:48:46 UTC":String
    from (irb):16

Correct procedure:
irb> ut = DateTime.parse("2010-10-25 23:48:46 UTC")

irb> ut.iso8601
 => "2010-10-25T23:48:46+00:00"

A: After much experimenting, I find the Time library's parser to be better than DateTime, although the reasons escape me at the moment.  With that caveat, I always use Time rather than DateTime for this kind of stuff, and the ruby documentation is also difficult to grok as to why this is so,
require 'time'
puts Time.parse("2010-10-25 23:48:46 UTC").iso8601
"2010-10-25T23:48:46Z"

A: I think you're trying to trick us.
The input date to your question is the 25th of October, 2010, whilst the output is the 29th of October, 2010. Well played!
Continuing on this nit-picking thread: your times are also completely different and you're missing the seconds from the output time.
Now for the true answer.
A little factoid first though: the ISO 8601 output in Ruby is similar to the "Combined date and time" output from ISO 8601's Wikipedia page.
You've got a string and so you'll need to convert it into a Time object which you can do with to_time. Then it's simply a matter of calling iso8601 on that object to get the ISO 8601 version:
"2010-10-25 23:48:46 UTC".to_time.iso8601

The to_time method is courtesy of Rails, whilst the iso8601 is courtesy of Ruby's standard library.

A: Adding an answer to this super old question because if you're using Rails, there is no need to convert/parse it in the way the other answers here are telling you to do:

*

*If it's already a timestamp (e.g., a created_at or updated_at attribute), you can directly call the iso8601 method on that timestamp (e.g., object.created_at.iso8601).

*The iso8601 method also accepts a numeric argument to display fractional digits; you would use this if you want 2020-04-06T19:16:55.604Z instead of 2020-04-06T19:16:55Z.

https://api.rubyonrails.org/v5.2.4/classes/ActiveSupport/TimeWithZone.html#method-i-iso8601


text:
Q: jQuery, 'undefined' length of array of arrays? I have this array structure:
mdarray = {
  '0001':{address:'add1',title:'title1'},
  '0002':{address:'add2',title:'title2'},
  '0003':{address:'add3',title:'title3'}
};

I wish to only work with the array if it has one or more items in it. Usually with an array I would use if (mdarray.length > 0) {} but when I do this with the array above, mdarray.length returns 'undefined'.
Is this is because it is an array of arrays? Is there another way to very simply pull back the number if items in the root of the array?
Or it is because the keys are strings and not integers?
I've played about with different array structures and read about multidimensional arrays but I've not yet found an answer.

A: That is an Object, not an Array. So it has no length!

A: Modified code: you are creating Object instead of Array you should use following code: see this thrad
mdarray = [
  {address:'add1',title:'title1'},
  {address:'add2',title:'title2'},
  {address:'add3',title:'title3'}
];

mdarray.length // 3


text:
Q: Problema al enviar variables desde arduino por metodo GET hacia pagina web Tengo un problema con mi codigo en arduino, el cual consiste en enviar los valores de temperatura y humedad por el metodo GET desde el arduino a una pagina web.
Les comento, realice la decodificación del arduino para que enviar valores GET al servidor local de Xampp y se almacenaran las variables en una Base de Datos. Esto me funciona perfectamente en el servidor local.
Pero cuando subi los archivos de la pagina web al servidor, las variables GET que se envian desde el arduino, no las almacena en la Base de datos del servidor y desde el arduino (en el monitor serie) me informa que el envio de los datos es exitoso. Pero en la base de datos del servidor no se almacenan los datos.
Si Alguien me pudiese colaborar con este problema, quedo inmensamente agradecido. Adjunto codigo del arduino cuando envia las variables al servidor por el metodo GET

#include
#include
#include
#include

//Declara constantes y pin de entrada
#define DHTTYPE DHT22 //DHT21, DHT22, DHT11
#define DHTPIN 2  // El sensor de temperatura y humedad

// Ingresamos la direccion MAC para el controlador
byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(198, 54, 116, 181); //se tiene que modificar por obligacion la direccion IP de la maquina o servidor 198.54.116.181

// Inicializamos la Libreria de Ethernet Client
// con la dirección IP y el puerto del servidor
// con el que se quiere conetcar (el puerto 80 es el predeterminado para HTTP):
EthernetClient client;

....

if (client.connect(server, 80)) { //colocar nombre de la página web sin http eso lo da el puerto 80

    float hum = dht.readHumidity(); //Leemos la Humedad
    float temp = dht.readTemperature(); //Leemos la temperatura en grados Celsius

    Serial.println("conectado");
    client.print("GET http://hector.paginaweb.click/secadero/controladores/conexion_arduino.php?temp="); // Enviamos los datos por GET para el servidor
    client.print(temp);
    client.print("&hum=");
    client.print(hum);
    client.println(" HTTP/1.0");
    client.println("User-Agent: Arduino 1.0");
    client.println();
    Serial.println("Envio con exito!");

    // Actualiza el tiempo en milisegundos de la ultima conexion
    ultimaConexion = millis();
}

A: El protocolo http es bastante estricto respecto al formato del mensaje.
En este caso en GET no debe figurar el servidor, sino la ruta del archivo... para indicar el servidor ya está el campo Host.
client.print("GET /secadero/controladores/conexion_arduino.php?temp="); // Enviamos los datos por GET para el servidor
client.print(temp);
client.print("&hum=");
client.println(hum)
client.println(" HTTP/1.0");
client.println("Host: hector.paginaweb.click");
client.println("User-Agent: Arduino 1.0");
client.println();

La cabecera final debería tener una forma similar a la siguiente:
GET /secadero/controladores/conexion_arduino.php?temp=.... HTTP/1.0
Host: hector.paginaweb.click
User-Agent: Arduino 1.0
[Linea sin contenido]

Por otro lado nunca estaría de más leer la respuesta del servidor para verificar que la comunicación es satisfactoria. Asumir que todo ha ido bien por el simple hecho de que has enviado el mensaje es mucho asumir.


text:
Q: How can i delete the mysql process which is not used any more? How can i delete the mysql process which is not used any more?
I am creating 1000 sql connection and some are not in use any more. I want to delete all the unused process.

A: you can list all active connections using the show processlist statement, and then kill the ones you don't need using the command kill {connectionid} . as others have pointed out, this is not a thing you should do often, instead try to fix the application so that unused connections are closed correctly.

A: This command will restart the server and close all open connections:
/etc/init.d/mysqld restart
You may however want to look into why the connections have not been closed in the first place. Your program is not supposed to leave 1000 connections unclosed.

A: You should modify the client application so it closes its connections when they are not needed.
Leaving connections open for a long time is usually counter-productive, it's often done as a (misguided, premature) optimisation. It causes problems because:

*

*Connections are not stateless, and unexpected state causes problems

*Connections get closed by the server after a while, or from network problems, leading to "morning bugs".

It is much better to close connections as soon as you're finished with them, in the general case.


text:
Q: Converting double value of 1234567.1234 to float in java I am trying to convert double to float in java.
Double d = 1234567.1234;
Float f = d.floatValue();

I see that the value of f is
1234567.1

I am not trying to print a string value of float. I just wonder what is the maximum number of digits not to lose any precision when converting double to float. Can i show more than 8 significant digits in java?

A: float: 32 bits (4 bytes) where 23 bits are used for the mantissa (6 to 9 decimal digits, about 7 on average). 8 bits are used for the exponent, so a float can "move" the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.
double: 64 bits (8 bytes) where 52 bits are used for the mantissa (15 to 17 decimal digits, about 16 on average). 11 bits are used for the exponent and 1 bit is the sign bit.
I believe you hit this limit what cause that problem.
If you change
Double d = 123456789.1234;
Float f = d.floatValue();

You will see that float value will be 1.23456792E8

A: The precision of a float is about 7 decimals, but since floats are stored in binary, that's an approximation.
To illustrate the actual precision of the float value in question, try this:
double d = 1234567.1234;
float f = (float)d;
System.out.printf("%.9f%n", d);
System.out.printf("%.9f%n", Math.nextDown(f));
System.out.printf("%.9f%n", f);
System.out.printf("%.9f%n", Math.nextUp(f));

Output
1234567.123400000
1234567.000000000
1234567.125000000
1234567.250000000

As you can see, the effective decimal precision is about 1 decimal place for this number, or 8 digits, but if you ran the code with the number 9876543.9876, you get:
9876543.987600000
9876543.000000000
9876544.000000000
9876545.000000000

That's only 7 digits of precision.

A:
I just wonder what is the maximum number of digits not to lose any precision when converting double to float.

Maybe you don't realize it, but the concept of N digits precisions is already ambigous. Doubtlessly you meant "N digits precision in base 10". But unlike humans, our computers work with Base 2.
Its not possible to convert every number from Base X to Base Y (with a limited amount of retained digits) without loss of precision, e.g. the value of 1/3rd is perfectly accurately representable in Base 3 as "0.1". In Base 10 it has an infinite number of digits 0.3333333333333... Likewise, commonly perfectly representable numbers in Base 10, e.g. 0.1 need an infinite number of digits to be represented in Base 2. On the other hand, 0.5 (Base 10) is peferectly accurately representable as 0.1 (Base 2).
So back to

I just wonder what is the maximum number of digits not to lose any precision when converting double to float.

The answer is "it depends on the value". The commonly cited rule of thumb "float has about 6 to 7 digits decimal precision" is just an approximation. It can be much more or much less depending on the value.
When dealing with floating point the concept of relative accuracy is more useful, stop thinking about "digits" and replace it with relative error. Any number N (in range) is representable with an error of (at most) N / accuracy, and the accuracy is the number of mantissa bits in the chosen format (e.g. 23 (+1) for float, 52 (+1) for double). So a decimal number represented as a float is has a maximum approximation error of N / pow(2, 24). The error may be less, even zero, but it is never greater.
The 23+1 comes from the convention that floating point numbers are organized with the exponent chosen such that the first mantissa bit is always a 1 (whenever possible), so it doesn't need to be explicitly stored. The number of physically stored bits, e.g. 23 thus allows for one extra bit of accuracy. (There is an exceptional case where "whenever possible" does not apply, but lets ignore that here).
TL;DR: There is no fixed number of decimal digits accuracy in float or double.

A: This is a simple example in support of the view that there is no safe number of decimal digits.
Consider 0.1.
The closest IEEE 754 64-bit binary floating point number has exact value 0.1000000000000000055511151231257827021181583404541015625. It converts to 32-bit binary floating point as 0.100000001490116119384765625, which is considerably further from 0.1.
There can be loss of precision with even a single significant digit and single decimal place.
Unless you really need the compactness of float, and have very relaxed precision requirements, it is generally better to just stick with double.

A: EDIT.
 No you cannot get any more precise with a float in Java because floats can only contain 32 bits ( 4 bytes). If you want more precision, then continue to use the Double. This might also be helpful


text:
Q: compare two xml files for and update certain key only with xmlstarlet I am trying to compare two of xml files and update only for a certain key as a new file. The issue occurs when i export a zabbix template and try to import on the other environment, status should be left as destination one. Assume that i have two xml files,
source.xml
<zabbix_export>
    <version>5.0</version>
    <groups>
        <group>
            <name>zabbix</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>testtemp</template>
            <name>testtemp</name>
            <groups>
                <group>
                    <name>zabbix</name>
                </group>
            </groups>
            <items>
                <item>
                    <name>test1</name>
                    <key>kernel.maxproc</key>
                    <triggers>
                        <trigger>
                            <expression>{last()}=0</expression>
                            <name>testtrig1</name>
                        </trigger>
                        <trigger>
                            <expression>{last()}=100</expression>
                            <name>testtrig2</name>
                        </trigger>
                    </triggers>
                </item>
            </items>
        </template>
    </templates>
</zabbix_export>

destination.xml
    <version>5.0</version>
    <groups>
        <group>
            <name> zabbix </name>
        </group>
    </groups>
    <templates>
        <template>
            <template>testtemp</template>
            <name>testtemp</name>
            <groups>
                <group>
                    <name>zabbix</name>
                </group>
            </groups>
            <items>
                <item>
                    <name>test1</name>
                    <key>kernel.maxproc</key>
                    <triggers>
                        <trigger>
                            <expression>{last()}=0</expression>
                            <name>testtrig1</name>
                            <status>DISABLED</status>
                        </trigger>
                    </triggers>
                </item>
            </items>
        </template>
    </templates>
</zabbix_export>

So my goal would be to create a new file and put the key/value "DISABLED" as following.
final.xml
<zabbix_export>
    <version>5.0</version>
    <groups>
        <group>
            <name>zabbix</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>testtemp</template>
            <name>testtemp</name>
            <groups>
                <group>
                    <name>zabbix</name>
                </group>
            </groups>
            <items>
                <item>
                    <name>test1</name>
                    <key>kernel.maxproc</key>
                    <triggers>
                        <trigger>
                            <expression>{last()}=0</expression>
                            <name>testtrig1</name>
                            <status>DISABLED</status>
                        </trigger>
                        <trigger>
                            <expression>{last()}=100</expression>
                            <name>testtrig2</name>
                        </trigger>
                    </triggers>
                </item>
            </items>
        </template>
    </templates>
</zabbix_export>

I've found one of the closest way to achieve this behave on the post Updating two xml file using xmlstarlet but still needs a small touch. So seems better to use 'xmlstarlet' since i need to run this babe in Debian natively.
It would be great at least give a clue how to use it in that way.
Thanks in advance,

A: Here are two ways to solve it, both assume that

*

*trigger elements have unique names

*a POSIX shell is used

First, an XSLT 1.0 transformation which will add a status element
from a same-named trigger in destination.xml. It's a basic
identity transform
which modifies the appropriate triggers. In case you want to limit
to certain status values you could add, for example,
 and $dstat = "DISABLED" to the xsl:if test clause.
<xsl:transform version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:strip-space elements="*"/>
  <xsl:param name="ddoc" select="'destination.xml'"/>
  <xsl:variable name="dtt" select="document($ddoc)//triggers/trigger"/>

  <xsl:template match="@*|node()" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="triggers/trigger[not(status)]">
    <xsl:variable name="dstat"
        select="$dtt[name = current()/name]/status"/>
    <xsl:copy>
      <xsl:apply-templates/>
      <xsl:if test="string($dstat)">
        <xsl:copy-of select="$dstat"/>
      </xsl:if>
    </xsl:copy>
  </xsl:template>

</xsl:transform>

Run as
xsltproc --stringparam ddoc destination.xml delta.xsl source.xml > final.xml

or
xmlstarlet tr delta.xsl -s ddoc=destination.xml source.xml > final.xml

Second, to do the same in xmlstarlet shorthand is trickier since
there are limitations on both the xmlstarlet select and xmlstarlet edit
operations: the former doesn't copy entire input, the latter doesn't
accept conditionals (except in XPath expressions). However, using
select as a code generator to produce an edit command is possible.
(To list the generated XSLT 1.0 code add -C option before -t.)
xmlstarlet sel -t \
  --var sq -o "'" -b \
  --var dq -o '"' -b \
  --var ddoc="'destination.xml'" \
  --var dtt='document($ddoc)//triggers/trigger' \
  -o 'xmlstarlet edit \' -n \
  -m '//triggers/trigger[not(status)]' \
    --var dstat='$dtt[name = current()/name]/status' \
    --if 'string($dstat)' \
      -o ' -s ' -v 'concat($sq,"//triggers/trigger[name=",$dq,current()/name,$dq,"]",$sq)' \
      -o ' -t elem -n status -v ' -v 'concat($sq,$dstat,$sq)' -o ' \' -n \
    -b \
  -b -f -n source.xml

For each status-less trigger in source.xml this command looks up
the same-named element in destination.xml having a non-empty status
element; on match emits an -s (subnode) clause for xmlstarlet edit
to target the appropriate node in source.xml. -o outputs literal
text, -n a newline, -f the input pathname, -b ends current
container (-m, --if, --var). Variables sq and dq assist in
quoting
Output:
xmlstarlet edit \
 -s '//triggers/trigger[name="testtrig1"]' -t elem -n status -v 'DISABLED' \
source.xml

Run as
xmlstarlet-sel-command-above | sh -s > final.xml

to execute the output as a shell script.