Q: Installing erlang 19.3 with ubuntu 18.04 gives the following error: crypto: No usable OpenSSL found, ssh : No usable OpenSSL found My OS is ubuntu 18.04, erlang version is 19.3, openssl version is 1.1.1, and when I use . /configure --prefix=/opt/erlang , the error report:
*********************************************************************
**********************  APPLICATIONS DISABLED  **********************
*********************************************************************

crypto         : No usable OpenSSL found
jinterface     : No Java compiler found
ssh            : No usable OpenSSL found
ssl            : No usable OpenSSL found

*********************************************************************
*********************************************************************
**********************  APPLICATIONS INFORMATION  *******************
*********************************************************************

wx             : wxWidgets not found, wx will NOT be usable

*********************************************************************
*********************************************************************
**********************  DOCUMENTATION INFORMATION  ******************
*********************************************************************

documentation  :
                 xmllint is missing.
                 Using fakefop to generate placeholder PDF files.

*********************************************************************

I check the version of libssl-dev
# dpkg -s libssl-dev
Package: libssl-dev
Status: install ok installed
Priority: optional
Section: libdevel
Installed-Size: 7669
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: amd64
Multi-Arch: same
Source: openssl
Version: 1.1.1-1ubuntu2.1~18.04.14
Depends: libssl1.1 (= 1.1.1-1ubuntu2.1~18.04.14)
Suggests: libssl-doc
Conflicts: libssl1.0-dev
Description: Secure Sockets Layer toolkit - development files
 This package is part of the OpenSSL project's implementation of the SSL
 and TLS cryptographic protocols for secure communication over the
 Internet.
 .
 It contains development libraries, header files, and manpages for libssl
 and libcrypto.
Homepage: https://www.openssl.org/
Original-Maintainer: Debian OpenSSL Team <pkg-openssl-devel@lists.alioth.debian.org>

I check the version of openssl:
# openssl version
OpenSSL 1.1.1  11 Sep 2018

What is the reason for the above error? How can I solve the above problem?


Q: How to automate data extraction from Elasticsearch Dev Tools? I have to do the following steps two or three times a day

*

*log in into Elasticsearch

*Go to Dev Tools

*Run a specific query by selecting it and pressing ctrl + enter
Query that I have to run

*Select the results that returns in the "buckets" and copy it.
The yellow markdown in the image is what I have to select and copy

*Then I go to https://www.convertcsv.com/json-to-csv.htm and paste the results so it converts to CSV.
Where I have to paste the results.

*I can then download the CSV and then import it into google sheets so I can view the results in a Looker Dashboard.
Button to download the converted CSV.
This take me some time everyday and I would like if there is any way that I could automate such routine.
Maybe some ETL tool that can perform at least part of the process or may some more specific way to do it with python.
Thanks in advance.
I don't have much experience with what I want to do and I tried to search online similar issues, but couldn't really find anything useful.

A: I don't know you tried, but there is a reporting tool on elasticsearch inside the "Stack Management > Reporting". On the other side, there are another tools which you can work from a server with crontab. Here are some of them :

*

*A little bit old but I think it can work for you. ES2CSV. YOu can check there are examples inside the docs folder. YOu can send queries via file and report to CSV.

*Another option which is my preference too. You can use pandas library of python. YOu can write a script according to this article, and you can get a csv export CSV. The article I mentioned is really explained in a great way.

*Another alternative a library written in Java. But the documentation is a little bit weak.

*Another alternative for python library can be elasticsearch-tocsv. This one is a little bit recently updated when I compare it to first alternative. But the query samples are a little bit weak. But there is a detailed article. You can check it.

*You can use elasticdump, which is written on NodeJS and a great tool to report data from elasticsearch. And there is a CSV export option. You can see examples on GitHub page.

I will try to find more and I will update this answer time by time. Thanks!


Q: Express JS not rendering jade template I'm going to keep this short, I'm just trying to render a jade template using express js.
I'm using express 3.0.0rc5 and jade 0.27.6.
Here's my jade templates, the layout:
// test-layout.jade
doctype 5
html
  head
    title My title
    block head
  body
    #content
      block content

And the index:
// test-index.jade
extends test-layout

block head
  script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js")

block content
  h1 My page

Here's some excerpts from app.js:
var app = express();
// Configuration
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/test-jade', function(req, res) {
    res.render('test-index', {}, function(err, html) {
    });
  });
app.get('/test', function(req, res) {
  res.send('this works');
});

Now whenever I try to go to http://myurl.com/test-jade the browser just hangs and timesout without showing any output in the console (even though I'm in dev mode).
However when I go to http://myurl.com/test I see 'this works'.
I feel like I'm missing something really simple here, I'm currently upgrading from 2.5 to 3.0.
Thanks in advance if anyone has advice.

A: Is it the blank call back?
 res.render('test-index', {}, function(err, html) {
 });

In my app I'm using
res.render('test-index', {});


Q: How can one solve this optimization problem by rewriting the matrix? Given this problem:
$$maximize \, \, x^T\begin{bmatrix}
3 & 4 \\
0 & 3
\end{bmatrix}x
$$
$$ subject \,to \, \, ||x||^2 = 1$$
I want to solve this using Langrange Conditions. What I wish to do is find the eigenvalues of a symmetric matrix $Q$, and the corresponding eigenvectors to maximize this problem.
In the solution material the textbook author rewrites the matrix: $\begin{bmatrix}
3 & 4 \\
0 & 3
\end{bmatrix} $ into $ Q = \begin{bmatrix}
3 & 2 \\
2 & 3
\end{bmatrix}$ , where $Q^T = Q$.  How and why can one do this?
(Afterwards one can calculate the eigenvalues of $Q$ and find the corresponding eigenvectors)
Thank you.

A: That manipulation is valid since $$x^T\begin{bmatrix}3&4\\0&3\end{bmatrix}x = 3x_1^2+4x_1x_2+3x_2^2 = 3x_1^2+2x_1x_2+2x_2x_1+3x_2^2 = x^T\begin{bmatrix}3&2\\2&3\end{bmatrix}x.$$
In general, if $A \in \mathbb{R}^{n \times n}$ and $x \in \mathbb{R}^n$, then $x^TAx$ is a scalar. Hence, $x^TAx = (x^TAx)^T = x^TA^Tx$, and thus, $$x^TAx = \dfrac{1}{2}x^TAx+\dfrac{1}{2}x^TA^Tx = x^T\left(\dfrac{A+A^T}{2}\right)x.$$


Q: PHP number_format() and round() not producing valid upper-range results 3 CODE:
in_array($number, round(range(65,74)))

or
round(in_array($number,range(65,74)))

I'm doing a switch case whenever the user inputs 73.4 the result is null. But whenever I input 73 or 74 it executes.
How to do it I'm a newbie in php here.

A: You need to round the user input number and not the range. So, it will be ,
in_array(round($number), range(65,74));

DEMO.


Q: Autolayout is expecting a different height I'm struggling with autolayout in my iOS 7 project on Xcode 5. Let's say I want to show these buttons :
    Something
        -
        |                      10 pts fixed space from top
        -
     Button 1                  50 pts height on 4" display, reduce height if 3"5
        -
        |                      10 pts fixed space
        -
     Button 2                  50 pts height on 4" display, reduce height if 3"5

I layout my buttons in Interface Builder (with a storyboard).
Then I start adding constraints :

*

*The vertical spacing from "button 1" to "something"

*The leading space to container for "button 1"

*The fixed width for "button 1"

Problem is Autolayout is complaining about my button's, saying "Expected: height=30". Why ? I want a 50 pts button, why is this a problem ? Of course, I can fix this by adding a height constraint, but I want the height to be reduced if the height of the screen is reduced. And, if I run it, even on a 4" display, the button's height is set to 30, as autolayout said it "should be".. And I didn't even set the second button's constraints yet, which will make it even worse.
How can I achieve such a thing ? It seems really basic and I still don't understand what's going on.
Note that I could manually set all the heights in code, but I really want to avoid that.

A: What you can do for solving the vertical constraint issue is to give Equal constraints to your button1 and button2 and give a fixed vertical constraint to the something view and from your second button to the bottom of the superview.
So this way you won`t need to give a fixed height to any of them and the distance between them and other elements (something and bottom of superview) will be standard.
I hope this helps!

A: Ok, I think I made it.
Here is what I did :

*

*I set all my constraints in the storyboard, with the Retina 4" form-factor.

*Constraints for the something view : fixed height & width, fixed top space and leading space. This view is absolutely fixed.

*Constraints for button 1 : fixed vertical space to something view, fixed leading space, fixed width. 2 height constraints : 30 <= height <= 50.

*Constraints for button 2 : fixed vertical space to button 1, fixed leading space, fixed width. Also 2 height constraints : 30 <= height <= 50. And fixed bottom space to bottom layout.
All constraints have a maximum priority of 1000, except the last one (fixed bottom space to bottom layout), which is set at 900 !
That way, the buttons keep a height >=30 and move up, but get shrinked vertically because the other constraints are more important.
Thanks a lot to @VasiliyDeych and @P.Sami for their advice. It helped a lot.

A: You're going to need to show us how your constraints are set up.
Constraints are a set of rules that the views must follow. If there is no rule saying the button must shrink with the parent view, it will not happen.
Based on your example, if I understood it correctly, you would want a set of constraints like this (defined in VFL for ease):
[yourParentView addVisualConstraints:@"V:|[something(100@75)]-(10@100)-[button1(<=50,>=30@100)]-(10@100)-[button2(button1@100)]-(>=300@50)-|"
                  forViews:NSDictionaryOfVariableBindings(something,button1,button2)];

All constraints here are vertical (V:), the numbers in parentheses represent a number of points, followed by @ and the desired priority of maintaining that number of points. The | symbols represent the top and bottom edges of the superview. So ]-(>=300@50)-| is saying, I'd like to keep 300 or more pixels between button2 and the bottom of the superview, but I care about it with a priority of 50. button1(<=50,>=30@100) means I really care that this button is between 30 and 50 pixels in height, with a priority of 100. button2(button1) means I want button2 to be the same height as button1. I also really care about keeping that 10-point distance between my elements. And I somewhat care that something (which is flush to the superview's top edge, hence |[) is going to stay at 100 points tall.
Does this not work for what you are intending to do?


Q: How discuss the matrix positive definition $A=B^TB$? let

$$B=\begin{bmatrix}
1&1&\cdots&1\\
a_{1}&a_{2}&\cdots&a_{m}\\
a^2_{1}&a^2_{2}&\cdots&a^2_{m}\\
\cdots&\cdots&\cdots&\cdots\\
a^{n-1}_{1}&a^{n-1}_{2}&\cdots&a^{n-1}_{m}
\end{bmatrix}$$

Discuss the matrix positive definition (meaning that,when $a_{i}$ such what conditions) $A = B ^ TB $ ？
My try: let
$$|A|=|B^TB|=|B|^2?$$
and I can't.Thank you for you help.and I guess

when $a_{i}\neq a_{j},\forall i\neq j$.then $A$ is  positive definition matrix?

A: Matrix $B$ has $m$ columns so its rank is at most $m$. When ${\sf rank}(B)=m$ we say that $B$ has full rank.
The answer to your question is YES. In fact, one has a much stronger result :
Theorem 1. The matrix $A=B^TB$ is positive definite
if and only if $B$ has full rank $m$.
Proof “if” Let $X$ be a vector in ${\mathbb R}^m$, one has $\langle AX,X\rangle=\langle B^TBX,X\rangle=\langle BX,BX\rangle=\|BX\|^2$ where $\|.\|$ is the usual euclidian norm. Also, if $\langle AX,X\rangle=0$, then $\|BX\|=0,BX=0$, hence
$X=0$ since $B$ has rank $\geq m$. So $A$ is positive definite.
“only if” : If $B$ has rank $< m$, there is a nonzero $X\in {\mathbb R}^m$ with
$BX=0$. Then $\langle AX,X\rangle=0$ and $X$ is nonzero, so $A$ cannot be positive definite.
Combine that with
Theorem 2 Let $B$ be the Van der Monde matrix $(a_j^{i-1})_{1\leq i\leq n,1\leq j \leq n}$.Then $B$ has full rank $m$ iff the  $a_j$ are distinct.
Proof : see here.


Q: How to convert plain text files into libreoffice cal (Excel sheet) on Ubuntu 14.04? I have a plain text file containing a huge amount of data. The data's are separated by semicolon and a newline for starting a new line of the following data. Here's a sample:

"user_id";"device_id";"timestamp";"driving";"id";"onfootoptional";"running";"servertimestamp";"stationary";"tiltingoptional";"unknown";"walking"
2089;2145;"2016-01-28 14:31:27";28;"b28aa64d-7fe0-49e7-8a1b-b8d37c95a851";1;0;"2016-01-28 15:11:41";18;0;50;1

I have tried to convert using the general method and its not converting. The problem I am finding after converting is the output is somewhat in Chinese letters whereas the text contain only English alphabet and numbers with some special characters. Also the conversion doesn't follow as the text file, like when a newline comes, it supposed to be starting from a new line.
How I really want to convert text files into excel sheet is :

*

*Convert each section containing with "Something or nothing" followed by a ";" into a single cell.

*Inside the " " field, if it is a string then it needs to be converted as a string and if it contains only Integer numbers then it needs to be converted as an integer number. However if there are a mixture of string and integer then it needs to be converted as a string. Additionally, if an integer number contains any type of special character like " . ", " , ", " - " or " : " then it needs to be converted as an integer plus special characters.

*When the line of the text is finished with an newline, then on the excel sheet the conversion would start from a newline.

A: I think, the built-in function (is this the general method?) of Libreoffice should be able to do this?
If not - try csv2odf. This is a very handy tool, especially for many files to convert. It should fit your needs.
I am not sure about the formatting you mentioned. Give csv2odf a try. If it does not what you want it to do, try to specify, what csv2odf does
-you want
-you don't want
Best with proper examples.
Hope this helps. Good luck!

A: I copied and pasted your sample into a file called "test.csv" and then double-clicked on it.  Using the default settings, it opened just fine in Calc.
Try trimming down the file to a few hundred rows using a text editor, and then open it.  If that works, then it should give an idea of what is causing the problem.
Maybe the file has newline problems.  Try fixing them like this: https://unix.stackexchange.com/questions/32954/use-sed-to-fix-broken-newlines
Also check the encoding: https://stackoverflow.com/questions/805418/how-to-find-encoding-of-a-file-in-unix-via-scripts
If "huge amount of data" is over 1 million rows, see https://ask.libreoffice.org/en/question/8631/upper-limit-to-number-of-rows-in-calc/.

A: The problem is solved. The conversion is not working correctly on my laptop but on someone else's Ubuntu 14.04 it worked. He basically didn't change any setting while converting. He has just followed by clicking next and then Ok finally.
Thanks for your responses.


Q: Portable speaker- battery pack problem I started building a DIY portbale speaker out of a douk audio tp 3116 and an old pair of sony speakers.
The spec on the ebay site of the amp says that it operates between 12-25 volts, but for the 60 watts sony speakers I would need around 24 volts.
So my question is how should I power the amp?
 I wanted to use 2 gel batteries, but if fully charged it would output around 28v, so i would need a dc-dc converter, and its capacity is small as well, so i thrashed this idea.
 If I used 18650-s I would need 5-6 cells, (I realised that 20v is enough for what I want it to use) but i dont know how long will it last with this kind of setup.
Should I use 2-3 packs in paralell in order to get decent batterylife or it is hopeless to make something this "powerful" battery powered.
Could you tell me what should I do in order to make this project work?

A: You haven't specified how much power the amp is supposed to put out, so apparently anything works.
Use as many 18650 lithium cells in series as you can without exceeding the amp's maximum allowed input voltage when the cells are at their maximum voltage.  The more tricky part is keeping track of the individual cells, and stopping before the lowest one gets to a voltage where it would be damaged.
Two car batteries in series might also work, as long as you don't charge them while connected to the amp.


Q: How do I solve "Undefined color `\dtlpie@segcolix '"? I have the following LaTeX file:
\documentclass{article}
\usepackage[pdftex,active,tightpage]{preview}
\setlength\PreviewBorder{2mm}
\usepackage{datapie}
%\usepackage{xcolor}
%\xdefinecolor{\dtlpie@segcolix }{rgb}{.8,.6,.4} <- didn't work

\begin{document}
\begin{preview}
    \DTLloaddb{myDB}{local-disk-space-piechart-2013-07-08.csv}
    \DTLdisplaydb{myDB}
    \DTLpiechart{variable=\Space,outerlabel=\Part}{myDB}{\Part=Part,\Space=Space}
    %\DTLdisplaydb{myDB} <- this works
\end{preview}
\end{document}

with this csv file:
Part,Space
programs,18124.8
movies,21606.4
source code,6246.4
VMs,3788.8
Android SDK,1228.8
Audio files,917.0
.cache,832.1
.config,358.5
Desktop,341.3
misc,829.44

which I compile like this within a Makefile:
pdflatex source.tex -output-format=pdf

I have no idea how I can get rid of the error:
[...]
(/usr/local/texlive/2012/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg))

! Package xcolor Error: Undefined color `\dtlpie@segcolix '.

See the xcolor package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.12 ...abel=\Part}{myDB}{\Part=Part,\Space=Space}

?
! Emergency stop.
 ...

l.12 ...abel=\Part}{myDB}{\Part=Part,\Space=Space}

!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on local-disk-space-piechart.log.
make: *** [make] Error 1

Do you know how to solve this problem?

A: According to the datapie documentation (section 7.3 Pie Chart Colours, p 131):

The datapie package predefines colours for the first eight segments
  of the pie chart. If you require more than eight segments or if you
  want to change the default colours, you will need to use
\DTLsetpiesegmentcolor{<n>}{<color>}

The first argument <n> is the segment index (starting from 1), and
  the second argument <color> is a colour specifier as used in
  commands such as \color.

\documentclass{article}

% Data
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
Part,Space
programs,18124.8
movies,21606.4
source code,6246.4
VMs,3788.8
Android SDK,1228.8
Audio files,917.0
.cache,832.1
.config,358.5
Desktop,341.3
misc,829.44
\end{filecontents*}

\usepackage[active,tightpage]{preview}
\setlength\PreviewBorder{2mm}
\usepackage{datapie}

\begin{document}
\begin{preview}
  \DTLsetpiesegmentcolor{9}{green!40!yellow}% Additional colour for segment 9
  \DTLsetpiesegmentcolor{10}{green!40!pink!20!black}% Additional colour for segment 10
  \DTLloaddb{myDB}{data.csv}
  \DTLdisplaydb{myDB}
  \DTLpiechart{variable=\Space,outerlabel=\Part}{myDB}{\Part=Part,\Space=Space}
  %\DTLdisplaydb{myDB} <- this works
\end{preview}
\end{document}

A: By default, eight colours are assigned by pie chart. But you are using ten data and require ten colours. The nineth and tenth colours should be defined to get rid of the error.
\DTLsetpiesegmentcolor{9}{cyan}
\DTLsetpiesegmentcolor{10}{brown}

Please try this command before \begin{document}. Also, see page 77 of datatool.pdf (texdoc datapie) for additional instructions.


Q: Firebase login with GCP service account I am trying to login to the Firebase Tools CLI with a GCP service account. I have the path to the service account credentials saved as GOOGLE_APPLICATION_CREDENTIALS. I have logged out of firebase with firebase logout and have tried to sign in with the service account with firebase login --no-localhost and firebase login --no-localhost  --token $GOOGLE_APPLICATION_CREDENTIALS. However in bother cases a web browser opens asking me to log in with my user account. How can I log in to firebase with a service account?

A: Taken from Michael Bleighs comment:
"The Firebase CLI does support GOOGLE_APPLICATION_CREDENTIALS, but you don't need to "log in" with them. If the environment variable is pointing to a valid service account you should be able to just use CLI commands as if you are logged in. You do need to be logged out for GAC to work correctly. Run the command with --debug if you're getting errors while trying to do so."
I can confirm I have this working. Note you might need to run firebase use <project-id> for it to work correctly.

A: You can't sign in to your Firebase project with a service account. You will need to use the proper user account of a collaborator on the project to sign in with Firebase tools.
Even when using the CI integration, the documentation says to:

*

*Start the signin process by running the following command:
 firebase login:ci

*Visit the URL provided, then sign in using a Google account.


Q: Insert Indirectly Into a Naming Table? Let's consider this diagram

With this JPA snippet of the Track class.
@Entity
@Table(name = "track")
public class Track {
    @Id
    @Type(type="pg-uuid")
    private UUID id;

    @Column(name = "genre")
    private String genre;

    /* Getters, setters, etc */
}

And the database schema
/** Liquibase */
<changeSet id="1" author="SoulBeaver">
    <createTable tableName="genre">
        <column name="name" type="VARCHAR(1024)">
            <constraints primaryKey="true" nullable="false" />
        </column>
    </createTable>

    <createTable tableName="track">
        <column name="id" type="UUID">
            <constraints primaryKey="true" nullable="false" />
        </column>
        <column name="genre" type="VARCHAR(1024)" />
    </createTable>
    <addForeignKeyConstraint baseTableName="track" baseColumnNames="genre" constraintName="genre_fk"
                             referencedTableName="genre"
                             referencedColumnNames="name" />
</changeSet>

Now, when I try to persist a track, which has been given a track.setGenre("Rock"); I get a RuntimeError stating that the key does not exist in Genre.
Is there any way I can avoid having to create the Genre class, persisting the Genre first, and finally persisting the Track?

A: Basically the FKey Constraint works in such a way that if you try to insert a value in child table with FKey value not present in your parent table, it will fail. This is not specific to JPA. It is how relational DB is designed.


Q: Why not wrap content within ``? It seems common to use the following HTML structure to accommodate
users who have enabled/disable javascript:
 <html>
     <style>
         div.body { display:none; }
         .body > ... { ... }
     </style>
     <script>
         document.onload( function() {
             javascript(CONTENT => div.body);
         });
     </script>
     <noscript>
         <style>
             body > :not(noscript) {
                 display:none;
             }
         </style>
     </noscript>
 <body>
     <div class="body">
     </div>
     <noscript class="body">
         CONTENT
     </noscript>
 </body>
 </html>

The mechanism uses a <div>; whose display attribute, initially set
to none, is subsequently set to block|grid|etc. and populated with
CONTENT once the page is loaded; alongside a <noscript>; which is
pre-populated with CONTENT.
No one seems to suggest simply popping the CONTENT within
<noscript> into the <body> when javascript is available as follows
:
 <html>
     <style>
         .body { ... }
         .body > ... { ... }
     </style>
     <script>
         document.onload( function() {
             let noscript = document.querySelector("noscript");
             noscript.outerHTML = noscript.innerHTML;
         });
     </script>
     <noscript>
         <style>
             body > noscript {
                 display:content;
             }
         </style>
     </noscript>
 <body>
     <noscript>
         CONTENT
     </noscript>
 </body>
 </html>

Here the CONTENT within noscript is displayed by default and if
there is javascript the tag is simply dropped; the specification
states the content of noscript should be parsable and that the parsed
result be readily assignable as noscript.outerHTML.
The first method requires one to repeat ones CONTENT in both the
noscript and wrapped into the javascript that populates the div;
this isn't especially DRY. I can't see that populating a page through
javascript calls is any faster then assigning ELEMENT.outerHTML; if
this is not true let me know.  The second method relies upona bit of
CSS trickery. Finally both methods seem subject to flicker.
The only reasons I can think of for not using the latter structure are
:

*

*SEO; I can't see how though e.g. you only have to scan CONTENT once, it sn't repeated, it isn't bundled between javascript, better
aria/a11y support.

*Frontend framework e.g. they all rely on the first structure

*historic reasons e.g. setting noscript.outerHTML breaks events or something ut they are broken under the spec anyhow, jQuery.unwrap
being a "recent" development, browser woes.


Q: Django form isn't rendering at all I'm trying to make a non model form that just gets input text for a chat like interface.
views.py
def get_input(request):
    if request.method == 'POST':
        form = inputForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')

    else:
        form = inputForm()

    return render(request, 'index.html', {'form': form})

def shelley_test(request):
    form = inputForm()
    return render(request, 'shelley_test.html')

form.py
from django import forms

class inputForm(forms.Form):
    input = forms.CharField(label='input field')

shelley_test.html
<form action="/get_input/" method="get">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

please please help. I'm new at django and stumped :(

A: You're not sending the form to the context in your shelley_test method - see the difference in the render line compared with get_input.
Note though you don't need shelley_test at all: just go straight to /get_input/ to see the empty form.


Q: Windows Defender deletes files of my Ubuntu Server I have two ubuntu servers i use as storage servers set up with samba files share. I connect to them through my main machine running windows 10 and some files on the server get flagged and instantly removed by windows defender. I have even added both servers as exclusions in windows defender but they windows does not seem to care at all. Windows does not actively remove them when i am not in the folder these files are in, but seem to delete them the moment i enter the folder and the files just disappear in front of my eyes.
I need help with getting a way to stop this from happening as a reason i even did parts of my servers are to keep windows from grabbing and randomly deleting files it does not like. Windows defender places the files in quarantine but they are not restorable or placable in to whitelist from that. I have tried everything i know through windows and windows defender but nothing seems to work.


Q: Hash created from CSV row not behaving like a normal hash I'm getting some weird issues. I'm trying to allow importing of a CSV into my model. I'm getting an unknown attribute 'hashtag' for Job. error, but that's not the issue. My model definitely has a hashtag column.
When I get the error, if I try doing job.to_hash I get {"hashtag"=>"apples", "number"=>"10", "job_type"=>"0"} and if I do job.to_hash.symbolize_keys (with or without a !) I get {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
However, here comes the issue. Both of these seem to be of the Hash class when I call .class on them. But if I try assigning it to a variable and calling ["hashtag"] or [:hashtag] on it, it returns nil.
Example of what I mean:
>> foo = job.to_hash.symbolize_keys
=> {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
>> bar = {hashtag: "apples", number: "10", job_type: "0"}
=> {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
>> foo == bar
=> false

>> foo.class
=> Hash
>> foo.class == bar.class
=> true

Model:
class Job < ApplicationRecord
  require 'csv'

  def self.import(file)
    file = CSV.read(file.path, headers:true)
    file.each { |job| Job.create(job.to_hash)}
  end
end

CSV:
hashtag,number,job_type
apples,10,0
bees,10,0
carrots,10,0

I really don't see what's going wrong... I'm literally copying and pasting the foo variable above into a new variable and it works, yet the original doesn't, despite, despite apparently being a hash as well.

A: Apparently the :hashtag has two different encodings for me, seems like one is stored as US-ASCII, and one (the parsed) in UTF-8. Funny that I was able to reproduce this only by pasting this into my irb.
To solve this, make sure they have the same encoding


Q: Compiling cross-referenced classes in Codelite I'm sure this topic has come up before, but I am not sure what even to google for:
I am new to C++ and while learning I wrote first a Vector class, then a Matrix class (which uses the Vector class). While working on the Vector class the program compiled fine, but when adding the Matrix class (which includes and uses the Vector class) I'm starting to get compile errors. Specifically "undefined reference to functionname" - eventhough the function for sure exists and was working fine before when only the Vector class existed (it's a getter function for a component).
Showing this code to someone who knows C++ but not Codelite they said my code is fine, but the compiling/build order seems weird and that it seems like the software tries to compile my classes like a main.cpp.
Is that enough for anybody to give me any pointers to what to research/look up to get this working?


Q: Why are rails development credentials gitignored by default? I'm generating credentials using the following command:
rails credentials:edit --environment development
I notice that rails puts this in the gitignore:
+/config/credentials/development.key
I dont understand why, based on the following reasons:

*

*The development credential file is encrypted by default, hence harmless to check in as long as the master key isnt checked in.

*It's essential for a fresh environment setup (eg. on a new dev environment)

*If the original file is lost, all the data in the dev environment will have to be reseeded.

I'm inclined to check it in but figured, given Chesterton's fence and all, I'm likely missing something.

A: I figured it out. I was confused between the development.key and the  config/credentials/development.yml.enc. The latter is the encrypted credential file.


Q: Python/Bash - Tab completion not including files when arguments are provided I'm not sure whether this is a Python issue or a bash issue, but I'm having trouble with tab completion not working on files (only directories) when I'm providing arguments to my python script. Example of how I want it to work:
python myscript.py -e data_dir/da[TAB]
python myscript.py -e data_dir/data.tsv

However, it works when I'm not providing an argument, or if I'm using an equals sign between the argument and the file path. Examples of scenarios where it works:
python myscript.py data_dir/da[TAB]
python myscript.py data_dir/data.tsv

python myscript.py -e=data_dir/da[TAB]
python myscript.py data_dir/data.tsv

Is what I'm expecting unreasonable, considering the normal behavior of python and bash? I.e. is my tab completion working like it's supposed to? Alternatively, am I using python arguments incorrectly when I'm not including the equals sign with my arguments?
I'm using bash version 4.3.11(1)-release and python version 2.7.6.
Thanks!


Q: Conformal Mapping of Simple Non-Convex Polygon onto Unit Circle I have seen conformal mappings from convex polygons to the unit circle, and I have seen mappings from the circle to non-convex polygons. I have not seen arbitrary simple non-convex polygons mapped to unit circles, which is where my interest lies.
Does such a mapping exist? In either case, what is an example, and what is a specific reference that I can follow up with?

A: As comments suggest, such a mapping exists by the Riemann Mapping Theorem. A constructive approach to determining the mapping (and its inverse) is given by the Schwarz-Christoffel formula. For reference, the book Schwarz-Christoffel Mapping by Driscoll and Trefethen is helpful.


Q: Algebra Question ( possible values) If

$$k = \dfrac{a}{b+c} = \dfrac{b}{a+c} = \dfrac{c}{b+a}$$

How many possible values of $k$ are there?

A: Add like this:
$$(b+c)k+(a+c)k+(b+a)k=a+b+c$$
$$k=\frac{a+b+c}{b+c+a+c+b+a}=\frac12$$
if $a+b+c\ne0$, else $a=-(b+c)\Longrightarrow\dfrac a{b+c}=-1$.
So there are $2$ possible values for $k$, because first is e.g. for $a=b=c=1$ and the second e.g. for $a=b=1, c=-2$.

A: Using Addendo, $$k=\frac a{b+c}=\cdots=\frac{a+b+c}{b+c+c+a+a+b}$$
Now check if $a+b+c=0$ and it is not


Q: Issue with stock Browser picking photos from Gallery I am working on a web page for uploading photos from a mobile device, using the <input type="file" accept="image/*"/> tag. This works beautifully on iphone and on chrome on the android, but where we are running into issues is with the stock android browser.
The issue arises when you select a file from your gallery (it works fine when you use the camera to take a photo). And we have narrowed it down even further to seeing that the data MIME type isn't available when taken from the gallery on the stock browser (the photos below show the first 100 characters of the data URL being loaded.  The goal was to force JPEG, but without the MIME type we cannot know for sure how to fix this.  See code below for how the images are being rendered.
How can an image be rendered without the type? Better yet, does anybody know why the type is not available on the stock android browser?
EDIT
Firstly, these are not the same image, they were taken near the same time, and that's not the issue, that's why the data is different (The MIME type doesn't appear on any images on the stock browser, so that's not the problem.
Update
I confirmed that the MIME type is the issue by inserting image/jpeg into the stock browser where it is on chrome. Unfortunately, we have no way of guaranteeing that it's going to be jpeg, so we again really can't do it that way
 _readInputFile: function (file, index) {
            var w = this, o = this.options;
            try {

                var fileReader = new FileReader();

                fileReader.onerror = function (event) {
                    alert(w._translate("There was a problem opening the selected file. For mobile devices, some files created by third-party applications (those that did not ship with the device) may not be standard and cannot be used."))
                    $('#loadingDots').remove();
                    return false;
                }
               fileReader.onload = function (event) {

                var data = event.target.result;
                //alert(data.substring(0,100));
                //var mimeType = data.split(":")[1].split(";")[0];

                alert("Load Image"); //I get to this point
                $('#' + w.disp.idPrefix + 'hiddenImages').append($('<img />', {
                    src: data,
                    id: "dummyImg" + index,
                    load: function(){
                    var width = dummy.width();
                    var height = dummy.height();
                    $('#dummyImg' + index).remove();
                    alert("Render"); // I don't get here
                        var resized = w._resizeAndRenderImage(data, null, null, biOSBugFixRequired, skewRatio, width, height);
                        alert("Image Rendered"); // I don't get here

                    }
                }));
            }
            fileReader.readAsDataURL(file);
        }
        catch (e) {
        }
 }

Chrome

Stock Browser

A: Since the issue is probably browser-related, and you can't really fix the browser(you could report a bug to Google though), I'd suggest taking a different path.
Have a look Here:
In Node.js, given a URL, how do I check whether its a jpg/png/gif?
See the comments of the accepted answer, which suggests a method to check the file type using the file stream. I'm pretty sure this would work on browser-implemented Javascript and not only in Node.js.


Q: Passing params in Knockout component as a AMD Module My tagname component is like below and while the component is registered as a single AMD module, I want to get the all params.
ko.components.register('tagname', {
  synchronous: true,
  require: params.url
});

<tagname params="url: 'some/relative/url'"></tagname>

How can I do that?

A: The function that you provide for your view model (or as the createViewModel factory) will receive all of the params. For example:
define(['knockout', 'text!./my-tagname.html'], function(ko, templateString) {
    function MyTagNameComponent(params) {
        // do something with params here
    }

    return { viewModel: MyTagNameComponent, template: templateString };
});

So, your component will receive its params as the first argument to MyTagNameComponent in this case.
Here is a sample: http://jsfiddle.net/rniemeyer/g7zhjfz1/


Q: How can this element button be clicked using protractor? I'm trying to select this button using protractor:
<button tabindex="-1" type="button" class="btn btn-default pull-left" ng-click="$arrowAction(-1, 0)">

 <i class="glyphicon glyphicon-chevron-up">
 </i>

</button>

the only unique element in this is ng-click="$arrowAction(-1, 0)"
Nothing I have tried works:
element(by.css("//button[@ng-click='$arrowAction(-1, 0)']")).click();

A: //button[@ng-click='$arrowAction(-1, 0)'] is not a valid CSS selector. It actually looks like this is an XPath expression and you meant to use by.xpath() locator.
You can though use the partial attribute check instead:
$("button[ng-click*=arrowAction]").click();

$ here is a shortcut to element(by.css(...)), *= means "contains".
Or, do an exact match:
$("button[ng-click='$arrowAction(-1, 0)']").click();

I still don't like the location technique used in this case, but, given what we have, it is probably the best we can do. Ideally, if you have control over the application code and templates, add a meaningful id, class or a custom data attribute to uniquely identify the element.


Q: Is this the (real) algebraic numbers? I want to construct the real algebraic numbers from $\mathbb{Q}$ in a manner that sort of "looks like" the construction of the complex numbers from the reals, in a superficial manner. I can't define a single "irrational unit", but I instead tried to start with the set $\{ \sqrt{z} \mid z \in \mathbb{Q} \}$ and build the algebraic numbers from there.
This is what I'm thinking:
Let $A_{0} = \{ q + p \sqrt{z} \mid  q, p, z \in \mathbb{Q} \}$.
In general, let $A_{n} = \{ q + p \sqrt{z} \mid q, p, z \in \mathbb{Q} \cup A_{0} \cup \dots \cup A_{n-1} \}$.
Let $A = \cup_{i=0}^{\infty} A_{i}$.
Is $A = \mathbb{A}$? If not, what's missing, and if so, can this description be simplified in some way?
Thanks all.

A: These are called the constructible numbers, so named because they are the numbers you can construct via Euclidean geometry with a compass and straightedge, starting from a unit interval.
Adjoining all square roots isn't enough to produce the algebraic numbers; you can never produce $\sqrt[3]{2}$ in this fashion.
Adjoining $n$-th roots isn't enough either; for example, there are explicitly known polynomials of degree five whose roots cannot be expressed in that fashion. (i.e. the "insolvability" of the quintic)


Q: Choosing a contour for this integral $$\int_{0}^\infty \frac{x^{\frac{1}{2}}}{x^2+1} \ dx$$
by taking the branch cut of $x^{\frac{1}{2}}$ along the positive real axis.
I wasn't sure what contour to choose, so I chose this keyhole contour:

Where the upper line segment is $C_1$ and the lower line segment is $C_2$, with the circular arc of radius $R$ being $C_R$ and the smaller circular arc of radius $r$ be $C_r$.
Can someone please show me how to use my contour to evaluate this?
This is my attempt

Note that $$\int_{C} \frac{z^{\frac{1}{2}}}{z^2+1} \ dz = 2\pi i \mathrm{Res}(f,i) + 2\pi i \mathrm{Res}(f,-i)$$
where $C = C_1 + C_2 + C_R + C_r$.
First consider
$$\left|\int_{C_R} \frac{z^{\frac{1}{2}}}{z^2+1}\right| \ dz \leq ML$$
where $M = \mathrm{max}\left\{\left|\frac{z^{\frac{1}{2}}}{z^2+1}\right|:z\in C_R\right\} = \frac{R^{\frac{1}{2}}}{R^2 - 1}$
and $L = \mathrm{length}{C_R} = 2\pi R$.
So that expression goes to zero as $R\rightarrow \infty$.
Similarly,
$$\left|\int_{C_r} \frac{z^{\frac{1}{2}}}{z^2+1}\right| \rightarrow 0$$
as $r\rightarrow 0$.
So it seems that all that's left is to parametrize the remaining segments... but I can't seem to have an expression which has upper limits going to infinity.

A: You have by the definition of your brach cut $$(x+ir)^{\frac12}\approx\sqrt{x}+\frac{ir}{2\sqrt{x}}$$ and $$(x-ir)^{\frac12}\approx-\sqrt{x}+\frac{ir}{2\sqrt{x}}$$ for $x>r$. Thus the integrals over the segments from $r+ir$ to $R+ir$ and from $R-ir$ to $r-ir$ approximate twice the searched for integral value.

For a more boring region substitute $x=e^u$ to get the transformed integral
$$
\int_{-\infty}^\infty \frac{e^{\frac32 u}}{1+e^{2u}}du
$$
Now integrate along the contour of the box $[-R,R]+i[0,\pi]$. The integration along the upper side has the integrand for $w=u+i\pi$ so that
$$
f(w)=\frac{-i\,e^{\frac32 u}}{1+e^{2u}}
$$
plus orientation reversal,
the left and right sides are of size $e^{-R/2}$, so that the limit $R\to\infty$ of the contour integral is $(1+i)$ times the required value, and the only pole is at $w=i\frac\pi2$.

A: As an alternative approach, you may just remove the branch point by enforcing the substitution $x=z^2$, leaving you with
$$ \int_{-\infty}^{+\infty}\frac{z^2}{z^4+1}\,dz = 2\pi i\sum_{k\in\{1,3\}}\text{Res}\left(\frac{z^2}{z^4+1},z=e^{\pi i k/4}\right)=\color{blue}{\frac{\pi}{\sqrt{2}}}. $$
For a real-analytic approach, the substitution $\frac{1}{x^2+1}=u$ directly leaves you with the value of a Beta function.


Q: HTML - Send email without open new windows in Outlook I send an email to a client that contains a button that must be pressed to send a user's cofee.
Pressing the button opens a new Outlook window and then the user must click on SEND
I would like the new window not to be opened but automatically the email must be sent without any confirmation.
is it possible to do this?
Thanks


Q: Success on emulator, Force stop on real device I deployed an application for Android which is successfully running on emulator.
But, when I try to run on real device (My device is Acer A200, tablet), my application always forced stop. The requirement of the operating system is no problem.
The error in logcat when I tried to run on real device is :
07-16 15:09:20.870: I/SqliteDatabaseCpp(780): sqlite returned: error code = 1, msg = no such table: kategori, db=/data/data/com.mroring.belajarperancis/databases/MY_DATABASE

I think the application didn't install the database correctly. What should I do ?
Thanks in advance :)

A: table name "kategori" does not exist on your database, you should check the code if you created the table or not. if created, change the version number of the database, It will call the onUpgrade method and the database will create again.


Q: Field $K$ with $\operatorname{Gal}(\overline{K}/K)\simeq\widehat{F_2}$ Is there a field K such that $\operatorname{Gal}(\overline{K}/K)$ is the profinite free group with two generators?
For one generator I know that for all the $\mathbb{F}_p$ we have $\operatorname{Gal}(\overline{\mathbb{F}_p}/\mathbb{F}_p)\simeq\widehat{\mathbb{Z}}$.

A: Yes, there is. In fact, for every projective profinite group $G$, there is a perfect and  pseudo-algebraically closed field whose absolute Galois group is $G$.
You may want to check corollary 23.1.2 of Field Arithmetic by Fried and Jarden for a proof.


Q: Filter a list of data using a select box in Blazor I have a table called SchoolsTable and there is a view that will show all the records that have been entered. Here is the my model:
 public partial class SchoolsTable
    {
        public int Id{ get; set; }
        public int Name{ get; set; }
        public int State{ get; set; }
    }

What I want to do is have a dropdown in that view that will let me select a State and the data shown on the view will only be those that have the corresponding state.
The razor component:

           Schools
          @foreach (var item in school)
          {
        @item.Name
        @item.State
          }

@code{
    private List<SchoolTable> schools=new List <SchoolTable>();
    private SchoolTable school= new SchoolTable();
    protected override async Task OnInitializedAsync()
    {
        GetSchoolTable();

    }
    private List<SchoolTable> GetSchoolTable()
    {
        schools= SchoolService.GetSchoolTable();
        return schools;
    }
}

the select gets all the states as duplicates:
Choose a State:
<select name="State">
    @foreach (var item in schools)
    {
        <option value="@item.State">@item.State</option>
    }
</select>

additionally, I have created a state table which has 2 records in them:
 public partial class StatesTable
        {
            public int Id{ get; set; }
            public int Description{ get; set; }
        }

using this select, gets the states as singles and no duplicate states
Choose a State:
<select name="State">
    @foreach (var item in branch)
    {
        <option value="@item.Id">@item.Description</option>
    }
</select>

A: You need to do a couple of things.
First you need to bind the selected value of your <select> element to a field. For that you need to use the @bind attribute:
Choose a State:
<select id="State" @bind="selectedState">
    <option value="">Choose a state</option>
    @foreach (var item in branch)
    {
        <option value="@item.Id">@item.Description</option>
    }
</select>

@code {
    private int? selectedState;
}

Also add an option with empty value in your select so that by default no state is selected:
<option value="">Choose a state</option>

Now you can create a property that returns the filtered schools based on the selected state:
private List<SchoolTable> FilteredSchools => selectedState.HasValue ?
    schools.Where(s => s.State == selectedState.Value).ToList() :
    schools;

Use this property to generate the
 element content:
Choose a State:
<select id="State" @bind="selectedState">
    <option value="">Choose a state</option>
    @foreach (var item in branch)
    {
        <option value="@item.Id">@item.Description</option>
    }
</select>

        Schools
        @foreach (var item in FilteredSchools)
        {
            @item.Name
            @item.State
        }

@code{
    private List<SchoolTable> schools = new List<SchoolTable>();
    private int? selectedState;

    private List<SchoolTable> FilteredSchools => selectedState.HasValue ?
        schools.Where(s => s.State == selectedState.Value).ToList() :
        schools;

    protected override void OnInitialized()
    {
        schools = SchoolService.GetSchoolTable();
    }
}


Q: Comentário em tabela MySQL É possível inserir um comentário na tabela igual ao comentário em um campo da tabela?
Estou precisando inserir informações de até 160 caracteres nas tabelas do banco de dados para ajudar os outros devs a ter um breve resumo do que se trata cada uma delas, sei fazer em campos mas não encontrei nada sobre as tabelas.

A: Você pode adicionar um comentário na tabela alterando-a:
ALTER TABLE tabela COMMENT = 'Comentário da tabela';

E pode ler o comentário com a seguinte query:
SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tabela';


Q: FileNotFoundException when restarting the app I don't know why but I get an FileNotFoundException from my Init() function.
What's happening is, when I launch the app for the first time, it's normal to get one (the file does not exist). Then I press a button which calls Save and so creates the file (if I add a Log just after outputStream.close(), I'm able to see it). I actually tried to open the created file with a FileInputStream and I didn't get the exception.
But. When I close the app and open it again. I get the FileNotFoundException. Any idea why ?
public class MyClass {
    public static Context mContext ;
    public static void Save(){
        String test = "test" ;
        FileOutputStream outputStream;
        try {
            outputStream = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            outputStream.write(test.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Init(Context c){
        mContext = c ;
        FileInputStream inputStream;
        try {
            inputStream = c.openFileInput(FILENAME);
            String test = "";
            char ch ;
            while((ch=(char) inputStream.read())!=-1)
                test+= ch ;
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Edit :
So, those calls are not in an activity but in a static class. Init is called from onCreate of my main activity. Save is called from onPause of another activity. Hope that helps.


Q: Convex or Concave Function the problem is: Is the function $\phi(f)=\frac{\sqrt{f}}{2}\cdot\log f$ for $f\in L^2(\mathbb{R}_{>0})$ convex or concave.
My idee or  presumption is, that the function $\phi$ is concave, because we have the inequalitiy\[\sqrt{\alpha\cdot f+(1-\alpha)\cdot g}\geq \alpha\cdot \sqrt{f}+(1-\alpha)\cdot\sqrt{g}\quad\text{for}~\alpha\in(0,1).\]

A: Waht i have so far for $\phi:\mathbb{R}_{>0}\to\mathbb{R}$ with $f\mapsto \phi(f)$
$\begin{align*}
-\phi(\alpha\cdot f+(1-\alpha)\cdot g)&=-\sqrt{\alpha\cdot f+(1-\alpha)\cdot g}\log(\alpha\cdot f+(1-\alpha)\cdot g)\\
&\leq -(\alpha\sqrt f+(1-\alpha) \sqrt{g})\log(f^{\alpha}g^{(1-\alpha)})\\
&=-\left[(\alpha\sqrt f+(1-\alpha) \sqrt{g})(\alpha\log(f)+(1-\alpha)\log(g))\right]\\
&=-[\alpha^2\sqrt{f}\log(f)+\alpha(1-\alpha)\sqrt{f}\log(g)+\alpha(1-\alpha)\sqrt{g}\log(f)\\
&+(1-\alpha)^2\sqrt{g}\log(g)]\\
&=...
\end{align*}$


Q: AngularJS ng-cloak: empty page is displaying in IE9 when browser cache is cleared I just encountered a weird issue on angular's ng-cloak. When I cleared my IE9 browser's cache and close and open my browser again, when i accessed the page, it display empty page :( but when i tried to refresh the page it the page is now displaying.


Q: Jquery compare data/object differences on checked I'm trying to make a checkbox to hihglight the differences between data inside a div rather than table.
So if row has differences "Single, Single, Married" this should be highlighted.
http://jsfiddle.net/Ly61u493/1/
Logic:
$('.check-diff').click(function() {
if($(this).prop('checked')){
    //highlight status except header
    alert("Bang highlight it...");
} else{
    //unchecked should remove the highlight areas
    alert("Not highlighted");
}
});

    Click to see differences
<input type="checkbox" class="check-diff">

Name

John

Henry

Kim

Status

Single

Married

Single

Car

Yes

Yes

Yes

A: how about the following jquery code?
$('.check-diff').click(function() {
if($(this).prop('checked')){
    checkDiff();
} else{
    $(".row").each(function(){
        $(this).css("background-color","#fff");
    });
}
});

function checkDiff(){
$(".row").each(function(){
    var diff = false;
    var source = $(this).find(".diff").first().text();
    $(this).find(".diff").each(function(){
        var compare = $(this).text();
        if(source != compare){
           diff = true;
        }
    });
    if(diff == true){
        $(this).css("background-color","red");
    }
 });
}

hope i got you right and you get an idea, how to move on! :)

A: You can use 2 each loops and a class name for the rows you want to check. Only row that has a class name checkDiff will be validated and cells that has a class name diff.
JSnippet DEMO - validate difference in rows base on the cell text
JS:
$(function(){

    $('.check-diff').click(function() {
        if($(this).prop('checked')){
            $('.row.checkDiff').each(function(i,ele){
                var values = $(ele).find('.diff');
                var first = values.eq(0).text();
                var diff = false;
                values.each(function(j,e){
                    if ($(e).text() !== first) diff = true;
                });
                if (diff) $(ele).addClass('highlight');
            });
        } else{
            $('.row.checkDiff').removeClass('highlight');
        }
    });

});

HTML:
Click to see differences
<input type="checkbox" class="check-diff">

Name

John

Henry

Kim

Status

Single

Married

Single

Car

Yes

Yes

Yes

Kids

Yes

Yes

No

Home

Yes

Yes

Yes


Q: measurable selection and values of optimization problem In general, my problem can be formulated as follows: Let $X$ be a random variable with value in $\mathbb R^2$, and let $G:\mathbb R^2 \times \mathbb R\rightarrow \mathbb R$ be a function which is continuous in the first argument and measurable in the second(i.e., a Caratheodory function). Assume the partial maximization $x\mapsto \sup_yG(x,y)$ is measurable. I am considering the values given by
\begin{equation}
V_1=\sup\{\mathbb E(G(X,y(X))| y:\mathbb R^2\rightarrow \mathbb R \: measurable\} \\
V_2=\mathbb E(\sup_{y\in\mathbb R}G(X,y))
\end{equation}
I would like to know if these two values are the same or not, assuming problem $V_1$ admits a maximizer.

In my original problem, the function $G$ is given by $G(x,y)=(x_1-f(y))(y-x_2)$, where $f:\mathbb R \rightarrow \mathbb R$ is a Borel measurable function. It seems that continuity of $G$ with respect to $y$ is quite crucial for the argmax correspondence $\Phi(x)=\{y:G(x,y)=sup_yG(x,y)\}$ to have a measurable selector. Unfortunately, this is something I do not have.
I would pretty much like to have a positive answer(i.e.,$V_1=V_2$), but a counter-example will be equally appreciated! Thanks!

A: Undery our assumptions, the argmax-correspondence need not even be nonempty-valued. But one can find almost-selections of an almost-argmax-correspondence, and that is enough.
Let $\epsilon>0$. Define the function $h$ by $h(x)=\sup_yG(x,y)$. By assumption, $h$ is measurable. Therefore, the set
$$B=\big\{(x,y)\mid G(x,y)>h(x)-\epsilon\big\}$$
is a Borel set such that no $x$-section is empty. By the von-Neumann selection theorem, there exist an analytically measurable selection $f$ of the crrespondece with graph $B$. Now an analytically measurable function is universally measurable, so $f$ is measurable with respect to the completion of the distribution of $X$. But then there must be a Borel measurable function $f'$ such that $f$ and $f'$ agree on a set of measure $1$ under the distribution of $X$.


Q: Detecting unused props passed in components in React I currently refactoring some old code and I'm curious if there's any way to detect parameters which are passed into the component but never actually used inside it? Without looking at all the places where the component is called and checking manually.
Eg. detecting that name and age are not used inside the Greet component so can be deleted.
export default function Greet ({ greeting }) {
  return (
    <h1>{greeting}</h1>
  )
}

<Greet greeting="Hello Word" name="David" age="100"/>

A: TypeScript will warn you if you try to pass unknown props.
Eslint will warn you if you have unused variables, imports ...
with rules like:

*

*no-unused-expressions

*no-unused-vars

*react/no-unused-prop-types

*unused-imports


Q: How to access Windows.Services.Store from Java application We have a Java application that we publish in the Windows Store.  We would like to implement in-app purchases, for which we need to use the Windows.Services.Store API.
How can we access the Windows.Services.Store API from Java?


Q: HTML5 swipe.js css3 transitions; offscreen rendering and caching of page elements I am building a HTML5 magazine for tablets and desktops with use of swipe.js (http://swipejs.com).
Everything seems to work fine, In one HTML page I have set next to each other fullscreen list elements. The whole magazine is build up in one static html file. I can slide through the pages by swiping on tablets, and by using buttons for the desktop version (consider the example on the swipe.js homepage, but then with fullscreen slides).
The pages are placed next to each other, and have the dimensions of the screen.
[ |0||1||2| .. |i-1||i||i+1| .. |n| ]

The swipe.js transitions are done with help of css3, using the translate3d() css function. In this case, hardware rendering is used.
On desktop (Chrome, Safari, FF), iPad1 and (even better on) iPad2 this has the desired effect I was looking for; smooth transitions. Perfect!
However, on the iPad3, the pages seem to render 'slow' when entered (by transition) for the first time. Even without setting background images (just the color), the 'rendering' of the transitioned page is considered a little 'slow'; the page is build up by 'flickering' blocks.
Assumption:
My assumption is (after reading into the subject), that this is because the browser only renders the elements that are in-screen, and will cache the swiped pages only for a while, cleaning the cache afterwards to control memory management.
My question: Is there a way to control the offscreen rendering and caching, so that I can force (pre) render page elements i-1, i+1 (and flush the cache for all other page elements), to speed up my transition rendering?
Note: In several topics on StackOverflow, 'flickering' of css3 transitions is mentioned. I have implemented the suggested CSS tricks but will not solve my case.
-webkit-backface-visibility: hidden;
-webkit-transform:translate3d(0,0,0);

A: In the end the solution was a hack of Swipejs in which I added a method 'hideOthers()', setting the style visibility to 'hidden', which unloads the pages from hardware memory:
hideOthers: function(index) {
  var i = 0;
  var el;

  for( i in this.slides ) {
      el = this.slides[i];
      if ( el.tagName == 'LI' ) {
          // Show pages i-1, i and i+1
          if ( parseInt(i) == index
             || (parseInt(i) + 1) == index
             || (parseInt(i) - 1) == index
          ) {
              el.style.visibility = 'visible';
          }
          else {
              el.style.visibility = 'hidden';
          }
      }
   }
}

..and added the trigger below as last line in the 'slide()' method
// unload list elements from memory
var self = this;
setTimeout( function() { self.hideOthers(index); }, 100 );

Only the translate3d was needed to toggle the hardware acceleration on (as mentioned in my question above):
-webkit-transform:translate3d(0,0,0);

You can find the result (including iScroll for vertical scrolling) here.

A: in regards to the webkit backface/translate3d props used to trigger hardware acceleration, I've read that in iOS 6+ these don't work quite the same as in previous versions, and (more importantly) that hardware acceleration needs to be applied not only on the element that is being animated, but also on any element that it is overlapping/overlaps it.
reference (not much): http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/
To be fair this is fairly anecdotal, I was myself unable to fix my own flickering issue - due to tight deadlines - but this might be a point in the right direction.


Q: AngularJS Form data is not defined In AngularJS, I have a form, that when submitted, passes data off to a controller and sends it to an API.
Form:
 <form ng-submit="newCompany()">

                ID<input type="text" name="id" id="id" ng-model="newCompany.id" tabindex="1" class="form-control">
                Name<input type="text" name="name" id="name" tabindex="2" ng-model="newCompany.name" class="form-control">
                Primary Contact<input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control">
                Address<input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control">
                Function<input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control">
                Telephone<input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control">
                Fax<input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control">
                URL<input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control">

                        <input type="submit" name="add-submit" id="add-submit" tabindex="10" class="form-control btn btn-primary" value="Add Company">

{{ addCompany }}

        </form>

And the controller...
app.controller("CompaniesController", ['$scope', 'Companies', function($scope, Companies) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

   $scope.companyData = {
       id: $scope.newCompany.id,
       name: $scope.newCompany.name,
       primary_contact: $scope.newCompany.primary_contact,
       address: $scope.newCompany.address,
       function: $scope.newCompany.function,
       telephone: $scope.newCompany.phone,
       fax: $scope.newCompany.fax,
       url: $scope.newCompany.url
   };

    $scope.newCompany = function() {
        var company = new Companies($scope.companyData);
        company.$save();
    };

    $scope.companies = Companies.query();
}]);

However - I get an error that says "cannot read property 'id' of undefined"
Does anybody know what is wrong here? I thought $scope.[NG-MODEL] gets the form data...

A: *

*You have a $scope.newCompany variable which is a function, not an object.

*When you initialize $scope.companyData, you call  id: $scope.newCompany.id, where $scope.newCompany is undefined. Try define it first with all its properties ($scope.newCompany = {
id : "",
...
})

*Call your submit function something else.

*Do not create a function whose name itself a 'function'. (function: $scope.newCompany.function). This is reserved as a keyword.
These steps may be close to the result you want to see, if not reply back.


Q: Are probes loaded and launched manually or automatically in Starfleet vessels? Many times we see the Captain of a Starfleet vessel ask for a probe to be launched in order to scan/examine some debris/star/anomaly/planet etc. Then a member of the crew, usually at the science or tactical stations, press a few buttons on their panels and moments later the probe is launched.
However, we never see what happens from the moment the crew "orders" the probe (by entering some command in the panel) and the launch itself. Does the command get forwarded to some crewmen in the lower decks who are responsible for maintaining the probes, who then load them and proceed with the launch or does the whole thing happen "automagically"?
So, my question is: are these probes loaded and launched manually or automatically in Starfleet vessels?
I'm only interested in the TNG era (TNG/DS9/VOY) and in both canon and expanded universe.

A: From Memory Alpha:

In addition to sensors, Galaxy-class ships were equipped with a variety of probes and scientific devices that could be launched from the torpedo launchers. These included basic scanner probes and reconnaissance probes, class-A probes and probes from class-1 to class-5. (TNG: "Where Silence Has Lease", "Force of Nature", "Ship in a Bottle", "Chain of Command, Part I")

There was a standard compliment of probes on Starfleet ships, which could be fired easily (and interchangeably) through the torpedo tubes. On some instances, however, a probe would have to be modified from its "stock" configuration before it could be launched.
From Memory Alpha:

When the preliminary readings were inconclusive, and Data couldn't detect abnormalities in Gamma Arigulon's radiant energy, Captain Jean-Luc Picard gave the order to prepare two class-1 probes. However, before the probes were launched, a Klingon attack cruiser de-cloaked, and the captain stopped the launch. (TNG: "Reunion")

and (Memory Alpha):

Some probes used by Starfleet were modified photon torpedo casings with extended sensor equipment and no warhead. (TNG: "The Emissary"; Star Trek Generations)

As to the process of launching the probe (Memory Alpha... again):

Tubes could be controlled from the bridge or from the torpedo bay. (ENT: "Silent Enemy")

This would apply for "stock" torpedoes and probes which would be loaded and prepped automatically.
From You Know Where:

Vessels in the 24th century were also equipped with automated torpedo bays. (TNG: "In Theory") Even though 24th century torpedo bays were automated, they could still be modified for manual launch.

A: The TNG Technical Manual indicates that standard probes are stored in the vicinity of the launcher for immediate use. Since the probes have to be loaded into the launch elevator (and are then ejected by the ship through the probe port via magnetic acceleration) it stands to reason that they have to be loaded manually by dedicated crews.

The following section lists the specifications of each class. The
  higher class numbers are not intended to imply greater capabilities,
  but rather different options available to the command crew when
  ordering a probe launch. General use probes readied for immediate
  launching are stored adjacent to the photon torpedo reactant loading
  area on Deck 25. Other standby probes are stored on Deck 26 on
  standard torpedo transfer pallets. All probes are accessible to
  Engineering crews for periodic status checks and modifications for
  unique applications.

A diagram is provided to help you visualise the chain of events.


Q: Linux iptables script to block all internet access except for desired applications CONTEXT:
I wanted to have a shell script that would block all Inbound/Outbound traffic to my computer, UNLESS I decide I want to use the browser or some other application, in which case I would summon it and only those applications would run.
I have researched previous scripts made by smart individuals (links to sources at the end), as well as invested the time to learn to use iptables myself (still working on this front).
Here is the result of the work done:
RESULTS:
before the shell script is run, a group called internet is created:
sudo groupadd internet
Shell Script:
#!/bin/sh
#only allow apps run from "internet" group to run

# clear previous rules
sudo iptables -F

# accept packets for internet group
sudo iptables -A OUTPUT -p tcp -m owner --gid-owner internet -j ACCEPT
sudo iptables -A OUTPUT -p udp -m owner --gid-owner internet -j ACCEPT

# also allow local connections
sudo iptables -A OUTPUT -p tcp -d 127.0.0.1 -j ACCEPT
sudo iptables -A OUTPUT -p tcp -d 192.168.0.1/24 -j ACCEPT

# reject packets for other users
sudo iptables -A OUTPUT -j REJECT

# same process for IPv6:
sudo ip6tables -A OUTPUT -p tcp -m owner --gid-owner internet -j ACCEPT
sudo ip6tables -A OUTPUT -p udp -m owner --gid-owner internet -j ACCEPT
sudo ip6tables -A OUTPUT -p tcp -d 127.0.0.1 -j ACCEPT
sudo ip6tables -A OUTPUT -p tcp -d 192.168.0.1/24 -j ACCEPT
sudo ip6tables -A OUTPUT -j REJECT

this is the other part of the shell that I'm currently working on and not 100% confident with:
#DROPS ALL INPUT and FORWARD
sudo iptables -A INPUT -j DROP
sudo iptables -A FORWARD -j DROP

#ONLY ACCEPTS INPUT THAT WAS INITIATED BY SOME OUTPUT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#SAME REPEATED FOR IPv6
sudo ip6tables -A INPUT -j DROP
sudo ip6tables -A FORWARD -j DROP
sudo ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

after the whole script above is executed, the following command would open a terminal that would be part of the internet group, and hence any application (like firefox for instance) that were open by that terminal would have internet access, while all other INPUT/OUTPUT would be stopped
sudo -g internet -s

QUESTION:
Is the previous logic in order? Currently I am working on testing out all the features, by installing network monitoring software (nethogs), testing each line of code and seeing if the result is as expected, BUT at the same time, I only started learning about iptables 2 days ago, so even though the sources of the original code is done by experienced coders, I am not 100% confident in my ability to put it all together to produced the desired result. Thanks to anyone who took the time to read all this and participate in the discussion !!!
sources:
https://plus.google.com/+TobyKurien/posts/YZhZJCZmGgm
https://serverfault.com/questions/429400/iptables-rule-to-allow-all-outbound-locally-originating-traffic
P.S.: Thanks to @dirkt for previously helping me understand a lot of the fundamental concepts of iptables as well as answering some of my questions regarding the source code.

UPDATE:
So after having run the code, there seems to be something wrong. What happens is as follows. I run the shell script:
bash myscript

I get 2 errors as follows:

ip6tables v1.6.0: host/network 127.0.0.1 not found
  Try `ip6tables -h' or 'ip6tables --help' for more information.
ip6tables v1.6.0: host/network 198.168.0.1 not found
  Try `ip6tables -h' or 'ip6tables --help' for more information.

but everything else ran well, and when doing sudo iptables -L I did confirm all the other rules are in place. AFTER that, I tried the following:

*

*Run firefox by manually double-clicking the icon. The result was as expected, right away I got a Server not found error, which was a good sign

*After that I ran the command sudo -g internet -s in the terminal, and then firefox. NOW... when I tried loading a website, it didn't show me Server not found, but it keep loading for a long period of time, very long. This leads me to believe that maybe the output response was sent, BUT the input was being blocked.

If anyone knows why this might be happening, I would love to know your feedback!


Q: How to switch to another branch while recursively initing submodules I have a git repository with several submodules (see an example). Its structure looks like this:
I--A--B <- main
       \
        C <- branch-c

*

*Commit A adds a submodule-a

*Commit B adds a submodule-b

*Commit C adds a submodule-c on branch branch-c
When I clone the above repo using
git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned.
When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint.
When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error:
fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c
fatal: could not reset submodule index

How do I check out (or switch to) branch branch-c while automatically initialising all submodules?

A: Your example repository is lacking a branch-c, so it's not a complete MCVE, but it's a good start :)

When I clone the above repo using git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned.

Yes, this is the current behaviour of git clone --recurse-submodules. The submodules are cloned and initialized using an invocation of git submodule update --init --recursive during the checkout phase of git clone, and as such, only submodules recorded in the default branch (or the branch specified using git clone -b <branch>) are cloned and initialized.

When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint.

Yes, this is unfortunately still the default behaviour of Git. Submodules working trees are not checked out by default by git checkout <branch>. git submodule status (or just git submodule) will show uninitialized submodules with a - prefixed.

When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error:
fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c
fatal: could not reset submodule index

This is a good reflex but unfortunately it does not work in that specific case and leads to this bad UX. git checkout --recurse-submodules <branch> assumes that every submodule recorded in branch-c are already initialized. Since that's not the case here, it errors out because it can't find the .git directory of the submodule. The message could be clearer. What you have to do (the first time you switch to branch-c after cloning your repository) is to check out branch-c non-recursively, and then initialize the submodule:
git checkout branch-c
git submodule update --init --recursive

Then, you will be able to correctly switch between your branches with --recurse-submodules:
git checkout --recurse-submodules main
git checkout --recurse-submodules branch-c
# etc

Note that you can set submodule.recurse in your config to avoid having to use --recurse-submodules all the time.


Q: Phone emulator in Visual Studio 2015 RC on Windows 10 preview build 10074 does not work I had some problem in running some Phone of the emulators in VS2015 RC so I tried to install also the "Pre-release Microsoft Emulator for Windows 10 Mobile" and then also the external SDK ...
Now, even thought I uninstalled the external Windows 10 SDK and made a "repair" of VS2015 RC, no one of the phone emulators stars (it goes till the "OS is starting" phase and then remain in that state till, after many minutes, the emulator crashes and some time a popup says "The emulator is unable to get the sensor states from the device: Operation failed because connection is shut down", ... most of the times no error is reported).
I also tried to delete in the Hyper-V manager both the created emulators virtual machines and the related  Virtual Switches related to Windows Phone Emulator Internal: these are recreated at the next run of the emulator from VS, but nothing changed ...
Any suggestion? How can I make at least some of the phone emulators work properly?
Regards
Enzo


Q: Check File Extension in android i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed.
Here is Code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView filecheck;

        filecheck = (TextView) findViewById(R.id.filecheck);

        filecheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (accept()) {
                    Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public boolean accept() {
        final File pathname = new File("/sdcard/test/");
        String files[] = pathname.list();
        System.out.println(files.length);
        for (String s : files) {
            if (s.contains(".mp4")) {
                System.out.println(s);
                return true;
            }
            return false;
        }
        return false;
    }
}

Here is exception:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: jss.testmethods, PID: 23659
                  java.lang.NullPointerException
                      at jss.testmethods.MainActivity.accept(MainActivity.java:38)
                      at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
                      at android.view.View.performClick(View.java:4478)
                      at android.view.View$PerformClick.run(View.java:18698)
                      at android.os.Handler.handleCallback(Handler.java:733)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:149)
                      at android.app.ActivityThread.main(ActivityThread.java:5257)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                      at dalvik.system.NativeStart.main(Native Method)

A: i was expecting simple error, i missed to add permission for read storage. it is working now.


Q: How do I define custom comparison (0 < mytype) in python? So I'm currently (ab)using python notation to create a domain specific language. As part of this I'm overriding comparison functions to return non-boolean values.
So, for (mytype1 < mytype2) and (mytype < 0) I can easily do this by defining the __lt__() magic method.
However, I cannot figure out how to do so for (0 < mytype) as presumably the magic method would need to be defined on the built-in int type. There doesn't seem to be a __rlt__() function as exists for numeric operations.
How do I add support for this comparison where the lhs is of type int (in python3)?

A: As per the documentation the reflected form of __lt__() is __gt__().

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.


Q: iOS SDK - using @2x, and icons.. where do they go? I have been developing my app for about a week and have loaded some images into it.
I noticed that you can put an image into the app and it scales correctly.  I have some larger images that have scaled down and look great.
I guess this is discouraged because it takes some processing power or memory correct?  Okay, so I want to scale my images to their actual size.
Let's say I have a button that is 40x50
Should that be the @2x size, or should I double that, and set that to the @2x size?
Second question is:  I read apple guidelines about submissions to the app store, and it looks like you need to submit a plethora of icons.  I know you can apply a retina icon, and a regular icon when setting up your project.  What about the rest.  do you just use their naming guidelines and dump them into your project somewhere?

A:
should that be the @2x size, or should I double that, and set that to the @2x size?

Listen to your intuition. It's not called image@0.5x but image@2x...

do you just use their naming guidelines and dump them into your project somewhere?

After your graphics designer has sent you the necessary files, yes. But not just "somewhere". Rather into the root of your app bundle.


Q: Swift iOS 13 : Click on push notification how to open textfield? User want to interact on click of push notification and send comment/reply/message.
I have following code in AppDelegate:
     func configureNotification() {
        let center = UNUserNotificationCenter.current()

        center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }

        center.delegate = notificationDelegate

        let replyAction = UNTextInputNotificationAction(identifier: replyID, title: "Add reply", options: [], textInputButtonTitle: "Send", textInputPlaceholder: "Reply here")

        let deafultCategory = UNNotificationCategory(identifier: "CustomSamplePush", actions: [replyAction], intentIdentifiers: [], options: [])
        center.setNotificationCategories(Set([deafultCategory]))

        UIApplication.shared.registerForRemoteNotifications()
    }

And Handle action like following:
 func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let identifier = response.actionIdentifier
               let request = response.notification.request

        if identifier == replyID{
            let textResponse = response as! UNTextInputNotificationResponse
            let newContent = request.content.mutableCopy() as! UNMutableNotificationContent
            newContent.body = textResponse.userText
            addNotification(content: newContent, trigger: request.trigger, indentifier: request.identifier)
        }

        completionHandler()
    }

    func addNotification(content:UNNotificationContent,trigger:UNNotificationTrigger?, indentifier:String){
        let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: {
            (errorObject) in
            if let error = errorObject{
                print("Error \(error.localizedDescription) in notification \(indentifier)")
            }
        })
    }

FYI : This code perfectly run for iOS 11 device but not working in iOS 13


Q: unable to read lines of log file I have an AWS S3 bucket with a bunch of log files in them. I have a lambda function using node.js 8.10 runtime that reads each line of the log file. This is what I have:
const readline = require('readline');

exports.handler = async (event) => {
    try {

        let bucket = event.Records[0].s3.bucket.name;
        let key = event.Records[0].s3.object.key;

        // documentation for this method:
        // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property
        let readStream = S3.getObject({ Bucket: bucket, Key: key }).createReadStream();  // 1

        const rl = readline.createInterface({
                input:  readStream
        });

        rl.on('line', async (line) => {
            console.log(line);
            // process line as needed
        });

    } catch (err) {
        console.log(err);
        return err;
    }
};

In the snippet above I'm printing the line in the log file to the console just for testing, but I don't see any output.
But if I refactor the code like this it works:
const stream = require('stream');
const bufferStream = new stream.PassThrough();
const readline = require('readline');

exports.handler = async (event) => {
    try {
        // retrieving first record only just for
        // testing
        let bucket = event.Records[0].s3.bucket.name;
        let key = event.Records[0].s3.object.key;

        // data.Body is a Buffer
        let data = await S3.getObject({ Bucket: bucket, Key: key }).promise();
        bufferStream.end(data.Body);   // 2

        const rl = readline.createInterface({
                input:  bufferStream
        });

        rl.on('line', (line) => {
            console.log(line);
            // process line as needed
        });

    } catch (err) {
        console.log(err);
        return err;
    }
};

For the line marked 2, the getObject function returns a buffer and is converted to a stream.
Is it possible to do this without using a buffer? My thinking is if the log file is very large it is inefficient to convert a buffer to a stream. I'm wondering if I can use a stream directly like the line marked 1.
EDIT:
I did some more testing and got it to work but without an async lambda function.  Here it is:
exports.handler = function (event, context, callback) {
        // for testing I'm looking at the first record
        let bucket = event.Records[0].s3.bucket.name;
        let key = event.Records[0].s3.object.key;

        const readStream = S3.getObject({ Bucket: bucket, Key: key }).createReadStream();

        const rl = readline.createInterface({
            input:  readStream,
            crlfDelay: Infinity
        });

        rl.on('line', (line) => {
            console.log(line);

        });
}

Does anyone know why this refactored code works, but not with async lambda ?


Q: AngularJS: Ng:init - how to assign ng:model? I have ng:repeat, created by json (methods), inside it creates a series of radio buttons that are characterized by iteration (method).
Below, I need to create a variable that will be based on method selected radio button, for use in the future. I will prepare the template for clarity.

    <input type="radio" ng:model="$parent.deliveryMethod" ng:value="method" />

I hope the point is clear. The problem is, as I understand it, ng:init is triggered earlier than time to form methods.
What I must to do?
Thanks!

A: You're syntax looks incorrect , You should be declaring ng- as listed below :
ng-repeat
ng-model
ng-init
ng-bind

ect...
docs here: https://docs.angularjs.org/api/ng/directive/ngRepeat
upadte - to apply method to radio button try ng-change :
ng-change="dosomething()"


Q: What errors can WebSocket emit? Is there a list of all possible error events a js websocket client can emit? Are the errors spec'ed or are they implementation dependent?
webSocket.on('error', (event) => ...) // What can event be?

A: here is a list of Websocket errors codes that you might receive.
websocket-close-codes
Most likely you'll receive 1006 in case of an exception

A: Browser-side error events are actually related to "close codes" used by the WebSocket protocol, as detailed in section 11.7 to the RFC.
You can find the registered WebSocket closure codes here.
In addition to server-side specified errors, some parsing errors and protocol errors are also emitted by the client (such as UTF-8 requirements)... which are often mapped to a closure code (UTF-8 is mapped to code 1003).
AFAIK, these closure error codes are actually sent to the onclose callback, as part of the close event. (i.e., close_event.code). However, according to MDN when the closure isn't normal (code 1000), the onerror callback is also called.
Personally I've never tested or coded anything with these error-codes, since they are unreliable and optional:

When closing an established connection (e.g., when sending a Close frame, after the opening handshake has completed), an endpoint MAY indicate a reason for closure.

Exposing these "error codes" is optional for a reason. Sending error codes from a server to a client / application could (potentially) expose security vulnerabilities.


Q: ORA-00060: Deadlock Trace file query found but can we get its parameter values As this ORA-00060 is quite famous and I too have analyzed it in past and have solved a few of them in past. In my case I have ensured there is no common update from multiple session, still the error was occurring, and for such solutions I have used to increase the initrans and frequent commit in the concurrent transactions have helped me to solve it.
Now in another program again I saw the ORA-00060. Then I analyze the .trc file. There it is showing the merge query running from two session which is causing deadlock. This query has bind parameters. I wanted to know the values of this bind parameter. Because if by any bug if this binding parameter is same from the two session then it will be obvious that the two sessions are updating the same records, and eventually causing the deadlock.
Where I am struggling is that I am not able to see any way to get the value of these bind parameter in the .trc file. The call stack trace in the .trc file does have some blocks but very difficult to figure out where and what is the value of this parameter when the deadlock graph was created. Does anyone know whether it is possible to get the bind parameter values from .trc file for the queries causing the deadlock? I have started putting the log in the code so that next time when it occurs I will get that from normal logs.
Deadlock graph:
------------Blocker(s)-----------  ------------Waiter(s)------------
Resource Name                             process session holds waits serial  process session holds waits serial TX-0012000B-0004A991-00000000-00000000        193     203     X         7643     195     583           S  11914 TX-000F000E-000871FC-00000000-00000000        195     583     X        11914     193     203           S   7643
The query (table/column names I have changed) is:
----- Information for waiting sessions -----
Session 203:
sid: 203 ser: 7643 audsid: 38682755 user: 151/SCHMEA1
...
pid: 193 O/S info: user: grid, term: UNKNOWN, ospid: 11010512
image: oracle@hostname
client details:
...
application name: JDBC Thin Client, hash value=2546894660
current SQL:
MERGE INTO TABLE_A TA USING ZPD_TABL2 ZPD ON (TA.COY=ZPD.COY AND TA.COL2=ZPD.COL2 AND TA.TRXNO=ZPD.TRXNO AND (TA.COL3 = ' ' OR TA.COL3 IS NULL OR TA.COL3 = 'I') AND ZPD.THREADNO=:B1 ) WHEN MATCHED THEN UPDATE SET TA.COL3 = 'Y', TA.USRPRF=:B3 , TA.JOBNM=:B2 , TA.DATIME=LOCALTIMESTAMP

Session 583:
sid: 583 ser: 11914 audsid: 38682758 user: 151/VM1DTA
...
pid: 195 O/S info: user: grid, term: UNKNOWN, ospid: 58064926
image: oracle@hostname
client details:
..
application name: JDBC Thin Client, hash value=2546894660
current SQL:
MERGE INTO TABLE_A TA USING ZPD_TABL2 ZPD ON (TA.COY=ZPD.COY AND TA.COL2=ZPD.COL2 AND TA.TRXNO=ZPD.TRXNO AND (TA.COL3 = ' ' OR TA.COL3 IS NULL OR TA.COL3 = 'I') AND ZPD.THREADNO=:B1 ) WHEN MATCHED THEN UPDATE SET TA.COL3 = 'Y', TA.USRPRF=:B3 , TA.JOBNM=:B2 , TA.DATIME=LOCALTIMESTAMP

----- End of information for waiting sessions -----

So if I get the value of THREADNO =:B1 (this bind parameter) value from .trc file then I can confirm whether these two merge from two sessions are updating the same records or not.

A: One possible suspect constalation in your use case would be if the threadno is not uniquely mapped to the join keys used in the MERGE.
You may quickly check it with the query below - it should not return any row. If yes, you have a postential problem described later.
select COY, COL2, TRXNO, min(THREADNO), max(THREADNO)
from zpd_tabl2 zpd
group by COY, COL2, TRXNO
having count(distinct THREADNO) > 1;

Bind Variables Used in Dealock Statements
Well, the deadlock trace file contains some information
Peeked Binds
============
  Bind variable information
    position=1
    datatype(code)=2
    datatype(string)=NUMBER
    precision=0
    scale=0
    max length=22
    value=1

But this will not help you as it is the peeked value used while the statement was parsed.
Rows waited on
More usefull information is the rowid of the rows caused the problem
Rows waited on:
  Session 138: obj - rowid = 00012563 - AAASVjAARAAAACbAAB
  (dictionary objn - 75107, file - 17, block - 155, slot - 1)
  Session 12: obj - rowid = 00012563 - AAASVjAARAAAACbAAA
  (dictionary objn - 75107, file - 17, block - 155, slot - 0)

The object_id (here 75107) should point to your TABLE_A and you can check the threadnos that try to modify the problematic rows with the following query.
select a.rowid, a.COY, a.COL2, a.TRXNO , zpd.threadno
from table_a a
join zpd_tabl2 zpd
ON ( a.coy = zpd.coy
AND a.col2 = zpd.col2
AND a.trxno = zpd.trxno)
where a.rowid in ( 'AAASVjAARAAAACbAAB','AAASVjAARAAAACbAAA');

If you see at least four rows, that you suffer the threadnoproblem stated in the beginning.
Reproducible Example
Note, I can't claim that this is exact your situation, but this is the simplest way how to get a deadlock you observed.
create table table_a as
select rownum coy, rownum col2, rownum trxno, ' ' col3, localtimestamp datime
from dual
connect by level <= 2;

create table zpd_tabl2 as
select rownum coy, rownum col2, rownum trxno, 1 threadno
from dual
union all
select  rownum coy,  rownum col2,  rownum trxno, 2 threadno
from dual
union all
select 1+rownum coy, 1+rownum col2, 1+rownum trxno, 3 threadno
from dual
union all
select  1+rownum coy,  1+rownum col2,  1+rownum trxno, 4 threadno
from dual
;

*

*in Session 1 run the MERGE with pareter 1
.
MERGE  INTO table_a ta
USING zpd_tabl2 zpd ON ( ta.coy = zpd.coy
                         AND ta.col2 = zpd.col2
                         AND ta.trxno = zpd.trxno
                         AND ( ta.col3 = ' '
                               OR ta.col3 IS NULL
                               OR ta.col3 = 'I' )
                         AND zpd.threadno = :b1 )
WHEN MATCHED THEN UPDATE
SET ta.col3 = 'Y',
    ta.datime = localtimestamp;

 1 row merged

*

*in Session 2 run the MERGE with pareter 4
1 row merged

*

*in Session 1 run the MERGE with pareter 3
waiting

*

*in Session 2 run the MERGE with pareter 1
waiting

*

*in Session 1
ORA-00060: deadlock detected while waiting for resource


Q: Unable to rotate AVPlayerViewController when fullscreen The app I am working on has UIInterfaceOrientationPortrait set as UISupportedInterfaceOrientations.
I create an AV player like so:
let playerVC = AVPlayerViewController()
// Some AVPlayer input
playerVC.player = player
presentableViewController?.present(playerVC, animated: true, completion: nil)

The AVPlayerViewController works however when I enter fullscreen and try to rotate it remains fixed to portrait. I need the ability to rotate to landscape.
I tried subclassing AVPlayerViewController like so:
class AVPlayerViewControllerRotatable: AVPlayerViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        .all
    }
}

However this had no effect. What am I doing wrong here?


Q: Get Rectangle of Image JPG and generate thumbnail in rectangle I try explain: I have a JPG image (img A).
This A.jpg has contents -colors, it's a picture of persons- and a one more little white rectangle (color white; the head of person is a white rectangle). I need get the position of rectangle in A.jpg.
Then, I have another B.jpg image, more little; and I'll generate thumbnail of B.jpg , with Rectangle dimensions (of white rectangle in A.jpg).
Finally, I'll generate new image: C.jpg, will has A.jpg, and B.jpg in rectangle of A.jpg.
any suggestions, any sample code ? I use vs 2008, .net 3.5, GDI+ only.

A: For the A problem, you could count the number of white pixels in each column and each row. The columns/rows with the highest number of white pixels are where the borders of your rectangle are. (Assuming that the rectangle sides are parallel to the sides of the image)
For B and C the hint is to start with
Bitmap aImage; // Initialize with your images
using (Graphics g = Graphics.FromImage(aImage))
{
    // Do stuff
}

And then you can find and overload of Graphics.DrawImage to scale and draw your images atop of each other.
To count the number of pixels you can use the GetPixel method.
// Sketchy code
// Calculate each column in sum[x]
[x,y] = b.Size;
for(x ...)
    for(y ..)
        if (aImage.GetPixel(x, y) == Color.White)
            sum[x]++;

A: Here is a snippet on draing an image over another image. (No credit i took it from here)
Bitmap bmp = Bitmap.FromFile(initialFileName);

// This draws another image as an overlay on top of bmp in memory.
// There are additional forms of DrawImage; there are ways to fully specify the
// source and destination rectangles. Here, we just draw the overlay at position (0,0).

using (Graphics g = Graphics.FromImage(bmp))
{
   g.DrawImage(Bitmap.FromFile(overlayFileName), 0, 0);
}
bmp.Save(saveAsFileName, System.Drawing.Imaging.ImageFormat.Png);

Now on how to locate a large white rectangle inside an image? This bit is a little trickier.
There is a library which can do this for you