title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
How to view log output using docker-compose run?
|
<p>When I use <code>docker-compose up</code> I can see logs for all containers in my <code>docker-compose.yml</code> file.</p>
<p>However, when I use <code>docker-compose run app</code> I only see console output for <code>app</code> but none of the services that <code>app</code> depends on. How can see log output for the other services?</p>
| 0 |
How to add font awesome in CSS
|
<p>I am trying to add a an icon from font awesome but for some reason it does not appear when I load the page.
Below is my html code in which I attempted to add the font awesome in different ways.</p>
<pre><code><html lang="en">
<head>
<title>Media Queries</title>
<meta name="viewport" content="width=device-width, initial=scale1.0">
<link rel="stylesheet" href="main.css">
<link href='https://fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="font-awesome-4.6.3/css/font-awesome.min.css">
</head>
<body>
<i class="fa fa-car" aria-hidden="true"></i>
<h1>
<i class="fa fa-car" aria-hidden="true"></i>Dummy Text
</h1>
</body>
</html>
</code></pre>
<p>Is there anything that am missing in the code?</p>
| 0 |
Unable to require openssl, install OpenSSL and rebuild ruby (preferred) or use non-HTTPS sources
|
<p>I'm attempting to install <code>jekyll</code> and I've encountered an error. I'm running Mac OS X 10.11.4 (El Capitan).</p>
<pre><code>$gem install jekyll
ERROR : While executing gem ... (Gem::Exception)
Unable to require openssl, install OpenSSL and rebuild ruby (preferred) or use non-HTTPS sources
$gem source -l
https://ruby.taobao.org
$which openssl
/usr/local/bin/openssl
</code></pre>
<p>I welcome your suggestions how to resolve this error.</p>
| 0 |
Node JS Process out of memory
|
<p>I am using forever JS to run my node JS server continuously, however occasionally the server crashes and site goes down for some time.</p>
<p>I looked at the forever logs, and here it shows:</p>
<pre><code>FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
<--- Last few GCs --->
35251732 ms: Mark-sweep 687.6 (219898.0) -> 687.6 (527360.0) MB, 13522.0 / 0 ms [allocation failure] [scavenge might not succeed].
35267178 ms: Mark-sweep 687.6 (527360.0) -> 687.6 (940128.0) MB, 15445.8 / 0 ms [allocation failure] [scavenge might not succeed].
35282842 ms: Mark-sweep 687.6 (940128.0) -> 687.6 (1352896.0) MB, 15664.3 / 0 ms [last resort gc].
35298326 ms: Mark-sweep 687.6 (1352896.0) -> 687.6 (1765664.0) MB, 15483.8 / 0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0x82f80fa5a91 <JS Object>
2: decode(aka utf8decode) [/home/ubuntu/chat2/node_modules/socket.io/node_modules/engine.io/node_modules/engine.io-parser/node_modules/utf8/utf8.js:~200] [pc=0x19db242bd813] (this=0x1ea709fcc4c9 <an Object with map 0xedc29877b11>,byteString=0x1bd8952f0461 <Very long string[8570662]>)
3: decodePacket [/home/ubuntu/chat2/node_modules/socket.io/node_modules/engine.io/node_modules/engine.io-...
error: Forever detected script was killed by signal: SIGABRT
error: Script restart attempt #9
Server running at http://localhost:1337/
</code></pre>
<p>Here are some more errors I found in my console.log file causing node to crash:</p>
<pre><code>error: Forever detected script was killed by signal: SIGKILL
error: Script restart attempt #11
Error: read ECONNRESET
at exports._errnoException (util.js:870:11)
at TCP.onread (net.js:544:26)
RangeNotSatisfiableError: Range Not Satisfiable
at SendStream.error (/home/ubuntu/chat2/node_modules/express/node_modules/connect/node_modules/serve-static/node_modules/send/index.js:245:31)
at SendStream.send (/home/ubuntu/chat2/node_modules/express/node_modules/connect/node_modules/serve-static/node_modules/send/index.js:564:19)
at onstat (/home/ubuntu/chat2/node_modules/express/node_modules/connect/node_modules/serve-static/node_modules/send/index.js:624:10)
at FSReqWrap.oncomplete (fs.js:82:15)
</code></pre>
<p>Any idea on how to fix this? I can't seem to find the error ?</p>
| 0 |
Finding a disabled component of a gameobject and enabling it again
|
<p>I have a Key that disables a the MeshRenderer and the BoxCollider components of the current GameObject. After these are disabled and the user presses the same Key again, I want to enable these same components again but it does not seem to be able to find these components as they are disabled. How would I be able to find these two components and enable them again? Thanks in advance!<br>
Here is a link to the script that I am using (I disable the components on lines 27+28 inside of a function, and I am trying to enable them again on lines 36+37 inside of a function as well): <a href="https://gist.github.com/anonymous/702cf5630bfc7236ba52f6ec8d7cd7a4" rel="nofollow">https://gist.github.com/anonymous/702cf5630bfc7236ba52f6ec8d7cd7a4</a></p>
<p>Edit: Or maybe tell me what mistake I made.</p>
| 0 |
Alternative to Treeview in VBA excel 2016 64bit
|
<p>I am trying to run an excel with VBA that has treeview control in it. It is working fine in 32bit machines but on 64bit machine with excel 2016 it is not working,with the error, treeview component is not found. </p>
<p>Is there any other similar component which I can replace treeview with?</p>
| 0 |
Is it safe to delete ~/.cache/pip directory
|
<p>I have limited space on my server, and I am thinking to delete the cache of the PIP. I am not sure if its safe to delete or not.</p>
<pre><code>ls ~/.cache/pip/
</code></pre>
<p>Contains following dir/files.</p>
<pre><code>http selfcheck.json wheels
</code></pre>
<h2>Version</h2>
<pre><code>$ pip -V
pip 7.1.2 from /usr/local/lib/python2.7/dist-packages/pip-7.1.2-py2.7.egg (python 2.7)
</code></pre>
<p>Please advise. </p>
| 0 |
warning: discards 'const' qualifiers from pointer target type
|
<p>Doesn't <code>const char *s</code> means that "s is a pointer which is pointing towards a constant char " then why it is giving me this warning? I am not trying to change values. </p>
<p>In first function warning is <code>return discards 'const' qualifiers from pointer target type</code>.</p>
<p>and in second warning is <code>assignment discards 'const' qualifiers from pointer target type</code>.</p>
<p>I was trying to make library functions which are defined in <code>string.h</code>, and also tell me how to correct it.</p>
<pre><code>char *my_strchr( const char *s, int c )
{
for(;*s!='\0';s++)
if(*s==c)
return s; // warning
return 0;
}
char *my_strpbrk( const char *s1, const char *s2 )
{
char *s2ptr;
for(;*s1!='\0';s1++)
for(s2ptr=s2;*s2ptr!='\0';s2ptr++) //warning
if(*s1==*s2ptr)
return s2ptr;
return 0;
}
</code></pre>
| 0 |
How do i authenticate a rest call in firebase?
|
<p>I want to do a rest call on some data protected by some rule using the aid of my user, so i need to had the token to my request.
depending of which version of firebase documentation there is different way:
old and deprecated way (<a href="https://www.firebase.com/docs/rest/api/">https://www.firebase.com/docs/rest/api/</a>): </p>
<pre><code>'https://samplechat.firebaseio-demo.com/users/jack/name.json?auth=<TOKEN>'
</code></pre>
<p>new way and i m quoting the doc (<a href="https://firebase.google.com/docs/reference/rest/database/user-auth#section-get">https://firebase.google.com/docs/reference/rest/database/user-auth#section-get</a>): </p>
<blockquote>
<p>Using the access token
The Database REST API will accept access_token= on the query string or header Authenticate: Bearer to authenticate a request with a service account.</p>
</blockquote>
<pre><code>'https://samplechat.firebaseio-demo.com/users/jack/name.json?access_token=<TOKEN>'
</code></pre>
<p>the new way is not working for me even if I used the new firebase console when i set it up, and even if the token that i m using is generated using the new Firebase sdk. Does someone know why only the deprecated way is working? I was interested to put the token in the header of my requests but can not do.</p>
| 0 |
ImageMagick: No decode delegate for this image format `' @ error/constitute.c/ReadImage/504
|
<p><strong>Problem:</strong> ImageMagick convert is unable to crop image. It looks like it doesn't recognize the image type?</p>
<p><strong>What I've Tried:</strong></p>
<p>I've searched around online and I've seen several similar issues but not mine.
I've attempted their solutions including</p>
<ul>
<li>Uninstalling and reinstalling ImageMagick via brew.</li>
<li>identify -list format (JPEG, GIF, PNG, TIFF, etc were all there and all had rw permissions)</li>
<li>convert -version <em>(png is is among the built-in delegates)</em></li>
<li>convert pic1.png pic1-jpg.jpg <em>(this worked fine)</em></li>
<li>convert pic1-jpg.jpg pic1-jpg.jpg <em>(this worked fine)</em></li>
<li>convert pic1-jpg.jpg 805X972+34+94 pic1-jpg-crop.jpg <em>(this gave the same error as for png as shown below)</em></li>
</ul>
<p> </p>
<p>I'm working on Mac OSX El Capitan and everything else in terminal works fine. ImageMagick was already installed.</p>
<p><strong>When I run:</strong></p>
<pre><code>$ convert /Users/Innovate/Desktop/crop/2015-04-26-GinaDate13_487.png 805X972+34+94 /Users/Innovate/Desktop/crop/2015-04-26-GinaDate13_487-cropped.png
</code></pre>
<p><strong>I get:</strong></p>
<blockquote>
<p>convert: unable to open image `805X972+34+94': No such file or directory @ error/blob.c/OpenBlob/2702.</p>
<p>convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/504.</p>
<p>no decode delegate for this image format `' @ error/constitute.c/ReadImage/504</p>
</blockquote>
<p>In the other posts on this issue, people get</p>
<blockquote>
<p>convert no decode delegate for this image format `PNG'</p>
</blockquote>
<p>Or similar (except with their image type or filename and image type)</p>
<p> </p>
<p>However, mine doesn't say anything about image file type...</p>
<p>I have not tried uninstalling ImageMagick then installing it manually from sources because I'm not very confident at doing that... (this solution was shown: <a href="https://stackoverflow.com/a/34633084/5398660">https://stackoverflow.com/a/34633084/5398660</a> )</p>
<p>Does anyone know what might be going on?</p>
<p>Also, can anyone help me interpret the <em>@ error/constitute.c/ReadImage/504</em> part? I'm looking at the code for <a href="http://www.imagemagick.org/api/MagickCore/constitute_8c_source.html" rel="noreferrer">constitute.c</a> but I'm not sure if I can get useful information from it to solve my problem (I only know a bit of C)</p>
<p>Thank you!</p>
| 0 |
Pass variable to included playbook?
|
<p>I would like to have a master playbook, which include's other playbooks. Is it possible to pass a variable to that included playbook?</p>
<p>The normal syntax which is used for passing variables to included tasks doesn't work (see below)</p>
<pre><code>- include: someplaybook.yml variable=value
</code></pre>
<p>and</p>
<pre><code>- include: someplaybook.yml
vars:
variable: value
</code></pre>
<p>I'm running v2.0.2.0.</p>
| 0 |
sum of an array using recursion Javascript
|
<p>Looking for a way to solve this problem by recursing <code>sum()</code>. Right now, the code works, but I am supposed to call <code>sum()</code> more than once, and it should not mutate the input array.</p>
<pre><code>var sum = function(array) {
if(array.length === 0){
return 0;
}
function add(array, i){
console.log(array[i]);
if(i === array.length-1){
return array[i];
}
return array[i] + add(array, i+1);
}
return add(array, 0);
};
sum([1, 2, 3, 4, 5, 6]) //21
</code></pre>
| 0 |
convert list of data object to csv
|
<p>I'm using python 2.7.6. I would like to convert my list of objects into csv format. I have a list of cdr object, this object contains some string, int and datatime object.</p>
<pre><code>class cdr():
def __init__(self):
# some init
def __iter__(self):
return iter(self.name, self.my_value,self.my_datetime)
#from another class
import csv
def make_csv(self, cdr_list):
with open(self.file_name, 'wb') as csv_file:
wr = csv.writer(csv_file, delimiter=",")
for cdr in cdr_list:
wr.writerow(cdr)
</code></pre>
<p>But i'm getting a blank csv. Thanks for help. </p>
| 0 |
The .NET Core SDK is not installed or cannot be found under the path
|
<p>When compiling .Net Core RC2 project under VS 2015 I am receiving following error</p>
<blockquote>
<p>GETSDKTOOLINGINFO : error : The .NET Core SDK is not installed or
cannot be found under the path C:\Program Files\dotnet\bin. These
components are required to build and run this project.</p>
</blockquote>
<p>Files do exist under that directory.</p>
<p>Also when I input <em>dotnet</em> into command line I do see it's prining proper version number and stuff.(.NET Command Line Tools (<strong>1.0.0-beta-001598</strong>)</p>
<p>Any idea how to resolve the issue?</p>
| 0 |
Docker with one nginx and one uwsgi container that is sharing a UNIX socket
|
<p>First off, sorry for the wall of text.</p>
<p>I'm trying to get my Flask-application up and running with Docker with the mindset "one service per container" so I really want to run Nginx in one container and uWSGI in one container so they are seperate and easy to update if I want to.</p>
<p>This is my relevant folder structure:</p>
<ul>
<li>docker-root-folder
<ul>
<li>nginx
<ul>
<li>sites-enabled/</li>
<li>ssl/</li>
<li>Dockerfile</li>
<li>nginx.conf</li>
<li>uwsgi_params</li>
</ul></li>
<li>uwsgi
<ul>
<li>app/</li>
<li>app.ini</li>
<li>Dockerfile</li>
</ul></li>
</ul></li>
</ul>
<p>Nginx's Dockerfile:</p>
<pre><code>FROM connexiolabs/alpine-nginx:1.7.11
RUN mkdir /etc/ssl/botillsammans
COPY ./ssl/dhparams.pem /etc/ssl/botillsammans
COPY ./ssl/botillsammans.klumpen.se /etc/ssl/botillsammans
COPY ./sites-enabled /etc/nginx/sites-enabled
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./uwsgi_params /etc/nginx/uwsgi_params
CMD ["/usr/local/sbin/nginx", "-c", "/etc/nginx/nginx.conf"]
</code></pre>
<p>The only enabled site for Nginx (called www):</p>
<pre><code>upstream flask {
server unix:///tmp/app.sock;
}
server {
listen 443 ssl;
server_name botillsammans.klumpen.se;
access_log /var/log/nginx/botillsammans.access.log;
error_log /var/log/nginx/botillsammans.error.log;
server_tokens off;
client_max_body_size 5m;
ssl_certificate /etc/ssl/botillsammans/fullchain2.pem;
ssl_certificate_key /etc/ssl/botillsammans/privkey2.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
# Disable SSLv3
ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
ssl_prefer_server_ciphers on;
ssl_ciphers '........';
ssl_dhparam /etc/ssl/botillsammans/dhparams.pem;
add_header Strict-Transport-Security max-age=15768000;
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/ssl/botillsammans/chain2.pem;
resolver 8.8.8.8 8.8.4.4 valid=86400;
resolver_timeout 10;
location / {
include /etc/nginx/uwsgi_params;
uwsgi_pass flask;
}
}
</code></pre>
<p>uWSGI's Dockerfile:</p>
<pre><code>FROM my-own-app-base
RUN mkdir -p /app/backend
RUN mkdir -p /app/frontend/prod
COPY ./app/backend /app/backend
COPY ./app/frontend/prod /app/frontend/prod
COPY ./app/wsgi.py /app
RUN mkdir /uwsgi
COPY ./app.ini /uwsgi
WORKDIR /uwsgi
CMD ["uwsgi", "--thunder-lock", "--ini", "/uwsgi/app.ini"]
</code></pre>
<p>My app.ini (uWSGI file):</p>
<pre><code>[uwsgi]
config_base = /tmp
app_base = /app
chmod-socket = 777
socket = %(config_base)/app.sock
pidfile = %(config_base)/app.pid
stats = %(config_base)/app.stats.sock
chdir = %(app_base)
wsgi-file = wsgi.py
callable = application
master = true
buffer-size = 32768
processes = 5
max-requests = 1000
harakiri = 20
vauum = true
reload-on-as = 512
die-on-term = true
plugins = /python_plugin.so
</code></pre>
<p>One funny (?) thing is that if I go into the running uWSGI-container, changes the port for the Flask-application and runs <code>uwsgi --ini /uwsgi/app.ini</code>, press Ctrl+C ONE TIME then the app will start and work as intended (that is, I can access the site in the browser and everything works).</p>
<p>My docker-compose.yml-file:</p>
<pre><code>uwsgi:
restart: always
build: ./uwsgi
volumes:
- /uwsgi
- /tmp
nginx:
restart: always
build: ./nginx
volumes_from:
- uwsgi
</code></pre>
<p>The log from Docker's logs:</p>
<pre><code>uwsgi_1 | [uWSGI] getting INI configuration from /uwsgi/app.ini
uwsgi_1 | *** Starting uWSGI 2.0.11.2 (64bit) on [Tue May 10 19:13:13 2016] ***
uwsgi_1 | compiled with version: 5.2.0 on 29 October 2015 23:59:33
uwsgi_1 | os: Linux-3.19.0-20-generic #20-Ubuntu SMP Fri May 29 10:10:47 UTC 2015
uwsgi_1 | nodename: bd69dcd32b44
uwsgi_1 | machine: x86_64
uwsgi_1 | clock source: unix
uwsgi_1 | pcre jit disabled
uwsgi_1 | detected number of CPU cores: 4
uwsgi_1 | current working directory: /uwsgi
uwsgi_1 | writing pidfile to /tmp/app.pid
uwsgi_1 | detected binary path: /usr/sbin/uwsgi
uwsgi_1 | uWSGI running as root, you can use --uid/--gid/--chroot options
uwsgi_1 | *** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
uwsgi_1 | chdir() to /app
uwsgi_1 | your processes number limit is 524288
uwsgi_1 | your memory page size is 4096 bytes
uwsgi_1 | *** WARNING: you have enabled harakiri without post buffering. Slow upload could be rejected on post-unbuffered webservers ***
uwsgi_1 | detected max file descriptor number: 524288
uwsgi_1 | lock engine: pthread robust mutexes
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | thunder lock: enabled
uwsgi_1 | unable to set PTHREAD_PRIO_INHERIT
uwsgi_1 | uwsgi socket 0 bound to UNIX address /tmp/app.sock fd 3
uwsgi_1 | Python version: 2.7.11 (default, Jan 23 2016, 12:34:14) [GCC 5.3.0]
uwsgi_1 | *** Python threads support is disabled. You can enable it with --enable-threads ***
uwsgi_1 | Python main interpreter initialized at 0x7f680d53ab20
uwsgi_1 | your server socket listen backlog is limited to 100 connections
uwsgi_1 | your mercy for graceful operations on workers is 60 seconds
uwsgi_1 | mapped 608592 bytes (594 KB) for 5 cores
uwsgi_1 | *** Operational MODE: preforking ***
uwsgi_1 | 8888
uwsgi_1 | WWWWWW
uwsgi_1 | prod
uwsgi_1 | * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
</code></pre>
<p>And I notice that these log message doesn't show up (like they do if I start another uWSGI instance as instructed above):</p>
<pre><code>WSGI app 0 (mountpoint='') ready in 9 seconds on interpreter 0x7f6285a21b80 pid: 17 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 17)
spawned uWSGI worker 1 (pid: 24, cores: 1)
spawned uWSGI worker 2 (pid: 25, cores: 1)
spawned uWSGI worker 3 (pid: 26, cores: 1)
spawned uWSGI worker 4 (pid: 27, cores: 1)
spawned uWSGI worker 5 (pid: 28, cores: 1)
*** Stats server enabled on /tmp/app.stats.sock fd: 17 ***
</code></pre>
<p>Both containers are only running as root and everything is owned by root. I know, not safe, and I will change this when I get everything running, promise.</p>
<p>So I guess my question is why can't uWSGI start completely?</p>
<p>EDIT #1:</p>
<p>The wsgi.py-file (I know I can remove the if-statement, it's just for me while testing):</p>
<pre><code>#!/usr/bin/env python
# coding=utf-8
from backend.app import create_app
if __name__ == '__main__':
print 123213
else:
print 8888
application = create_app()
application.run(host='0.0.0.0', port=8080, debug=True, use_reloader=False)
</code></pre>
<p>The <code>create_app</code>-function that is called in the previous text:</p>
<pre><code>def create_app(config_object=ProdConfig):
config = 'dev'
if config_object.ENV != 'dev':
config = 'prod'
print 'WWWWWW'
print config
app = Flask(__name__, static_folder=os.getcwd() + '/frontend/' + config, static_url_path='/s')
app.config.from_object(config_object)
return app
</code></pre>
| 0 |
How to create a condition to check if the datatable item is null in vb
|
<p>Now I want if the <code>dt.rows(i).item(0)</code> is null, then some code.. </p>
<p>This is my code:</p>
<pre><code>If dtpay.Rows(i).Item(23).ToString Is Nothing Then
GoTo finalline
End If
</code></pre>
<p>But seems like the code is not working..
Thanks a lot for your concern :D</p>
| 0 |
CAST/CONVERT empty string to INT in SQL Server
|
<p>I came across a bug where I was using <code>CAST(Col1 AS INT) + CAST(Col2 AS INT)</code> where both Col1 and Col2 are <code>VARCHAR</code> and I was getting valid results out when Col1 or Col2 was blank and I didn't expect this. I checked and CAST (and CONVERT) both have this default behavior of replacing blank with 0:</p>
<pre><code>SELECT CAST('' AS INT)
SELECT CONVERT(INT, '')
</code></pre>
<p>I checked the <a href="https://msdn.microsoft.com/en-GB/library/ms187928.aspx" rel="noreferrer">info page</a> and I can't see any reference to explain why this is the behavior (or change it through a server setting). I can of course work around this but I wanted to ask why this is the behavior as I do not think it is intuitive. </p>
<p>I'd actually rather this <code>CAST</code> failed or gave <code>NULL</code>, is there a server setting somewhere which effects this?</p>
| 0 |
C# Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals
|
<p>When I add a static string property to my class that returns a long string I get this error.</p>
<p>In the same project I have added lots of string properties over 20k chars, but when I create another property returning a string and build the project I get this error.</p>
<p>How can I increase that limit? I tried to use Stringbuilder but same happens.</p>
| 0 |
Python time.sleep indefinitely
|
<p>In Python's time module, there is a <code>sleep()</code> function, where you can make Python wait x seconds before resuming the program. Is there a way to do this indefinitely until a condition is met? For example:</p>
<pre><code>while True:
time.sleep()
if x:
break
time.unsleep()
</code></pre>
<p>I am trying to make a pause function for my PyGame program. Any help is appreciated. </p>
| 0 |
Store query result in variable
|
<p>I have declared 6 variables in a stored procedure and I'd like to store a query result (which may bring up to 6 records) into each one of those variables. My query looks like this:</p>
<pre><code> DECLARE
@Sib1 varchar(20),
@Sib2 varchar(20),
@Sib3 varchar(20),
@Sib4 varchar(20),
@Sib5 varchar(20),
@Sib6 varchar(20)
select
PC.SKU
from
Product PC
where
Parent_code in (select
Parent_code
from
Product
where
SKU =12345)
and ParentFlag <> 'p'
and SKU <> 12345
order by Parent_Child_Priority desc
</code></pre>
<p>I'd like to put each one of the resulting SKU in each @SIB variables. if it only returns 1 result, I'd like to put null values into the rest of the @SIB variables.</p>
<p>Thanks.</p>
| 0 |
Cocoapods 1.0: Header files not found
|
<p>I just tried to update from cocoapods 0.39.x to Cocoapods 1.0.
Running</p>
<blockquote>
<p>pod install</p>
</blockquote>
<p>from the terminal causes no warnings. Everything seems normal. However, when I try to build my project it outputs:</p>
<blockquote>
<p>AFNetworking/AFNetworking.h file not found</p>
</blockquote>
<p>My pod file looks like this (there are a few more dependencies but I only listed a part of it):</p>
<pre><code>platform :ios, '8.0'
use_frameworks!
source 'https://github.com/CocoaPods/Specs.git'
target 'MyApp' do
pod 'AFNetworking', '~> 2.6'
pod 'BEMCheckBox'
pod 'ActionSheetPicker-3.0', '~> 2.0.5'
pod 'SCLAlertView'
pod 'DZNEmptyDataSet'
pod 'SSZipArchive'
end
target 'MyAppTests' do
end
</code></pre>
<p>Since some projects are written in Objective-C, i created a bridging header:</p>
<pre><code>#import <AFNetworking/AFNetworking.h>
#import <ActionSheetPicker_3_0/ActionSheetPicker.h>
#import <SSZipArchive/SSZipArchive.h>
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
</code></pre>
<p>I explicitly included <code>$(inherited)</code> in the <code>Header Search Paths</code>, the <code>User Header Search paths</code>, and the <code>Framework Search paths</code> but the error does not go away.
Does someone have an idea on how to fix this? </p>
| 0 |
Is there a way to build the mobile nav bar in ng2-bootstrap?
|
<p>I've been implementing ng2-bootstrap and Angular2.</p>
<p>I cannot figure out how to make the mobile navbar open / close.</p>
<p><strong>Is this something that just isn't supported yet? Or am I missing something?</strong></p>
<p>Update, html:</p>
<pre><code><nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img src="/logo.png" />
</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li router-active>
<a [routerLink]=" ['Index'] ">Summary<span class="sr-only">(current)</span></a>
</li>
<li router-active>
<a [routerLink]=" ['Portfolio'] ">Portfolio<span class="sr-only">(current)</span></a>
</li>
<li router-active>
<a [routerLink]=" ['About'] ">About<span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li dropdown keyboardNav="true">
<a href class="dropdown-toggle" role="button" aria-expanded="false" dropdownToggle>
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
Andrew Duncan
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li role="menuitem"><a class="dropdown-item" href="#">Account Settings</a></li>
<li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
<li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
<li class="divider dropdown-divider"></li>
<li role="menuitem"><a class="dropdown-item" href="#">Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</code></pre>
<p></p>
<p>Typescript:</p>
<pre><code>/*
* Angular 2 decorators and services
*/
import { Component, ViewEncapsulation } from '@angular/core';
import { RouteConfig, Router } from '@angular/router-deprecated';
import { AppState } from './app.service';
import { Home } from './home';
import { RouterActive } from './router-active';
import { BUTTON_DIRECTIVES, DROPDOWN_DIRECTIVES } from '../../node_modules/ng2-bootstrap';
/*
* App Component
* Top Level Component
*/
@Component({
selector: 'app',
pipes: [ ],
providers: [ ],
directives: [
RouterActive,
BUTTON_DIRECTIVES,
DROPDOWN_DIRECTIVES ],
encapsulation: ViewEncapsulation.None,
styles: [
require('./app.css')
],
template: require('./app.html')
})
@RouteConfig([
{ path: '/', name: 'Index', component: Home, useAsDefault: true },
{ path: '/home', name: 'Home', component: Home },
// Async load a component using Webpack's require with es6-promise-loader and webpack `require`
{ path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
{ path: '/portfolio', name: 'Portfolio', loader: () => require('es6-promise!./portfolio')('Portfolio') }
])
export class App {
angularclassLogo = 'assets/img/angularclass-avatar.png';
loading = false;
url = 'https://twitter.com/AngularClass';
constructor(
public appState: AppState) {
}
ngOnInit() {
console.log('Initial App State', this.appState.state);
}
}
/*
* Please review the https://github.com/AngularClass/angular2-examples/ repo for
* more angular app examples that you may copy/paste
* (The examples may not be updated as quickly. Please open an issue on github for us to update it)
* For help or questions please contact us at @AngularClass on twitter
* or our chat on Slack at https://AngularClass.com/slack-join
*/
</code></pre>
| 0 |
How to write to a CSV line by line?
|
<p>I have data which is being accessed via http request and is sent back by the server in a comma separated format, I have the following code :</p>
<pre><code>site= 'www.example.com'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
soup = soup.get_text()
text=str(soup)
</code></pre>
<p>The content of text is as follows:</p>
<pre><code>april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9
</code></pre>
<p>How can I save this data into a CSV file.
I know I can do something along the lines of the following to iterate line by line:</p>
<pre><code>import StringIO
s = StringIO.StringIO(text)
for line in s:
</code></pre>
<p>But i'm unsure how to now properly write each line to CSV</p>
<p>EDIT---> Thanks for the feedback as suggested the solution was rather simple and can be seen below.</p>
<p>Solution:</p>
<pre><code>import StringIO
s = StringIO.StringIO(text)
with open('fileName.csv', 'w') as f:
for line in s:
f.write(line)
</code></pre>
| 0 |
W3C validation error with image width
|
<p>I need an image to resize to the full width of my webpage. This works fine with the following HTML/CSS:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#logo{
position: fixed;
top: 0;
left: 0;
min-width: 100%;
z-index: 3;
opacity: .8;
} </code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo"><img src="/logo.png" alt="logo" width="100%"></div></code></pre>
</div>
</div>
</p>
<p>However W3C validation picks this up as an error. "Bad value 100% for attribute width on element img: Expected a digit but saw % instead."</p>
<p>I tried this alternative, but now the image does not resize of course:</p>
<pre><code><div id="logo"><img src="/logo.png" alt="logo" width:100%;></div>
</code></pre>
<p>How do I retain the same effect while still passing the W3C validation? It is the only error on my entire page, and I know it doesn't really matter, but there is bound to be a solution I am overlooking.</p>
| 0 |
How to push item to [string] in TypeScript
|
<p>I want to add items to [string].
But the following code fails at param.push statement.</p>
<p>EDIT</p>
<pre><code>declare var sqlitePlugin:any;
var query: string = `SELECT * FROM items `;
var param: [string];
if (options['limit']) {
var limit = options['limit'];
query = query + " LIMIT ? ";
param.push(String(limit));
}
if (options['offset']) {
var offset = options['offset'];
query = query + " OFFSET ? ";
param.push(String(offset));
}
sqlitePlugin.openDatabase({name: 'Items.db', key: 'Password', location: 'default'}, (db) => {
db.transaction((tx)=> {
tx.execQuery(query, param, (resultSet)=>{
this.items = [];
for(let i = 0; i < resultSet.rows.length; i++) {
var item: Item = new Item();
item.code = resultSet.rows.item(i).item_code;
item.name = resultSet.rows.item(i).item_name;
this.items.push(item);
}
callback(this.items);
} );
}
});
</code></pre>
<p>Sorry to ask this very basic question but I'm struggling for 2 days..
Please give me any hint or link.</p>
<p>Thanks in advance.</p>
| 0 |
REST POST works correctly with POSTMAN but exception when using Spring RestTemplate
|
<p>I am writing a Rest client to post JSON data using Spring RestTemplate.
Using POSTMAN and following JSON data in body get the response correctly-</p>
<pre><code>{
"InCode":"test",
"Name":"This is test",
"Email":"[email protected]",
"Id":18,
}
</code></pre>
<p>However when trying to hit the REST API using Spring RestTemplate as follows</p>
<pre><code>ResponseEntity<String> response = restTemplate.exchange(baseUrl,
HttpMethod.POST, getHeaders(), String.class);
private HttpEntity<?> getHeaders() throws JSONException {
JSONObject request = new JSONObject();
request.put("Email", "[email protected]");
request.put("Id", "18");
request.put("Name", "This is test");
request.put("InCode", "test");
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return new HttpEntity<>(request.toString(), headers);
}
</code></pre>
<p>I get the exception-</p>
<pre><code>11:52:56.808 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://server-test/platform/v4/org"
11:52:56.815 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
12:03:47.357 [main] DEBUG o.s.web.client.RestTemplate - Writing [{"InCode":"test","Email":"[email protected]","Id":"18","Name":"This is test"}] using [org.springframework.http.converter.StringHttpMessageConverter@6a1aab78]
11:52:57.574 [main] DEBUG o.s.web.client.RestTemplate - POST request for "http://server-test/platform/v4/org" resulted in 500 (Internal Server Error); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
</code></pre>
<p>Would be thankful for any help.</p>
| 0 |
Differences between ConstraintLayout and RelativeLayout
|
<p>I am confused about the difference between <code>ConstraintLayout</code> and <code>RelativeLayout</code>. Could someone please tell me the exact differences between them? </p>
| 0 |
Getting ValueError: The indices for endog and exog are not aligned
|
<p>I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:</p>
<pre><code>y = y_mort.convert_objects(convert_numeric=True)
#Building Logistic model_LSVC
print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape)
print("y values:",y.head())
logit = sm.Logit(y,X,missing='drop')
</code></pre>
<p>The error that appears:</p>
<pre><code>Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59)
y values: 0 0
1 1
2 0
3 0
4 0
Name: mort, dtype: int64
ValueError Traceback (most recent call last)
<ipython-input-8-fec746e2ee99> in <module>()
160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape)
161 print("y values:",y.head())
--> 162 logit = sm.Logit(y,X,missing='drop')
163 # fit the model
164 est = logit.fit(method='cg')
D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs)
399
400 def __init__(self, endog, exog, **kwargs):
--> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs)
402 if (self.__class__.__name__ != 'MNLogit' and
403 not np.all((self.endog >= 0) & (self.endog <= 1))):
D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs)
152 """
153 def __init__(self, endog, exog, **kwargs):
--> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs)
155 self.raise_on_perfect_prediction = True
156
D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs)
184
185 def __init__(self, endog, exog=None, **kwargs):
--> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs)
187 self.initialize()
188
D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs)
58 hasconst = kwargs.pop('hasconst', None)
59 self.data = self._handle_data(endog, exog, missing, hasconst,
---> 60 **kwargs)
61 self.k_constant = self.data.k_constant
62 self.exog = self.data.exog
D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs)
82
83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs):
---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs)
85 # kwargs arrays could have changed, easier to just attach here
86 for key in kwargs:
D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs)
564 klass = handle_data_class_factory(endog, exog)
565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst,
--> 566 **kwargs)
D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs)
74 # this has side-effects, attaches k_constant and const_idx
75 self._handle_constant(hasconst)
---> 76 self._check_integrity()
77 self._cache = resettable_cache()
78
D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self)
450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and
451 not self.orig_endog.index.equals(self.orig_exog.index)):
--> 452 raise ValueError("The indices for endog and exog are not aligned")
453 super(PandasData, self)._check_integrity()
454
ValueError: The indices for endog and exog are not aligned
</code></pre>
<p>The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?</p>
| 0 |
Laravel Application is not working after uploading to the server
|
<p>My laravel Application was working perfect on the local server. But After I uploaded it to my server it is not working. The directory structure of my application is shown in the following image:
<a href="https://i.stack.imgur.com/IpTzK.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/IpTzK.jpg" alt="enter image description here"></a></p>
<p>And I am getting the following problem. It is automatically redirected to loopback address showing nothing
<a href="https://i.stack.imgur.com/RgYl2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/RgYl2.jpg" alt="enter image description here"></a></p>
<p>Here is my php version in the server</p>
<p><a href="https://i.stack.imgur.com/pwC2N.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/pwC2N.jpg" alt="enter image description here"></a></p>
| 0 |
Firebase database getInstance crashes app
|
<p>When running the sample after creating google-service.json, the app crashes when trying to get database reference in SignInActivity</p>
<pre><code>mDatabase = FirebaseDatabase.getInstance().getReference();
</code></pre>
<p>Crash log</p>
<pre><code>05-21 09:27:27.644 488-488/com.google.firebase.quickstart.database D/AndroidRuntime: Shutting down VM
05-21 09:27:27.644 488-488/com.google.firebase.quickstart.database E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.firebase.quickstart.database, PID: 488
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.firebase.quickstart.database/com.google.firebase.quickstart.database.SignInActivity}: com.google.firebase.database.DatabaseException: Failed to get
FirebaseDatabase instance: FirebaseApp object has no DatabaseURL in its FirebaseOptions object.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: com.google.firebase.database.DatabaseException: Failed to get FirebaseDatabase instance: FirebaseApp object has no DatabaseURL in its FirebaseOptions object.
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.google.firebase.quickstart.database.SignInActivity.onCreate(SignInActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code></pre>
<p>How to fix this issue ?</p>
| 0 |
Laravel edit existing pdf
|
<p>I don't know how to edit an existing pdf file with Laravel.</p>
<p>I have found many plugin for create PDF but no one help me in my problem.</p>
<p>Can anyone know how to do it?</p>
<p>This is what I have tried so far</p>
<pre class="lang-php prettyprint-override"><code>$pdf->AddPage();
$source = $pdf->setSourceFile(asset("assets/images/coupon/source/coupon.pdf"));
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx, 10, 10, 90);
$pdf->SetXY(40, 0); // Doesn't work
$pdf->Write(0, 'This is just a simple text'); // Doesn't work
$pdf->Output(); // Doesn't work
</code></pre>
| 0 |
Overriding AppConfig.ready()
|
<p>Trying to catch the basics of Django. Namely how Applications work.
The docs: <a href="https://docs.djangoproject.com/en/stable/ref/applications/#methods" rel="noreferrer">https://docs.djangoproject.com/en/stable/ref/applications/#methods</a></p>
<p>And in the code of the class AppConfig we can read: </p>
<pre><code>def ready(self):
"""
Override this method in subclasses to run code when Django starts.
"""
</code></pre>
<p>Well, this is my example:</p>
<p><strong>my_app/apps.py</strong></p>
<pre><code>class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
print('My app')
</code></pre>
<p>I just want to make the ready method work. That is, when Django finds my_app, let it run the ready method. </p>
<p>The app is registered in INSTALLED_APPS. </p>
<p>I execute 'python manage.py runserver'. And nothing is printed.</p>
<p>If I place a breakpoint inside the ready method, the debugger don't stop there.</p>
<p>Could you help me: what is my mistake in understanding here. Thank you in advance.</p>
<pre><code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
]
</code></pre>
<p>And I created a view </p>
<p><strong>my_app/views.py</strong></p>
<pre><code>def index(request):
print('Print index')
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', my_app_views.index, name='home')
]
</code></pre>
<p>Well, the view is working. This means that the application is registered.</p>
| 0 |
Why is my Golang Channel Write Blocking Forever?
|
<p>I've been attempting to take a swing at concurrency in Golang by refactoring one of my command-line utilities over the past few days, but I'm stuck.</p>
<p><a href="https://github.com/stephendolan/jira_open_comment_emailer" rel="noreferrer">Here's</a> the original code (master branch).</p>
<p><a href="https://github.com/stephendolan/jira_open_comment_emailer/tree/x_concurrent" rel="noreferrer">Here's</a> the branch with concurrency (x_concurrent branch).</p>
<p>When I execute the concurrent code with <code>go run jira_open_comment_emailer.go</code>, the <code>defer wg.Done()</code> never executes if the JIRA issue is added to the channel <a href="https://github.com/stephendolan/jira_open_comment_emailer/blob/x_concurrent/jira_open_comment_emailer.go#L241" rel="noreferrer">here</a>, which causes my <code>wg.Wait()</code> to hang forever.</p>
<p>The idea is that I have a large amount of JIRA issues, and I want to spin off a goroutine for each one to see if it has a comment I need to respond to. If it does, I want to add it to some structure (I chose a channel after some research) that I can read from like a queue later to build up an email reminder.</p>
<p>Here's the relevant section of the code:</p>
<pre><code>// Given an issue, determine if it has an open comment
// Returns true if there is an open comment on the issue, otherwise false
func getAndProcessComments(issue Issue, channel chan<- Issue, wg *sync.WaitGroup) {
// Decrement the wait counter when the function returns
defer wg.Done()
needsReply := false
// Loop over the comments in the issue
for _, comment := range issue.Fields.Comment.Comments {
commentMatched, err := regexp.MatchString("~"+config.JIRAUsername, comment.Body)
checkError("Failed to regex match against comment body", err)
if commentMatched {
needsReply = true
}
if comment.Author.Name == config.JIRAUsername {
needsReply = false
}
}
// Only add the issue to the channel if it needs a reply
if needsReply == true {
// This never allows the defered wg.Done() to execute?
channel <- issue
}
}
func main() {
start := time.Now()
// This retrieves all issues in a search from JIRA
allIssues := getFullIssueList()
// Initialize a wait group
var wg sync.WaitGroup
// Set the number of waits to the number of issues to process
wg.Add(len(allIssues))
// Create a channel to store issues that need a reply
channel := make(chan Issue)
for _, issue := range allIssues {
go getAndProcessComments(issue, channel, &wg)
}
// Block until all of my goroutines have processed their issues.
wg.Wait()
// Only send an email if the channel has one or more issues
if len(channel) > 0 {
sendEmail(channel)
}
fmt.Printf("Script ran in %s", time.Since(start))
}
</code></pre>
| 0 |
Jquery select button by name
|
<p>I don't understand how to select by name with Jquery the button "g_list".</p>
<pre><code><div class="col-sm-4 sezione-na">
<div class="titolo-sezione-na">Title:</div>
<div class="form-group">
<div class="col-sm-12"><button name="g_list" type="button" class="btn btn-primary btn-block">Generate list</button></div>
</div>
</code></pre>
<p></p>
<p>I wrote this Jquery code, but it doesn't work:</p>
<pre><code>$("input[name='g_list']").click(function(){
alert( "ready!" );});
</code></pre>
| 0 |
Stock management database design
|
<p>I'm creating an Intranet for my company, and we want to have a stock management in it. We sell and rent alarm systems, and we want to have a good overview of what product is still in our offices, what has been rented or sold, at what time, etc.</p>
<p>At the moment I thought about this database design :</p>
<p><a href="https://i.stack.imgur.com/HG4bP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HG4bP.png" alt="enter image description here"></a></p>
<p>Everytime we create a new contract, this contract is about a location or a sale of an item. So we have an Product table (which is the type of product : alarms, alarm watches, etc.), and an Item table, which is the item itself, with it unique serial number. I thought about doing this, because I'll need to have a trace of where a specific item is, if it's at a client house (rented), if it's sold, etc. Products are related to a specific supplier, to whom we can take orders. But here, I have a problem, shouldn't the order table be related to Product ?</p>
<p>The main concern here is the link between Stock, Item, Movement stock. I wanted to create a design where I'd be able to see when a specific Item is pulled out of our stock, and when it enters the stock with the date. That's why I thought about a Movement_stock table. The Type_Movement is either In / Out.
But I'm a bit lost here, I really don't know how to do it nicely. That's why I'm asking for a bit of help.</p>
| 0 |
Wrapping DIV inside Anchor tag or otherwise
|
<p>Suppose I have a clickable complex <code>div</code> element structure which links to another page as follows. This is the thing that is being achieved currently on click.
On click (css :active state) change the background color inside <code><a></code> tag and redirect to other page. <br></p>
<p>I am wondering whether this conforms to HTML5 validation or consider as a best practice compared to wrapping it with a <code>div</code> and using JavaScript to manage the link redirect and background color change on click. </p>
<p>To me, the first approach seems to be much cleaner and straight forward.</p>
<p>I believe this is a common issue face by a lot of web developers but I am not sure whether there is an existing best practice solution for this.</p>
<p>1) Maintain as this</p>
<pre><code><a href="page1.html">
<div>
<!-- complex layout -->
</div>
</a>
</code></pre>
<p>2) Omit the <code><a></code> tag and manage background color during click event and redirect using JavaScript</p>
<pre><code><div id="#redirectLink" data-link="page1.html">
<!-- complex layout -->
</div>
</code></pre>
| 0 |
How to substract/add minutes from a timestamp in postgreSQL
|
<p>I have the following scenario:</p>
<p>I have employees who register their check in/out from their work. But they have 10 minutes of tolerance.</p>
<p>The late entries I get with this view:</p>
<pre><code>CREATE OR REPLACE VIEW employees_late_entries
(
id,
created_datetime,
entry_datetime,
contact_id,
contact_name,
user_id,
employees_perm_id
)
AS
SELECT precence_records.id,
precence_records.created AS created_datetime,
("substring"(precence_records.created::text, 0, 11) || ' '::text) || contacts.entry_time::text AS entry_datetime,
contacts.id AS contact_id,
contacts.name AS contact_name,
precence_records.user_id,
precence_records.employees_perm_id
FROM precence_records,
contacts
WHERE
precence_records.type::text = 'entry'::text AND
contacts.employee = true AND
contacts.id = precence_records.contact_id AND
( ("substring"(precence_records.created::text, 0, 11) || ' '::text) || contacts.entry_time::text) < precence_records.created::text AND
precence_records.employees_perm_id IS NULL;
</code></pre>
<p>the <code>precence_records.created</code> is the check in time and <code>contacts.entry_time</code> its the time of the schedule entry time for the employee.</p>
<p>This is the <code>condition contacts.entry_time</code> vs <code>precence_records.created</code> to get the late entries:</p>
<pre><code> ( ("substring"(precence_records.created::text, 0, 11) || ' '::text) || contacts.entry_time::text) < precence_records.created::text
</code></pre>
<p>So I wanna do something like that:</p>
<pre><code> ( ("substring"(precence_records.created::text, 0, 11) || ' '::text) || (contacts.entry_time::text + 10 MINUTES) ) < precence_records.created::text
</code></pre>
<p>DATA TYPES:</p>
<p>precence_records.created TIMESTAMP
contacts.entry_time VARCHAR</p>
<p>Can you help me please</p>
| 0 |
How do I auto refresh HTML page every hour?
|
<p>I want to refresh an HTML page every hour automatically in the background. I was thinking about using PHP but I'm not sure what if that's possible.</p>
<p>This is all the I have:</p>
<pre><code><meta http-equiv="refresh" content="3600" >
</code></pre>
<p>But this doesn't refresh automatically in the background. How can I do this? If this is possible in PHP and a cron job please let me know (with code preferably). Thank you. </p>
| 0 |
Stop a running Docker container by sending SIGTERM
|
<p>I have a very very simple Go app listening on port 8080</p>
<pre><code>http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "text-plain")
w.Write([]byte("Hello World!"))
})
log.Fatal(http.ListenAndServe(":8080", http.DefaultServeMux))
</code></pre>
<p>I install it in a Docker container and start it like so:</p>
<pre><code>FROM golang:alpine
ADD . /go/src/github.com/myuser/myapp
RUN go install github.com/myuser/myapp
ENTRYPOINT ["/go/bin/myapp"]
EXPOSE 8080
</code></pre>
<p>I then run the container using <code>docker run</code>: </p>
<pre><code>docker run --publish 8080:8080 first-app
</code></pre>
<p>I expect that, like most programs, I can send a SIGTERM to the process running <code>docker run</code> and this will cause the container to stop running. I observe that sending SIGTERM has no effect, and instead I need to use a command like <code>docker kill</code> or <code>docker stop</code>.</p>
<p>Is this intended behavior? I've asked <a href="https://forums.docker.com/t/docker-run-cannot-be-killed-with-ctrl-c/13108" rel="noreferrer">in the forums</a> and on IRC and gotten no answer.</p>
| 0 |
How to convert byte array to map[string,string] in golang
|
<p>I want to convert byte array to map[string,string] using golang. I tried this:</p>
<pre><code>var byte := json.Marshal(input)
var map := make(map[string]string *byte) // NOT WORKING
</code></pre>
<p>if byte holds value like {\"hello\":\"world\",...}
How to create the map from byte array</p>
<p>Please help.</p>
| 0 |
TcpClient class in c++ (Microsoft Visual Studio) example?
|
<p>I feel so embarrassed it's really a newbie question.
I usually using sys/socket in Linux / Osx to get tcp networking work.
In windows I didn't have clue about it.</p>
<p>I've already made this code running in C#:</p>
<pre><code>using System;
using System.Net.Sockets;
using System.Text;
public class HelloWorld
{
const String ipAddress = "192.168.2.81";
static TcpClient tcpClient;
static NetworkStream networkStream;
static public void Main ()
{
Console.WriteLine ("Hello Mono World");
tcpClient = new TcpClient();
tcpClient.Connect(ipAddress, 9090);
networkStream = tcpClient.GetStream();
networkStream.WriteTimeout = -1;
byte[] data = Encoding.ASCII.GetBytes("Client Connected to: " + ipAddress);
networkStream.Write(data, 0, data.Length);
byte[] data1 = Encoding.ASCII.GetBytes("Action1");
while(true) {
System.Threading.Thread.Sleep(1000);
networkStream.Write(data1, 0, data1.Length);
}
}
}
</code></pre>
<p>When I look into the msdn <a href="https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx" rel="nofollow">TcpClient</a>, it does supporting c++. But when I put it, the studio can't understand TcpClient. Usually we need to put some header in it. But in the documentation there is no header to include. So i'm confuse how can I use TcpClient in c++ then? Am I missing something from the documentation, since i'm new at this?</p>
| 0 |
Download file with javascript
|
<p>I want to trigger a file download using javascript only</p>
<p>I know how to do it with html, but i need to trigger the download specifically with javascript, on a button click.</p>
<p>The reason i am not doing it with html is because i want to use a variable as file name later on.</p>
<p>i have used this</p>
<pre><code>$("#button").click(function(){
window.location = 'files/aaa.pdf';
});
</code></pre>
<p>but it only opens the pdf on the same window instead of prompting the user to download it.</p>
<p>I have also tried using this:</p>
<pre><code><iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = 'files/aa.pdf';
};
</script>
</code></pre>
<p>But it fails to produce results.</p>
| 0 |
Converting 2D Numpy array of grayscale values to a PIL image
|
<p>Say I have a 2D Numpy array of values on the range 0 to 1, which represents a grayscale image. How do I then convert this into a PIL Image object? All attempts so far have yielded extremely strange scattered pixels or black images.</p>
<pre><code>for x in range(image.shape[0]):
for y in range(image.shape[1]):
image[y][x] = numpy.uint8(255 * (image[x][y] - min) / (max - min))
#Create a PIL image.
img = Image.fromarray(image, 'L')
</code></pre>
<p>In the code above, the numpy array image is normalized by (image[x][y] - min) / (max - min) so every value is on the range 0 to 1. Then it is multiplied by 255 and cast to an 8 bit integer. This should, in theory, process through Image.fromarray with mode L into a grayscale image - but the result is a set of scattered white pixels.</p>
| 0 |
Parse a string with key=value pair in a map?
|
<p>I have below String which is in the format of <code>key1=value1, key2=value2</code> which I need to load it in a map <code>(Map<String, String>)</code> as <code>key=value</code> so I need to split on comma <code>,</code> and then load <code>cossn</code> as key and <code>0</code> its value.</p>
<pre><code>String payload = "cossn=0, itwrqm=200006033213";
Map<String, String> holder =
Splitter.on(",").trimResults().withKeyValueSeparator("=").split(payload);
</code></pre>
<p>I am using Splitter here to do the job for me but for some cases it is failing. For some of my strings, value has some string with equal sign. So for below string it was failing for me:</p>
<pre><code>String payload = "cossn=0, abc=hello/=world";
</code></pre>
<p>How can I make it work for above case? For above case <code>key</code> will be <code>abc</code> and value should be <code>hello/=world</code>. Is this possible to do?</p>
| 0 |
Carousel with zooming of current slide
|
<p>I used the Slick.js to make a carousel just like on a picture, but I failed (
Does anybody knows any way to make a carousel just like on a picture? There should be a different width of slides, animation, and a current slide must have a bigger size</p>
<p>What I need to do:</p>
<p><a href="https://i.stack.imgur.com/kScfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kScfg.png" alt="enter image description here"></a></p>
<p>What I have now - <a href="https://jsfiddle.net/fiter92/xL5qezxy/" rel="nofollow noreferrer">https://jsfiddle.net/fiter92/xL5qezxy/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(document).ready(function($){
$('.carousel').slick({
infinite: true,
slidesToShow: 4,
slidesToScroll: 1,
arrows: false,
centerMode: true,
centerPadding: '60px',
variableWidth: true
});
$('.carousel-nav').slick({
infinite: true,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
arrows: true,
appendArrows: '.carousel-arrows',
prevArrow: '<span class="carousel-prev">&lt;-</span>',
nextArrow: '<span class="carousel-next">-&gt;</span>',
asNavFor: '.carousel',
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slick-slide {
padding: 20px;
}
.slick-current img {
width: 120%;
max-width: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"></script>
<div class="carousel">
<div>
<img src="http://dummyimage.com/600x400/000/fff&text=1" alt="">
</div>
<div>
<img src="http://dummyimage.com/600x400/000/fff&text=2" alt="">
</div>
<div>
<img src="http://dummyimage.com/600x400/000/fff&text=3" alt="">
</div>
<div>
<img src="http://dummyimage.com/800x400/000/fff&text=4" alt="">
</div>
<div>
<img src="http://dummyimage.com/400x400/000/fff&text=5" alt="">
</div>
<div>
<img src="http://dummyimage.com/600x400/000/fff&text=6" alt="">
</div>
</div>
<div class="carousel-nav">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
</div>
<div class="carousel-arrows">
</div></code></pre>
</div>
</div>
</p>
| 0 |
Using Mockito with TestNG
|
<p>I took a working test written for JUnit using Mockito and tried to adapt it to work with TestNG but oddly using TestNG only one test will work.</p>
<p>I think it is somehow related to the resetting of the mocks but I have played around with trying to call Mockito.reset and using BeforeMethod and BeforeClass and different combinations but still can only get one test to pass.</p>
<p>What I need to do to get the test to work?</p>
<pre><code>@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(calculatorController).build();
}
@AfterMethod
public void reset() {
Mockito.reset(calculatorService);
}
@Test
public void addFunctionTest() throws Exception {
Assert.assertNotNull(calculatorController);
Result expectedResult = new Result();
expectedResult.setResult(10);
when(calculatorService.add(anyInt(), anyInt())).thenReturn(expectedResult);
mockMvc.perform(get("/calculator/add").accept(MediaType.APPLICATION_JSON_VALUE)
.param("val1", "100")
.param("val2", "100"))
.andExpect(content().contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", equalTo(10)));
verify(calculatorService, times(1)).add(anyInt(), anyInt());
}
@Test
public void subtractFunctionTest() throws Exception {
Assert.assertNotNull(calculatorController);
Result expectedResult = new Result();
expectedResult.setResult(90);
when(calculatorService.subtract(anyInt(), anyInt())).thenReturn(expectedResult);
mockMvc.perform(get("/calculator/subtract").accept(MediaType.APPLICATION_JSON_VALUE)
.param("val1", "100")
.param("val2", "10"))
.andExpect(content().contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", equalTo(90)));
verify(calculatorService, times(1)).subtract(anyInt(), anyInt());
}
</code></pre>
<p>The second test always seems to fail on assertions that either content type is not set or the expected result is wrong. </p>
<p>It seems like the response for the first test is somehow being evaluated in the second test and so is obviously wrong!</p>
<p>I know the controller and service work as expected and the exact same tests running with jUnit actually work ok.</p>
<p>I have managed to get the tests to perform properly only when I do the following:</p>
<pre><code> @BeforeGroups("subtract")
public void reset() {
Mockito.reset(calculatorService);
mockMvc = MockMvcBuilders.standaloneSetup(calculatorController).build();
}
@Test(groups = "subtract")
public void subtractFunctionTest() throws Exception {
System.out.println("***** IN METHOD *****");
Assert.assertNotNull(calculatorController);
Result expectedResult = new Result();
expectedResult.setResult(90);
when(calculatorService.subtract(anyInt(), anyInt())).thenReturn(expectedResult);
//Perform HTTP Get for the homepage
mockMvc.perform(get("/calculator/subtract").accept(MediaType.APPLICATION_JSON_VALUE)
.param("val1", "100")
.param("val2", "10"))
.andExpect(content().contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", equalTo(90)));
//Verify that the service method was only called one time
verify(calculatorService, times(1)).subtract(anyInt(), anyInt());
}
</code></pre>
<p>This means I need to add one of these reset methods for each test method though and I then need a group per test method which doesnt seem correct.</p>
| 0 |
POST data to a PHP method from Swift
|
<p>I'm trying to post some info to my PHP file from Swift.
My php file is executed, but the posted variables just don't get through to the php file. What am I doing wrong?</p>
<p>Swift code:</p>
<pre><code>@IBAction func buttonPress(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.domain.com/php_swift_test/insert.php")!)
request.HTTPMethod = "POST"
let postString = "a=test&b=bla"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
</code></pre>
<p>PHP code:</p>
<pre><code><?php
@session_start();
@ob_start();
$host='localhost';
$user='test';
$password='Passw0rd99';
$db_name="mysql_test";
$connection = mysql_connect($host,$user,$password);
$a = $_POST['a'];
$b = $_POST['b'];
if(!$connection){
die('Connection Failed');
}
else{
$dbconnect = @mysql_select_db($db_name, $connection);
if(!$dbconnect){
die('Could not connect to Database');
}
else{
$query = "INSERT INTO res_club (FirstName, LastName) VALUES ('$a','$b')";
mysql_query($query, $connection) or die(mysql_error());
echo 'Successfully added.';
echo $query;
echo $a.$b;
}
}
?>
</code></pre>
<p>An empty row is added to the database, with no first name and last name. The PHP file doesn't get the <code>$_Post['a']</code> and b</p>
<p>The echo statement, <code>echo $a.$b</code> stays blank too. No errors are shown.</p>
| 0 |
Android - How to test if the microphone is working
|
<p>I'm working on a diagnosis app, I want to know how can I test that the microphone is working properly? I tried looking but could not find any code.
From working properly i mean that its not broken and it functions properly. Is there any way?</p>
| 0 |
How to install a module on Python?
|
<p>Okay, so, I'm actually a beginner in programming Python, and I only found out yesterday how you were supposed to encode <code>pip install ModuleName</code> in the Python command line and not in the interactive shell. I'm trying to download a lot of modules, such as the Send2Trash module, Pyperclip, Requests, Beautiful Soup, and Selenium.</p>
<p>Before I checked the forums about installing modules, I found out how we needed to have the pip tool. I'm a Windows user, but for some reason, I didn't have the 'Scripts' folder installed when I downloaded Python. I didn't know we needed it, so I used raw scripts from GitHub, setup.py, and copy pasted the script into the File Editor in Python, ran it in the interactive shell, and tried to import the module I needed. It worked for the Pyperclip and the Requests module; no errors popped up after I imported them using <code>import pyperclip</code> or <code>import requests</code>, but when I tried the same procedure for the rest of the modules I needed, there were some errors.</p>
<p>Also, when I tried to download the modules on pypi.python.org, I tried to open it using the interactive shell, but then something pops up, 'The file's encoding is invalid for Python3.x...', and when I click 'OK', it's going to say 'Failed to Decode', and close everything.</p>
<p>So, after reading forum after forum, I found out how to download pip, and was also able to download setuptools and wheel. I'm not sure if it's <em>really</em> already downloaded, but I was able to get the 'Scripts' folder that wasn't there before, so I guess so. I also already went into my <code>PATH</code> using the edit environment for your account thing, and I edited the <code>Path</code> variable so its value would lead to my 'Scripts' folder. Please do tell me if I did the right thing here.</p>
<p>So, following the advice of the forums, I tried to install the modules I needed by typing <code>pip install ModuleName</code> in the Python command line instead of the interactive shell, but it still gave me a Syntax Error. I also tried it in Command Prompt, typing the same code <code>pip install ModuleName</code>, but when I clicked Enter, nothing happens; no errors or anything. It seemed like my install was accepted, but when I tried importing the module in the interactive shell, it still gave an Import Error.</p>
<p>Please tell me what I did wrong throughout my process, and how to properly install the modules I need. I would include pictures into this, but it seems I can only add two before my reputation becomes 10, and I'm pretty new here, so... If there's anything I need to elaborate on about my problem, don't hesitate to ask, and I'll try my best.</p>
| 0 |
Link Conda environment with Jupyter Notebook
|
<p>I'm trying to set a good environnement for doing some scientific stuff with python. To do so, I installed Jupyter & miniconda.</p>
<p>Then I want to be able to have different environnement and use them with Jupyter notebooks. So I created two custom envs with conda : py27 and py35.</p>
<pre><code>> conda env list
# conda environments:
#
py27 /Users/***/miniconda3/envs/py27
py35 /Users/***/miniconda3/envs/py35
root * /Users/***/miniconda3
</code></pre>
<p>Then on my notebook I have two kernels <code>python 2</code> and <code>python 3</code>.
Inside a notebook, I get the following with the python3 kernel :</p>
<pre><code>> import sys
> print(sys.executable)
/Users/***/miniconda3/envs/py35/bin/python
</code></pre>
<p>And this with the python2 kernel :</p>
<pre><code>> import sys
> print(sys.executable)
/usr/local/opt/python/bin/python2.7
</code></pre>
<ul>
<li>How can I set the <code>sys.executable</code> to miniconda env for python2 ?</li>
<li>How can I bind a conda env with a notebook kernel ?</li>
<li>Is doing <code>source activate py35</code> has a link with <code>jupyter notebook</code> ?</li>
</ul>
<p>I think I really missed something.</p>
<p>Thank you everyone.</p>
<p>--- edit</p>
<p>I have multiple jupyter bin :</p>
<pre><code>> where jupyter
/usr/local/bin/jupyter
/usr/local/bin/jupyter
/Users/ThomasDehaeze/miniconda3/bin/jupyter
</code></pre>
<p>I have only one kernel here <code>/usr/local/share/jupyter/kernels/python2</code>.
But inside Jupyter, I have two kernels, <code>python2</code> and <code>python3</code>. Where can I find the other one ?</p>
<hr>
<p>I modified <code>kernel.json</code> from <code>/usr/local/share/jupyter/kernels/python2</code> :</p>
<pre><code>{
"display_name": "Python 2",
"language": "python",
"argv": [
"/Users/***/miniconda3/envs/py27/bin/python2.7",
"-m",
"ipykernel",
"-f",
"{connection_file}"
]
}
</code></pre>
<p>And then :</p>
<pre><code>import sys
print(sys.executable)
/usr/local/opt/python/bin/python2.7
</code></pre>
<p>So nothing has changed</p>
| 0 |
Apply GZIP compression to a CSV in Python Pandas
|
<p>I am trying to write a dataframe to a gzipped csv in python pandas, using the following:</p>
<pre><code>import pandas as pd
import datetime
import csv
import gzip
# Get data (with previous connection and script variables)
df = pd.read_sql_query(script, conn)
# Create today's date, to append to file
todaysdatestring = str(datetime.datetime.today().strftime('%Y%m%d'))
print todaysdatestring
# Create csv with gzip compression
df.to_csv('foo-%s.csv.gz' % todaysdatestring,
sep='|',
header=True,
index=False,
quoting=csv.QUOTE_ALL,
compression='gzip',
quotechar='"',
doublequote=True,
line_terminator='\n')
</code></pre>
<p>This just creates a csv called 'foo-YYYYMMDD.csv.gz', not an actual gzip archive.</p>
<p>I've also tried adding this:</p>
<pre><code>#Turn to_csv statement into a variable
d = df.to_csv('foo-%s.csv.gz' % todaysdatestring,
sep='|',
header=True,
index=False,
quoting=csv.QUOTE_ALL,
compression='gzip',
quotechar='"',
doublequote=True,
line_terminator='\n')
# Write above variable to gzip
with gzip.open('foo-%s.csv.gz' % todaysdatestring, 'wb') as output:
output.write(d)
</code></pre>
<p>Which fails as well. Any ideas? </p>
| 0 |
Reading Cifar10 dataset in batches
|
<p>i am trying to read the CIFAR10 datasets, given in batches from <a href="https://www.cs.toronto.edu/~kriz/cifar.html" rel="nofollow">https://www.cs.toronto.edu/~kriz/cifar.html</a>>. i am trying to put it in a data frame using pickle and read 'data' part of it. But i am getting this error .</p>
<pre><code>KeyError Traceback (most recent call last)
<ipython-input-24-8758b7a31925> in <module>()
----> 1 unpickle('datasets/cifar-10-batches-py/test_batch')
<ipython-input-23-04002b89d842> in unpickle(file)
3 fo = open(file, 'rb')
4 dict = pickle.load(fo, encoding ='bytes')
----> 5 X = dict['data']
6 fo.close()
7 return dict
</code></pre>
<p>KeyError: 'data'.</p>
<p>i am using ipython and here is my code :</p>
<pre><code>def unpickle(file):
fo = open(file, 'rb')
dict = pickle.load(fo, encoding ='bytes')
X = dict['data']
fo.close()
return dict
unpickle('datasets/cifar-10-batches-py/test_batch')
</code></pre>
| 0 |
Scheduling: execute tasks only one time in spring boot
|
<p>Im trying to manage scheduled tasks using spring boot. I want to execute my job <strong>only one time at a particular date</strong> ( specified by the user ). User can add dates for execution as much as he wants.Here is my Job : </p>
<pre><code>@Component
public class JobScheduler{
@Autowired
ServiceLayer service;
@PostConstruct
public void executeJob(){
try {
service.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
<p>And here is the execute method : </p>
<pre><code>private TaskScheduler scheduler;
Runnable exampleRunnable = new Runnable(){
@Override
public void run() {
System.out.println("do something ...");
}
};
@Override
@Async
public void execute() throws Exception {
try {
List<Date> myListOfDates = getExecutionTime(); // call dao to get dates insered by the user
ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();
scheduler = new ConcurrentTaskScheduler(localExecutor);
for(Date d : myListOfDates ){
scheduler.schedule(exampleRunnable, d);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
</code></pre>
<p>Issue 1 : Im using PostConstruct annotation. Thus, when executeJob method is called, there is no dates in the List 'myListOfDates'.</p>
<p>Issue 2 : Supposing that myListOfDates contains dates, how can i get the latest dates in case user entered another one? </p>
<p>Issue 3 : If i use @Scheduled(initailDelay=10000, fixedRate=20000) instead of @PostConstruct annotation, it will resolve the first issue, but it will execute my job every 20s for instance.</p>
<p>Any clue ?</p>
| 0 |
Sliding up image with Official Support Library 23.x.+ bottomSheet like google maps
|
<p><strong>Update</strong><br>
I want to accomplish the same behavior that google maps have <strong>with Support Library 23.x.+ and without ANY 3rd library</strong><br><br></p>
<p>NOTE: this is not a duplicated question because:<br></p>
<ol>
<li>I want to use Behaviors, Support Library and without ANY 3rd party library (I added it in question title and above description)<br></li>
<li>I wanted <strong>ALL behaviors</strong> that you see in the next gif, the other questions are asking for one or two behaviors and using anyway to achieve it.
<br><br>
<a href="https://cloud.githubusercontent.com/assets/5357526/11641271/097c35d0-9d40-11e5-94c6-f9bef5f5ab9d.gif" rel="nofollow noreferrer"><img src="https://cloud.githubusercontent.com/assets/5357526/11641271/097c35d0-9d40-11e5-94c6-f9bef5f5ab9d.gif" alt="like you can see in this gif" /></a></li>
</ol>
<p>I have already the Official bottomSheet working (even inside a tab and view pager).</p>
<p>What is making me going crazy <strong>is how to achieve the image behavior that comes up from the BottomSheet when sliding up using the official bottomSheet?</strong>.<br><br>
I have tried using anchor like FAB with no success.<br>
I read something about using a scroll listener but ppl said it's not smooth and faster like google maps.
<br><br>
My XML (I don't think it's going to help but anyway):<br><br></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MasterActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:layout_scrollFlags="scroll|enterAlways|snap">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/borderlessButtonStyle"
android:text="Departure"
android:layout_gravity="center"
android:id="@+id/buttonToolBar"
/>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@android:color/white"
app:tabTextColor="@color/colorAccent"
app:tabSelectedTextColor="@color/colorAccent"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.v4.widget.NestedScrollView
android:id="@+id/asdf"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:behavior_peekHeight="100dp"
android:fitsSystemWindows="true"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<LinearLayout
android:id="@+id/qwert"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="16dp"
android:background="@android:color/white"
android:padding="15dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BOOTOMSHEET TITLE"
android:textAppearance="@style/TextAppearance.AppCompat.Title" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text 2"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text 3"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text 4"
android:layout_margin="10dp"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="320dp"
android:background="@color/colorAccent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Your remaining content here"
android:textColor="@android:color/white" />
</FrameLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_anchor="@id/asdf"
app:layout_anchorGravity="top|right|end"
android:src="@drawable/abc_ic_search_api_mtrl_alpha_copy"
android:layout_margin="@dimen/fab_margin"
android:clickable="true"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
| 0 |
ReactNative: how to center text?
|
<p>How to center Text in ReactNative both in horizontal and vertical? </p>
<p>I have an example application in rnplay.org where <strong>justifyContent="center"</strong> and <strong>alignItems="center"</strong> is not working:
<a href="https://rnplay.org/apps/AoxNKQ" rel="noreferrer">https://rnplay.org/apps/AoxNKQ</a></p>
<p>The text should being centered.
And why is there a margin at the top between the text (yellow) and parent container?</p>
<p>Code:</p>
<pre class="lang-js prettyprint-override"><code>'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
Image,
View,
} = React;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.topBox}>
<Text style={styles.headline}>lorem ipsum{'\n'}ipsum lorem lorem</Text>
</View>
<View style={styles.otherContainer}>
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'red',
justifyContent: 'center',
alignItems: 'center',
},
topBox: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'lightgray',
justifyContent: 'center',
alignItems: 'center',
},
headline: {
fontWeight: 'bold',
fontSize: 18,
marginTop: 0,
width: 200,
height: 80,
backgroundColor: 'yellow',
justifyContent: 'center',
alignItems: 'center',
},
otherContainer: {
flex: 4,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'green',
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
module.exports = SampleApp;
</code></pre>
| 0 |
how to count number of uploaded files in php
|
<p>How can i count the number of uploaded files?
This is my form:</p>
<pre><code><div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
</form>
</code></pre>
<p>and this is the piece of php which uploads the files:</p>
<pre><code>if($_SERVER['REQUEST_METHOD'] == "POST") {
$tmpFilePath = $_FILES['file']['tmp_name'];
$newFilePath = $dir.'/' . $_FILES['file']['name'];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "xxx files are successfully uploaded";
}
}
</code></pre>
| 0 |
What is the in-place alternative to Array.prototype.filter()
|
<p>I've got an array that I would like to remove some elements from. I can't use <code>Array.prototype.filter()</code>, because I want to modify the array in place (because it saves a memory allocation and, more important for me, makes the code more simple in my use case). Is there an in-place alternative to <code>filter</code> that I can use, maybe analogously to how <a href="https://stackoverflow.com/a/3034430/371137"><code>Array.prototype.forEach()</code> can be used as an in-place variant to <code>Array.prototype.map()</code></a>?</p>
<p>Edit: Minimum example upon request:</p>
<pre><code>function someCallback(array) {
// do some stuff
array.filterInPlace(function(elem) {
var result = /* some logic */
return result;
})
// do some more stuff
}
</code></pre>
| 0 |
PHP PDO SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'events'
|
<p>When I connect to the database using MySQLi, everything works as it should, but with PDO or with CI database methods, I get this error : SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'events'.</p>
<pre><code>try {
$link = new PDO("mysql:host=localhost;dbname=events;");
$link->setAttribute(PDO::ATTR_MODE, PDO::ERR_MODE_EXCEPTION);
//create statement;
$statement = $link->prepare($sql);
$statement->bindParam(":username", $login_request["username"]);
$statement->bindParam(":password", $login_request["password"]);
$statement->execute();
$rows = $statement->fetchColumn();
return ($rows == 1) ? true : false;
}
catch(PDOEXCEPTION $e){
echo $e->getMessage();
}
</code></pre>
| 0 |
SQL Union All with order by and limit (Postgresql)
|
<p>In the following query I get syntax error:</p>
<pre><code>SELECT <property1>, <property2>
FROM <table1>
ORDER BY <condition> LIMIT 1
UNION ALL
SELECT <property1>, <property2>
FROM <table2>
WHERE <condition> ORDER BY <condition> LIMIT 1;
</code></pre>
<blockquote>
<p>syntax error at or near "UNION"
LINE 4: UNION ALL</p>
</blockquote>
<p>Each of the <code>SELECT</code> stand alone executes fine. My guess is about the <code>ORDER BY... LIMIT 1</code> maybe?</p>
| 0 |
Floor division with negative number
|
<p>The expression <code>6 // 4</code> yields <code>1</code>, where floor division produces the whole number after dividing a number. </p>
<p>But with a negative number, why does <code>-6 // 4</code> return <code>-2</code>?</p>
| 0 |
gson.fromJson return null values
|
<p>This is My JSON String : <code>"{'userName' : 'Bachooo'}"</code></p>
<p>Converting JSON String to <strong>LoginVO</strong> logic is:</p>
<pre><code>Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
LoginVO loginFrom = gson.fromJson(jsonInString, LoginVO.class);
System.out.println("userName " + loginFrom.getUserName()); // output null
</code></pre>
<p>My <strong>LoginVO.class</strong> is:</p>
<pre><code>public class LoginVO {
private String userName;
private String password;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
</code></pre>
<p>Note I am using <strong>jdk 1.8.0_92</strong> </p>
<p>Output of loginForm.getUserName() is <code>NULL</code> instead of <code>"Bachooo"</code> any idea about this issue?</p>
| 0 |
How to monitor free disk space at AWS EC2 with Cloud Watch in windows
|
<p>I want to make alarm in case that there is 10% left in my disk space.</p>
<p>I read some articles of how monitoring free disk space with Cloud Watch but I think it seems to be only for linux.</p>
<p>Do you have any solution for monitoring free disk space for windows?</p>
<p>Thanks in advance.</p>
| 0 |
Meaning of lib directory in github repositories
|
<p>Most of the time, when I look at projects in github , I see lib/ directory. </p>
<p>I just googled if there is a conventional meaning of lib/ directory. But I couldn't find much.</p>
<p>I would like to know what lib/ directory is for just to choose where to start looking at in github projects. </p>
<p>Project which have lib/ directories. </p>
<p><a href="https://github.com/robrich/orchestrator" rel="noreferrer">orchestrator</a> </p>
<p><a href="https://github.com/gulpjs/gulp" rel="noreferrer">gulp</a> </p>
| 0 |
How to insert jQuery code in Avada theme?
|
<p>I want to insert a simple jQuery code in my Wordpress theme (Avada), something <a href="http://codepen.io/lormski/pen/meXadK/" rel="noreferrer">like this</a>:</p>
<pre><code>$(function() {
$("#tabs").tabs({ show: { effect: "blind", direction: "right", duration:300 }});
$( "#accordion" ).accordion();
var btn = $('#accordion li a');
var wrapper = $('#accordion li');
$(btn).on('click', function() {
$(btn).removeClass('active');
$(btn).parent().find('.addon').removeClass('fadein');
$(this).addClass('active');
$(this).parent().find('.addon').addClass('fadein');
});
});
</code></pre>
<p>In a page, but it doesn't work. </p>
<p>I tried to use different classes to all the HTML elements and to insert my code with a plugin named "CSS & Javascript Tool box", but it didn't helped.</p>
| 0 |
How to Call Onload Function inside table td tag
|
<p>Hiii Everone,</p>
<p>I want to check the condition while load td tag.SO that i tried to check the condition with the help of onload function.Below is the example but the code which i tried inside onload is not working please any one help me to get out of this problem.Sceneraio is inside td there will be two button if the condition inside check_course is greater than 1 it will show button 1 or else button 2.</p>
<p>PHP Code</p>
<pre><code><?php
date_default_timezone_set('Asia/Kolkata');
$date = date("Y-m-d");
$time = date("Y-m-d H:i:s");
require "country.php";
$per_email=$_POST['per_email'];
$stream_name=$_POST['specialization_filter'];
$country_filter=$_POST['country_filter'];
$country = new country();
$users = $country->universities($stream_name,$country_filter);
if ( empty($users) ) {
?>
<br/><br/>
<?php echo "<span class=\"alert alert-danger\">No universities Available For Your Search Results!!! </span> <br>" ;
}else{
?>
<div class="table-responsive" id="filter_universities">
<table class="table no-border">
<thead >
<tr class="row_univ">
<th class="university_sort" id="name_total_sort" status="asc" style="cursor:pointer">University
<i class="fa fa-caret-down font-grey-salsa"></i>
</th>
<th class="col-md-3">Program</th>
<th class="fee_structure" id="fee_total_sort" status="asc" style="cursor:pointer">Fee
<i class="fa fa-caret-down font-grey-salsa"></i>
</th>
</tr>
</thead>
<tbody>
<?php
$i=0;
foreach ($users as $user){
$i++;
?>
<tr class="tr_bgs">
<td class="col-md-4">
<div class="row">
<div class="col-md-3">
<img src="images/university1.jpg" class="img-circle" width="62px" height="62px" alt="">
</div>
<div class="col-md-9">
<h5 class="bold fees">
<a target="_blank" class="university_class" mode="ambitious" cid="292"><?php echo $user['university']?> </a>
</h5>
<span class="font-grey-lite"><?php echo $user['country']?> </span>
</div>
</div>
</td>
<td>
<h5 class="bold fees"> <?php echo $user['course']?> </h5>
<span class="font-grey-lite"> <?php echo $user['stream_name']?> </span>
</td>
<td>
<h5 class="bold fees"><?php echo $user['fees']?> </h5>
<span class="font-grey-lite">Per Year</span>
</td>
<td class="text-center" id="course_button" onload="check_course(<?php echo $user['id']?>);">
<div id="added_course<?php echo $user['id']?>"><br/><button type="button" class="btn btn-primary" onClick="delete_course_list(<?php echo $user['id']?>);">
<i class="fa fa-star" aria-hidden="true"></i>&nbsp;Course Added</button></div>
<div id="add_course<?php echo $user['id']?>">
<br/><button type="button" class="btn btn-primary"
onClick="save_course_list(<?php echo $user['id']?>);">
<i class="fa fa-star-o" aria-hidden="true"></i>&nbsp;Add to My Course</button></div>
</td>
</tr>
<tr class="row_univ tr_bgs">
<td colspan="6">
<table class="table no-border no-margin text-grey">
<tbody>
<tr class="tr_bgs">
</tr>
</tbody>
</table>
</td>
</tr>
<?php
}
} ?>
</tbody>
</table>
</div>
</code></pre>
<p>Script</p>
<pre><code>function check_course(variable)
{
var course_id=str;
var per_email= '<?php echo $per_email; ?>' ;
var datas="&course_id="+course_id+"&per_email="+per_email;
alert(datas);
$.ajax({
type: "POST",
url: 'php/country/check_course.php',
data:datas
}).done(function( data )
{
alert(data);
if(data>0)
{
$('#added_course'+str).show();
$('#add_course'+str).hide();
}
else
{
$('#add_course'+str).show();
$('#added_course'+str).hide();
}
});
}
</code></pre>
<p>What mistake i did is there any syntax problem with this.Please help me.Thanks in advance.</p>
| 0 |
Python pandas: Why does df.iloc[:, :-1].values for my training data select till only the second last column?
|
<p>Very simply put, </p>
<p>For the same training data frame <code>df</code>, when I use
<code>X = df.iloc[:, :-1].values</code>, it will select till the second last column of the data frame instead of the last column (which is what I want BUT it's a strange behavior I've never seen before), and I know this as the second last column's value and the last column's value for that row is different. </p>
<p>However, using
<code>y = df.iloc[:, -1].values</code> gives me the row vector of the last column's values which is exactly what I want. </p>
<p>Why is the negative 1 for X giving me the second last column's value instead?</p>
<p><img src="https://i.imgur.com/X4jKqIy.png" alt="Error"></p>
| 0 |
Convert scientific notation back to numbers in SQL Server
|
<p>I had data in Excel like</p>
<pre><code>7540006
7540447
</code></pre>
<p>But when I import the data into <code>SQL Server</code>, it is saved as </p>
<pre><code>7.54001e+006
7.54045e+006
</code></pre>
<p>So now when I try to convert it to back to original state, it's not ending up with the correct value.</p>
<p>I have tried following queries for conversion</p>
<pre><code>declare @a varchar(40)
set @a = '7.54001e+006'
declare @b decimal(27, 12)
SELECT @b = CONVERT(REAL, @a, 2)
SELECT LTRIM(RTRIM(str(@a))), LTRIM(STR(@a))
SELECT CAST('7.54001e+006' as REAL)
</code></pre>
<p>and the output I am getting is addition of 3 to original value for all methods
i.e.</p>
<pre><code>7540010
7540050
</code></pre>
<p>How do I convert it back to original state ??</p>
| 0 |
React' findNodeHandle method stopped working
|
<p>After upgrade to <em>0.26.0-rc</em> version, this line:</p>
<pre><code>React.findNodeHandle(this.refs.myRef)
</code></pre>
<p>Throws this error message:</p>
<blockquote>
<p>Unhandled JS Exception: _react2.default.findNodeHandle is not a
function.</p>
</blockquote>
<p>I'm importing React with this:</p>
<pre><code>import React from 'react';
</code></pre>
<p>Docs <a href="https://facebook.github.io/react-native/docs/nativemethodsmixin.html#measurelayout" rel="noreferrer">still say</a>:
<em>"As always, to obtain a native node handle for a component, you can use React.findNodeHandle(component)."</em></p>
| 0 |
nodemon app crashed - waiting for file changes before starting
|
<p><strong>EDIT</strong>
After further testing, I have found that this is happening with both gulp and grunt on this app and on the default install of mean.js. I'm running this locally on a Mac. When I running either app using "node server.js" they don't crash.</p>
<p>I'm using a MEAN stack with grunt-nodemon and node is crashing when an express URL is accessed. It isn't always consistent though. Sometimes it works, sometimes node crashes right when the URL is hit retiring no data, and other times I get a response and node crashed immediately after.</p>
<p><strong>Browser console response:</strong> </p>
<pre><code>http://localhost:8000/api/users net::ERR_CONNECTION_REFUSED
</code></pre>
<p><strong>Terminal output:</strong></p>
<pre><code>Mongoose: users.insert({ firstname: 'mike', lastname: 'jones', email:'[email protected]', role: 'admin', password: 'mike', _id: ObjectId("57485c16fc11894b96c28057"), created: new Date("Fri, 27 May 2016 14:39:18 GMT"), __v: 0 })
user.save success
node crash
[nodemon] app crashed - waiting for file changes before starting...
</code></pre>
<p>In this case, the POST request went through, the user was added, then node crashed, but sometimes it crashes before a successful POST. Node also occasionally crashes on the GET request. </p>
<p><strong>gruntfile.js:</strong></p>
<pre><code>module.exports = function(grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
var pkg = grunt.file.readJSON('package.json');
var options = {
paths: {
app: 'app',
assets: 'app/assets',
dist: 'app/dist',
distAssets: 'app/dist/assets',
html: 'app/html',
htmlTmp: '.tmp/htmlsnapshot',
htmlAssets: 'app/html/assets',
index: 'app/dist/index.html',
indexDev: 'app/index.html',
indexTmp: '.tmp/html/index.html'
},
pkg: pkg,
env: {
test: {
NODE_ENV: 'test'
},
dev: {
NODE_ENV: 'development'
},
prod: {
NODE_ENV: 'production'
}
}
};
// Load grunt configurations automatically
var configs = require('load-grunt-configs')(grunt, options);
// Define the configuration for all the tasks
grunt.initConfig(configs);
// Connect to the MongoDB instance and load the models
grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () {
// Get the callback
var done = this.async();
// Use mongoose configuration
var mongoose = require('./config/lib/mongoose.js');
// Connect to database
mongoose.connect(function (db) {
done();
});
});
grunt.registerTask('bumper', ['bump-only']);
grunt.registerTask('css', ['sass']);
grunt.registerTask('default', [
'sass',
'copy:dev',
'nodemon',
'concurrent:dev',
'watch',
'mongoose'
]);
grunt.registerTask('shared', [
'clean:demo',
'copy:demo',
'sass',
'ngconstant',
'useminPrepare',
'concat:generated',
'cssmin:generated',
'uglify:generated',
'filerev',
'usemin',
'imagemin',
'usebanner'
]);
grunt.registerTask('demo', [
'shared',
'copy:postusemin',
'grep:demo'
]);
grunt.registerTask('dist', [
'shared',
'copy:postusemin',
'copy:dist',
'grep:dist',
'compress',
'copy:postusemin',
'grep:demo',
]);
grunt.loadNpmTasks('grunt-forever');
};
</code></pre>
<p><strong>default.js</strong></p>
<pre><code>module.exports.tasks = {
// version update
bump: {
options: {
files: ['package.json', 'bower.json'],
pushTo: 'origin'
}
},
// application constants
ngconstant: {
options: {
dest: '<%= paths.assets %>/js/app.constants.js',
name: 'app.constants',
}
},
// remove all bs from css
cssmin: {
options: {
keepSpecialComments: 0
}
},
markdown: {
all: {
files: [
{
src: 'README.md',
dest: '<%= paths.assets %>/tpl/documentation.html'
}
],
options: {
template: '<%= paths.assets %>/tpl/_documentation_template.html',
}
}
}
};
</code></pre>
<p><strong>dev.js:</strong></p>
<pre><code>var _ = require('lodash'),
defaultAssets = require('./assets/default'),
testAssets = require('./assets/test'),
testConfig = require('./env/test'),
fs = require('fs'),
path = require('path');
module.exports.tasks = {
// copy files to correct folders
copy: {
dev: {
files: [
{ expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/font-awesome/fonts', dest: '<%= paths.assets %>/fonts' },
{ expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/material-design-iconic-font/fonts', dest: '<%= paths.assets %>/fonts' },
{ expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/roboto-fontface/fonts', dest: '<%= paths.assets %>/fonts' },
{ expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/weather-icons/font', dest: '<%= paths.assets %>/fonts' },
{ expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/bootstrap-sass/assets/fonts/bootstrap', dest: '<%= paths.assets %>/fonts' }
]
}
},
// watch for changes during development
watch: {
js: {
files: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
css: {
files: [
'<%= paths.assets %>/css/**/*.scss'
],
tasks: ['sass'],
options: {
livereload: true
}
},
markdown: {
files: [
'README.md'
],
tasks: ['markdown']
},
tasks: [ 'express:dev' ],
},
// debug while developing
jshint: {
all: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js']
},
concurrent: {
dev: {
tasks: ['nodemon', 'node-inspector', 'watch'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug'],
ext: 'js,html',
callback: function (nodemon) {
nodemon.on('crash', function (event) {
console.log(event);
});
},
watch: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
}
}
},
forever: {
server1: {
options: {
index: 'server.js',
//logDir: 'logs'
}
}
}
};
</code></pre>
<p><strong>Angular controller function:</strong></p>
<pre><code> $scope.addUser = function(){
var user = {
firstname: $scope.firstname,
lastname: $scope.lastname,
email: $scope.email,
role: $scope.role.selected,
password: $scope.password
};
$http.post('/api/userAdd', user ).then(function successCallback(response) {
$location.path('/users');
}, function errorCallback(response) {
console.log('error addding user');
console.log(response);
});
};
</code></pre>
<p><strong>Express route:</strong> </p>
<pre><code>User = require('../models/user.js');
module.exports = function (app) {
app.get('/api/users', function (req, res) {
User.find({}, function (err, users) {
if ( err ) {
res.send({
message : 'error finding users',
success: false
});
} else {
res.json(users);
}
});
});
app.get('/api/users', function (req, res) {
User.find({fields: {}}, function (err, docs) {
res.json(docs);
});
});
app.post('/api/userAdd', function (req, res) {
var user = new User(req.body);
user.save( function( err, user ){
if (err){
console.log('user.save error');
console.log(err);
res.send({
success: false
});
} else {
console.log('user.save success');
res.send({
success: true
});
}
});
});
};
</code></pre>
<p>I'm also testing with Chromes Advanced REST extension and with any request using this tool node crashes immediately. </p>
<p>I'm new to MEAN so am I missing something here that is causing the crash? Any ideas? </p>
| 0 |
How does some apps(wechat) ignore fake location and then detect the real one?
|
<p>I have installed a fake location app and set my location different. Then opened Google Maps and Wechat app, </p>
<ul>
<li>Google Maps shows my location as what i set(fake)</li>
<li>Wechat app <strong>ignores</strong> fake location and <strong>detects</strong> real location (how?)</li>
</ul>
<p>Then i wanted to prevent wechat analyze my previously received real locations and new fake location.</p>
<ul>
<li>Uninstalled Wechat</li>
<li>Restarted my device</li>
<li>Set my location as fake</li>
<li>Installed Wechat again</li>
</ul>
<p>But same result, it detects my real location.</p>
<p>I really want to understand how they do this. Any ideas?</p>
<hr>
<p><strong>What i have tried</strong> </p>
<ul>
<li>Gps provider spoof</li>
<li>Network provider spoof</li>
<li>Fused location provider spoof</li>
<li>IP geolocation spoof</li>
<li>Gps provider spoof + IP geolocation spoof</li>
</ul>
<hr>
<p><strong>UPDATE</strong></p>
<p>Uses GPS even when disabled. </p>
<p><a href="https://i.stack.imgur.com/CdjXs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CdjXs.png" alt="enter image description here"></a></p>
<p>07-02 11:46:15.504 2346-2356/? D/LocationManagerService: request 434a7e28 gps Request[ACCURACY_FINE gps requested=+1s0ms fastest=+1s0ms] from com.tencent.mm(10173)</p>
<hr>
<p><strong>CONCLUSION</strong></p>
<ul>
<li>You can fake location on older versions of wechat(lower than 6.0)</li>
<li>Uses something like BaiduLocationSDK. It's not affected from any mock attempt through LocationManager and Fused provider.</li>
<li>I'm not sure but, seems like BaiduLocationSDK uses GPS through hardware level.</li>
</ul>
| 0 |
Remove smallest number in JS Array
|
<p>I have a number array [2, 1, 3, 4, 5, 1] and want to remove the smallest number in the list. But somehow my IF statement gets skipped. </p>
<p>I checked and by itself "numbers[i + 1]" and "numbers[i]" do work, but "numbers[i + 1] < numbers[i]" doesn't...</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function removeSmallest(numbers) {
var smallestNumberKEY = 0;
for (i = 0; i <= numbers.lenths; i++) {
if (numbers[i + 1] < numbers[i]) {
smallestNumberKEY = i + 1;
}
}
numbers.splice(smallestNumberKEY, 1);
return numbers;
}
document.write(removeSmallest([2, 1, 3, 4, 5, 1]));</code></pre>
</div>
</div>
</p>
| 0 |
serial in postgres is being increased even though I added on conflict do nothing
|
<p>I'm using Postgres 9.5 and seeing some wired things here.</p>
<p>I've a cron job running ever 5 mins firing a sql statement that is adding a list of records if not existing.</p>
<pre><code>INSERT INTO
sometable (customer, balance)
VALUES
(:customer, :balance)
ON CONFLICT (customer) DO NOTHING
</code></pre>
<p>sometable.customer is a primary key (text)</p>
<p><strong><em>sometable structure is:</em></strong><br>
id: serial<br>
customer: text<br>
balance: bigint </p>
<p>Now it seems like everytime this job runs, the id field is silently incremented +1. So next time, I really add a field, it is thousands of numbers above my last value. I thought this query checks for conflicts and if so, do nothing but currently it seems like it tries to insert the record, increased the id and then stops.</p>
<p>Any suggestions?</p>
| 0 |
Laravel 5.2 form validation request not working properly
|
<p>When I hit submit button nothing happens its just refreshing the page.</p>
<p>Here's my code:</p>
<p><strong>app/Http/routes.php</strong></p>
<pre><code>Route::group(['middleware' => ['web']], function () {
Route::get('profile/edit', 'UserController@editProfile');
Route::post('update_name', 'UserController@updateName');
});
</code></pre>
<p><strong>app/Http/Request/UpdateNameRequest.php</strong></p>
<pre><code><?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Auth;
class UpdateNameRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'first_name' => 'required|min:2|alpha',
'last_name' => 'required|min:2|alpha',
];
}
}
</code></pre>
<p><strong>app/Http/Controllers/UserController.php</strong></p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\User;
class UserController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function editProfile() {
if (Auth::user()->role_id === 3) {
return view('profile.crew.edit');
}
}
public function updateName(Requests\UpdateNameRequest $request) {
return dd($request->all());
}
}
</code></pre>
<p><strong>and here's the html form</strong></p>
<pre><code>{!! Form::open(array('url' => 'update_name')) !!}
<div class="form-group{{ $errors->has('first_name') ? ' has-error' : '' }}">
<label class="control-label">First Name</label>
<input type="text" class="form-control" name="first_name" value="{{ old('first_name') }}" placeholder="{{ Auth::user()->first_name }}">
@if ($errors->has('first_name'))
<span class="help-block">
<strong>{{ $errors->first('first_name') }}</strong>
</span>
@endif
</div>
<div class="form-group{{ $errors->has('last_name') ? ' has-error' : '' }}">
<label class="control-label">Last Name</label>
<input type="text" class="form-control" name="last_name" value="{{ old('last_name') }}" placeholder="{{ Auth::user()->last_name }}">
@if ($errors->has('last_name'))
<span class="help-block">
<strong>{{ $errors->first('last_name') }}</strong>
</span>
@endif
</div>
<button type="submit" class="btn btn-success">Update name</button>
{!! Form::close() !!}
</code></pre>
<p><strong>for reference heres the form output</strong></p>
<pre><code><form method="POST" action="http://localhost:8000/update_name" accept-charset="UTF-8">
<input name="_token" type="hidden" value="VViupfPaPCQCk5aeUdc27Pt2Z8J7Hx1Y2khC0IY9">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" class="form-control" name="first_name" value="" placeholder="Hans">
</div>
<div class="form-group">
<label class="control-label">Last Name</label>
<input type="text" class="form-control" name="last_name" value="" placeholder="Padberg">
</div>
<button type="submit" class="btn btn-success">Update name</button>
</form>
</code></pre>
<p><strong>here's my output in php artisan route:list</strong></p>
<pre><code>+--------+----------+-------------------------+------+-----------------------------------------------------------------+--------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+--------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | home | | App\Http\Controllers\HomeController@index | web,web,auth |
| | GET|HEAD | login | | App\Http\Controllers\Auth\AuthController@showLoginForm | web,guest |
| | POST | login | | App\Http\Controllers\Auth\AuthController@login | web,guest |
| | GET|HEAD | logout | | App\Http\Controllers\Auth\AuthController@logout | web |
| | POST | password/email | | App\Http\Controllers\Auth\PasswordController@sendResetLinkEmail | web,guest |
| | POST | password/reset | | App\Http\Controllers\Auth\PasswordController@reset | web,guest |
| | GET|HEAD | password/reset/{token?} | | App\Http\Controllers\Auth\PasswordController@showResetForm | web,guest |
| | GET|HEAD | profile | | App\Http\Controllers\UserController@getProfile | web,web,auth |
| | GET|HEAD | profile/edit | | App\Http\Controllers\UserController@editProfile | web,web,auth |
| | GET|HEAD | register | | App\Http\Controllers\Auth\AuthController@showRegistrationForm | web,guest |
| | POST | register | | App\Http\Controllers\Auth\AuthController@register | web,guest |
| | POST | update_email | | App\Http\Controllers\UserController@updateEmail | web,web,auth |
| | POST | update_name | | App\Http\Controllers\UserController@updateName | web,web,auth |
| | POST | update_password | | App\Http\Controllers\UserController@updatePassword | web,web,auth |
| | POST | update_profile_picture | | App\Http\Controllers\UserController@updateProfilePicture | web,web,auth |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+--------------+
</code></pre>
| 0 |
How can I add a shadow to bottom sheet view?
|
<p>As of now, with the official bottom sheet component from the Android design library implemented the top edge doesn't show a shadow. But for what I've seen in various mockups and in the Material Design specs, the bottom sheet include a discrete shadow of some sort.</p>
<p>I think the shadow would help distant the bottom sheet from the main layout, especially if there's a peek value set and/or the bottom sheet is always visible. Otherwise it just will blend together with the main layout and its items.</p>
<p>I've tried both <code>ViewCompat.setElevation(bottomSheet, 5);</code> and setting <code>android:elevation="5dp"</code> to the view in the XML, without success.</p>
<p><a href="https://i.stack.imgur.com/eWpb3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eWpb3.png" alt="Bottom sheet example from Material Design specs"></a></p>
| 0 |
Hibernate expected NUMBER got BINARY on null field
|
<p>I can't understand why Hibernate is trying to set this field as a VARBINARY when it is null.</p>
<p>The Java data type is BigDecimal
The Oracle data type is Float</p>
<p>It is being set like this:</p>
<pre><code>entityManager.createNamedQuery("blah").setParameter("target_field", object.sourceValue)
</code></pre>
<p>again - sourceValue is a BigDecimal, and when i debug it the value is null.</p>
<p>when it tries to execute this update, I get oracle error: </p>
<pre><code>ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
</code></pre>
<p>this is what shows up for this property in the console log:</p>
<pre><code>o.h.type.descriptor.sql.BasicBinder : binding parameter [8] as [VARBINARY] - [null]
</code></pre>
<p>IF I do this silly hack in Java before I execute the update:</p>
<pre><code>if (object.sourceValue == null) object.sourceValue = new java.math.BigDecimal(0);
</code></pre>
<p>Then it runs fine. So the cause of this error is definitely not anything else than hibernate doing something wrong when the field is null.</p>
<p>How do I fix this so I can set the field to null without hibernate mishandling it?</p>
<p>In the DB, the field is nullable.</p>
| 0 |
Eclipse- How to remove jars which are added "from class path" of referenced library
|
<p>I use eclipse. I just added two jars into my project as library >Add external jar . As in below picture, all other jars in the folder are coming to my project as referenced library. How to remove this. Are these really required ? After I compiled, the app jar file size is much bigger than I expected. </p>
<p><a href="https://i.stack.imgur.com/eHrGW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eHrGW.png" alt="enter image description here"></a></p>
<p>tool tip shows-<code>from class path of .jar</code></p>
<p><a href="https://i.stack.imgur.com/0i30o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0i30o.png" alt="enter image description here"></a></p>
| 0 |
Concat two nodelists
|
<p>I am trying to concat two nodelists using</p>
<pre><code>var ul = document.querySelector("ul");
var down = document.getElementsByClassName("mobile")[0];
var ul_child = Array.prototype.concat.call(ul.children,down.children);
</code></pre>
<p>But this returns only two nodes from ul nodelist and ignore others. What is the most valid to concat two nodelsits? I would like to avoid brute looping them </p>
| 0 |
Why there is no do while loop in python
|
<p>Why doesn't Python have a 'do while' loop like many other programming language, such as C?</p>
<p>Example : In the C we have do while loop as below : </p>
<pre><code>do {
statement(s);
} while( condition );
</code></pre>
| 0 |
Password Cracker of Protected Sheet in Excel 2013 and Later using VBA
|
<p>Anybody knows if there are other ways to crack a password of a protected sheet in excel? I have been using these codes ever since but now, it doesn't seem to work anymore. The file just says "Not Responding" every time I run the code. I'm using MS Office 2013.</p>
<pre><code>Sub PasswordBreaker()
'Breaks worksheet password protection.
Dim i As Integer, j As Integer, k As Integer
Dim l As Integer, m As Integer, n As Integer
Dim i1 As Integer, i2 As Integer, i3 As Integer
Dim i4 As Integer, i5 As Integer, i6 As Integer
On Error Resume Next
For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
If ActiveSheet.ProtectContents = False Then
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
Exit Sub
End If
Next: Next: Next: Next: Next: Next
Next: Next: Next: Next: Next: Next
End Sub
</code></pre>
| 0 |
JavaFX new custom pop out window
|
<p>I am searching for the example of pop out windows in JavaFX.
I have JavaFX application and at one point I need a pop out window to appear. this popout windows needs some complicated inputs which I need to process and check and come back to main appliation/window. </p>
<p>Now the problem is I can not find anywhere an example how in one JavaFX controller class call now JavaFX pop out window? I only find examle how to make Dialog pop out windows but I can not find example of a new pop out window based on JavaFX (I saw one solution where there is two windows in paralel but I would need one to be created only when needed).</p>
<p>Do you know of such example of JavaFx custom popout window?</p>
| 0 |
Unexpected character ('F' (code 70)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') What does it mean?
|
<p>I am trying to access a url using rest client</p>
<p>My Client Code:</p>
<pre><code> public class ProductByListTestClient {
// private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) {
ProductByListTestClient http = new ProductByListTestClient();
try {
http.sendPost();
} catch (Exception e) {
e.printStackTrace();
}
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://localhost:7111/product.lookup.tobuylist/rest/product/productbuylist";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
// con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "{\"itemID\":F123}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
</code></pre>
<p>}</p>
<p>Root cause of <code>ServletException</code>:</p>
<pre class="lang-none prettyprint-override"><code>org.codehaus.jackson.JsonParseException: Unexpected character ('F' (code 70)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: weblogic.servlet.internal.ServletInputStreamImpl@186948; line: 1, column: 12]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:306)
at org.codehaus.jackson.impl.Utf8StreamParser._handleUnexpectedValue(Utf8StreamParser.java:2084)
at org.codehaus.jackson.impl.Utf8StreamParser.nextToken(Utf8StreamParser.java:549)
Truncated. see log file for complete stacktrace
</code></pre>
| 0 |
HTML input that takes only numbers and the + symbol
|
<p>I am trying to build a custom text input for phone numbers that accepts only numbers and the plus (+) symbol; all other characters need to be discarded and not shown on the field.</p>
<p>I am trying to do this using an event handler (onkeydown/onkeypress) and discarding inputs corresponding to other keys. However, I can't figure out a cross-browser way to do it. Here are the approaches that I have tried and don't work:</p>
<ul>
<li><p><strong>Using the onkeypress event and looking at event.key</strong> to figure out which key was pressed: doesn't work on Chrome (see <a href="http://caniuse.com/keyboardevent-key" rel="noreferrer">http://caniuse.com/keyboardevent-key</a>). Is there any cross-browser workaround?</p></li>
<li><p><strong>Using the onkeycode event and looking at event.keyCode:</strong> does not work when we need to press multiple keys to print a character (for instance, an English keyboard layout requires pressing Shift and = to give +). Furthermore, it allows characters such as !@#$%ˆ&*() to appear, as these appear when pressing Shift and a number. (This is the approach followed in <a href="https://stackoverflow.com/questions/5535449/javascript-keycode-allow-number-and-plus-symbol-only">JavaScript keycode allow number and plus symbol only</a>, but it does not help me much ;))</p></li>
<li><p><strong>Using the HTML pattern attribute:</strong> this does not really seem to prevent people from writing whatever they feel like.</p></li>
</ul>
<p>Thanks!</p>
| 0 |
Winsock server/client application in c#
|
<p>I'm working to make a Client/Server Application in C# using winsock Control. I done every thing in that but i stuck the place of sending data from client to server. In my program server always listen the client using the ip and port. I send the data from the client to server. </p>
<p>1)When click the Listen button on the server form it open the server where client is connect.</p>
<p>2)In Client form 1st i click the connect button for that the server is connected Gives an message (Connect Event: ip) for this message we easly know that the client is connected to the server.</p>
<p>3)Then we enter some data in the Send Data text Box then click Send Button to send the data to server and also save in client.</p>
<p>Code Below:</p>
<p><strong>SERVER:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const string DEFAULT_SERVER = "ip";
const int DEFAULT_PORT = 120;
System.Net.Sockets.Socket serverSocket;
System.Net.Sockets.SocketInformation serverSocketInfo;
public string Startup()
{
IPHostEntry hostInfo = Dns.GetHostByName(DEFAULT_SERVER);
IPAddress serverAddr = hostInfo.AddressList[0];
var serverEndPoint = new IPEndPoint(serverAddr, DEFAULT_PORT);
serverSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
serverSocket.Bind(serverEndPoint);
return serverSocket.LocalEndPoint.ToString();
}
public string Listen()
{
int backlog = 0;
try
{
serverSocket.Listen(backlog);
return "Server listening";
}
catch (Exception ex)
{
return "Failed to listen" + ex.ToString();
}
}
public string ReceiveData()
{
System.Net.Sockets.Socket receiveSocket;
byte[] buffer = new byte[256];
receiveSocket = serverSocket.Accept();
var bytesrecd = receiveSocket.Receive(buffer);
receiveSocket.Close();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(buffer);
}
private void Listen_Click(object sender, EventArgs e)
{
string serverInfo = Startup();
textBox1.Text = "Server started at:" + serverInfo;
serverInfo = Listen();
textBox1.Text = serverInfo;
//string datatosend = Console.ReadLine();
//SendData(datatosend);
serverInfo = ReceiveData();
textBox1.Text = serverInfo;
//Console.ReadLine();
}
private void winsock_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
{
ReceiveData();
Listen();
}
private void winsock_ConnectEvent(object sender, EventArgs e)
{
Listen();
}
}
}
</code></pre>
<p>This all are work perfectly But here my problem is that i get data form the client to server at only one time. When i send data again from the client to the server its not working and gives me some Message like</p>
<blockquote>
<p>Additional information: Only one usage of each socket address
(protocol/network address/port) is normally permitted</p>
</blockquote>
<p>In the server form </p>
<pre><code>serverSocket.Bind(serverEndPoint);
</code></pre>
<p>Please someone help me to solve my problem.</p>
<p>Thank you.</p>
| 0 |
How do you keep track of your comments on GitHub issues?
|
<p>I want to find all the <a href="https://github.com/" rel="nofollow noreferrer">GitHub</a> issues that I commented on. I tried searching for <code>commenter:mbigras type:issue</code> like the <a href="https://help.github.com/articles/searching-issues/" rel="nofollow noreferrer">Searching issues and pull requests</a> GitHub article suggests. But that method returns fewer results than the public activity section of my profile.</p>
<p>See both attached images:</p>
<h2>Search method</h2>
<p>Doesn't display current results:
<a href="https://i.stack.imgur.com/WDX9e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WDX9e.png" alt="enter image description here" /></a></p>
<h2>Profile method</h2>
<p>Gets mixed up with other public activity:
<a href="https://i.stack.imgur.com/szu3n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/szu3n.png" alt="enter image description here" /></a></p>
<p>Is there a way to get the full history of my comments on GitHub?</p>
<p><strong>EDIT</strong></p>
<p><code>author:mbigras type:issue</code> gives wider results but still not the full history:
<a href="https://i.stack.imgur.com/KbZ5Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KbZ5Q.png" alt="enter image description here" /></a></p>
<p>What I'm looking for is a way to quickly view all my comment/issue history in all issues.</p>
<p><strong>EDIT</strong></p>
<p>I emailed GitHub about this. Search doesn't match the public activity section because search indexes issues by <em>creation date</em> and not <em>last active date</em>.</p>
<p>How do you keep organized about which issues you've commented on?</p>
| 0 |
PHP Fatal error: Out of memory (allocated 1707606016) (tried to allocate 426680697 bytes)
|
<p>I have a droplet on DigitalOcean, it was a 10$ package with 1GB Memory, then I upgraded to 20$ package.</p>
<p>So how it all started was that I'm trying to upload a file from one server to another using cURL parameters, now the issue is... The file doesn't send because I get this beautiful error.</p>
<pre><code>PHP Fatal error: Out of memory (allocated 1707606016) (tried to allocate 426680697 bytes)
</code></pre>
<p>Now I have <code>memory_limit</code> set to 2048MB because that's how much MB of memory I got on my VPS. Now before I upgraded, I had only 1024MB of memory and the error message was different at the time, and this is what I got.</p>
<pre><code>PHP Fatal error: Out of memory (allocated 530055168) (tried to allocate 529639729 bytes)
</code></pre>
<p>My VPS has MORE than enough memory to upload a 403MB file, and I have my memory_limit maxed, there's no way I need to upgrade the servers memory limit.</p>
<pre><code>memory_limit = 2048M
file_uploads = On
upload_max_filesize = 5000M
max_file_uploads = 20
allow_url_fopen = On
post_max_size = 0
max_execution_time = 90000
max_input_time = 90000
</code></pre>
<p>Obviously it may look like a duplicate, but the solutions on all of the posts I've looked at <strong>don't</strong> work for me. The script that is having its memory_limit is literally a handler that handles the cURL request sent from the alternative server. </p>
| 0 |
SQL Server database: INSERT query blocked with wait type LCK_M_IX
|
<p>Our Java application cleans up the data from log table through a cron job. Here is the query which is executed for clean up:</p>
<pre><code>DELETE FROM AU_TRANSACTIONDATA
WHERE AU_ACTIVITYENDTIME != 0
AND AU_ACTIVITYENDTIME <= 1464570001151
</code></pre>
<p>We have an index on <code>AU_ACTIVITYENDTIME</code> column of this table:</p>
<pre><code>CREATE INDEX [IX_AU_TRANSDATA_ENDTIME]
ON [AU_TRANSACTIONDATA]([AU_ACTIVITYENDTIME]) ON [PRIMARY];
</code></pre>
<p>Our application dumps transaction data (generated on execution of APIs in our application) into this table. Here is the INSERT query:</p>
<pre><code>INSERT INTO AU_TRANSACTIONDATA (AU_TRANSACTIONID, AU_TRANSACTIONNAME, AU_TRANSACTIONDOMAINID, AU_ACTIVITYNAME, AU_ACTIVITYID, AU_ACTIVITYPID, AU_ACTIVITYTYPE, AU_ACTIVITYSTARTTIME, AU_ACTIVITYENDTIME, AU_ACTIVITYSTATUS, AU_CORRECTDATA, AU_ERRORDATA, AU_USERID, AU_GROUPID, AU_NODENAME, AU_TRANSACTIONDESCRIPTION, AU_SEQUENCEID, AU_TRANSSEQUENCEID)
VALUES (@P0, @P1, @P2, @P3, @P4, @P5, @P6, @P7, @P8, @P9, @P10, @P11, @P12, @P13, @P14, @P15, @P16, @P17)
</code></pre>
<p>We are facing issue when log clean up (<code>DELETE</code> query) and data processing (<code>INSERT</code> query) happens simultaneously. We had around 1.5 million records for clean up, so delete query took some time to clean up the log records. But during that time, processing was blocked and no <code>INSERT</code> queries went through. </p>
<p>Here are the logs:</p>
<pre><code>SPID at Head of Blocking Chain:
SPID [ecid]: 3524 [0]
Blocked by SPID: 0
Client Machine: xxxxx
Client Process ID: 123
Application: jTDS
Login Name: xxxx
Last Batch: 5/30/2016 9:06:56 PM
Wait Type:
Wait Resource:
Wait Time: 00:00:00
Database:
Command Text:
DELETE FROM AU_TRANSACTIONDATA
WHERE AU_ACTIVITYENDTIME != 0 AND AU_ACTIVITYENDTIME <= 1464570001151
----------------------------------------------------------------------
Blocked SPID:
SPID [ecid]: 211 [0]
Client Machine: xxxxx
Client Process ID: 123
Application: jTDS
Login Name: xxxxx
Last Batch: 5/30/2016 9:06:56 PM
Wait Type: LCK_M_IX
Wait Resource: AU_TRANSACTIONDATA.IX_AU_TRANSDATA_ENDTIME
Wait Time: 00:00:24
Database: xxxx
Command Text:
INSERT INTO AU_TRANSACTIONDATA (AU_TRANSACTIONID, AU_TRANSACTIONNAME, AU_TRANSACTIONDOMAINID, AU_ACTIVITYNAME, AU_ACTIVITYID, AU_ACTIVITYPID, AU_ACTIVITYTYPE, AU_ACTIVITYSTARTTIME, AU_ACTIVITYENDTIME, AU_ACTIVITYSTATUS, AU_CORRECTDATA, AU_ERRORDATA, AU_USERID, AU_GROUPID, AU_NODENAME, AU_TRANSACTIONDESCRIPTION, AU_SEQUENCEID, AU_TRANSSEQUENCEID) VALUES ( @P0 , @P1 , @P2 , @P3 , @P4 , @P5 , @P6 , @P7 , @P8 , @P9 , @P10 , @P11 , @P12 , @P13 , @P14 , @P15 , @P16 , @P17 )
</code></pre>
<p>Logs shows that INSERT statements are waiting for resource AU_TRANSACTIONDATA.IX_AU_TRANSDATA_ENDTIME (which denotes an index) with wait type as LCK_M_IX. In some logs, we have seen wait resource to be AU_TRANSACTIONDATA which is table itself.</p>
<p>Can you please explain the following:</p>
<ol>
<li>Why INSERT queries are getting blocked when <code>DELETE</code> query for log clean up is executing?</li>
<li>What is meant by <code>LCK_M_IX</code> wait type and how it can be resolved?</li>
<li>Is <code>DELETE</code> query locking the whole table or places exclusive (X) lock on index?</li>
</ol>
<p>I am not familiar with wait and locking strategies in SQL Server, so any help in this regard shall be appreciated.</p>
<p><strong>EDIT</strong>: We already tried to delete the data in chunks i.e. 10000 rows at a time but it didn't help the cause. Here is the new DELETE query:</p>
<pre><code>SET ROWCOUNT 10000
delete_more:
DELETE FROM AU_TRANSACTIONDATA
WHERE AU_ACTIVITYENDTIME != 0 AND AU_ACTIVITYENDTIME <= 1464570001151
IF @@ROWCOUNT > 0 GOTO delete_more
SET ROWCOUNT 0
</code></pre>
| 0 |
Breaking out of nested loops in R
|
<p>Very simple example code (only for demonstration, no use at all):</p>
<pre><code>repeat {
while (1 > 0) {
for (i in seq(1, 100)) {
break # usually tied to a condition
}
break
}
break
}
print("finished")
</code></pre>
<p>I want to break out from multiple loops without using <code>break</code> in each loop separately.
According to <a href="https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python">a similar question regarding python</a>, wrapping my loops into a function seems to be a possible solution, i.e. using <code>return()</code> to break out of every loop in the function:</p>
<pre><code>nestedLoop <- function() {
repeat {
while (1 > 0) {
for (i in seq(1, 100)) {
return()
}
}
}
}
nestedLoop()
print("finished")
</code></pre>
<p>Are there other methods available in R? Maybe something like labeling loops and then specifying which loop to break (like in Java) ?</p>
| 0 |
How to use CSS absolute position inside a scrollable div element
|
<p>I have the following html. I have multiple elements (e.g div with id = one, two, three) inside a div container which is scrollable.</p>
<p>In each element, I need to use css position 'absolute' which position related to its parent div (i.e. class='Anchor').</p>
<p>The problem I am having is, when I scroll the outer container, none of the div with absolute position moved. My understand is position 'absolute' is it is positioned relatieve to its parent DIV element. Can you please tell me how can I make those 'absolute' position moved as I scroll the outer container?</p>
<pre><code><div style="overflow-y: scroll">
<div>
<div class="Anchor" id="one">
<div style="position: absolute"> something </div>
<div style="position: absolute"> something else </div>
</div>
</div>
<div>
<div class="Anchor" id="two">
<div style="position: absolute"> something </div>
<div style="position: absolute"> something else </div>
</div>
</div>
<div>
<div class="Anchor" id="three">
<div style="position: absolute"> something </div>
<div style="position: absolute"> something else </div>
</div>
</div>
</div>
</code></pre>
| 0 |
How do you set the height and width of a UIButton with image
|
<p>This is driving me nuts. I have looked everywhere and cannot figure this out. Check it out...</p>
<pre><code> let findMeButton = UIButton(type: UIButtonType.System)
findMeButton.translatesAutoresizingMaskIntoConstraints = false
findMeButton.setImage(UIImage(named: "locateMe"), forState: UIControlState.Normal)
findMeButton.addTarget(self, action: #selector(MapViewController.findUserLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(findMeButton)
// I added this line of code and it still doesn't work.
findMeButton.frame.size = CGSizeMake(50, 50)
findMeButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -10).active = true
findMeButton.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor, constant: 5).active = true
</code></pre>
<p>I am still learning iOS. How do you set the Height and Width of this UIButton with an Image. Everything I have tried has given me an error or just didn't work. I am still trying to rap my head around what translatesAutoresizingMaskIntoConstraints does. I just simply want to have the Button where it is but change its size (Height & Width). </p>
<p>Thanks in advance</p>
<p><strong>EDIT:</strong> I have changed the bit of code to this</p>
<pre><code> // Locate user button
let locateButton = UIButton(type: UIButtonType.System) as UIButton
locateButton.frame = CGRectMake(0, 0, 50, 50)
locateButton.setBackgroundImage(UIImage(named: "locateMe"), forState: UIControlState.Normal)
locateButton.addTarget(self, action: #selector(MapViewController.findUserLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(locateButton)
</code></pre>
<p>I want to position the button to the windows bottom and right margin. I also want to set the image dimensions to height 50 x width 50. How would I accomplish this?</p>
<p><strong>EDIT 2:</strong> I figure you have to use Auto Layout to do so but can someone show me how. Everything I have done hasn't worked.</p>
| 0 |
Trim   values in javascript
|
<p>I am trying to trim the text which I get from kendo editor like this. </p>
<pre><code>var html = "&nbsp; T &nbsp;"; // This sample text I get from Kendo editor
console.log("Actual :" + html + ":");
var text = "";
try {
// html decode
var editorData = $('<div/>').html(html).text();
text = editorData.trim();
console.log("After trim :" + text + ":");
}
catch (e) {
console.log("exception");
text = html;
}
</code></pre>
<p>This code is in seperate js file ( generated from typescript). When the page loads the trimming is not working. But when I run the same code in developer tools console window its working.
Why it is not working?</p>
<p>Adding typescript code</p>
<pre><code> const html: string = $(selector).data("kendoEditor").value();
console.log("Actual :" + html + ":");
let text: string = "";
try {
// html decode
var editorData = $('<div/>').html(html).text();
text = editorData.trim();
console.log("After trim :" + text + ":");
}
catch (e) {
console.log("exception");
text = html;
}
</code></pre>
| 0 |
How to make nav-fixed-top push down content like non-fixed navbar?
|
<p>I want to make my navbar fixed on the top and push down content when I open the collapse menu like it normally do in static or just nav.</p>
<p>Like this: (<a href="https://getbootstrap.com/examples/navbar-static-top/" rel="noreferrer">https://getbootstrap.com/examples/navbar-static-top/</a>)
But I want the navbar to be fixed to top.</p>
<p>I read this before: <a href="https://stackoverflow.com/questions/24639086/navbar-fixed-top-pushes-content-on-page-up">Navbar-fixed-top pushes content on page up</a></p>
<p>but adding padding just won't work, please help me solve this xD</p>
<p>My code</p>
<p>CSS & HTML:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*------------------------------------------------- Hero Image -------------------------------------------------*/
.calltoaction {
text-align: center;
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
/* Rules below not implemented in browsers yet */
-o-user-select: none;
user-select: none;
}
.calltoaction h1 {
text-align: center;
display: inline-block;
font-size: 70px;
/*text-transform: uppercase;*/
letter-spacing: 2px;
border: 8px solid #FFFFFF;
border-radius: 13px;
padding: 17px 20px;
color: white;
font-family: sans-serif;
font-weight: 900;
}
.calltoaction h3 {
color: #FFFFFF;
font-size: 29px;
text-align: center;
}
#hero-image {
height: 870px;
background: #e8eced url('http://twnateserver.no-ip.org/Pictures/taiwan-taipei.jpg') no-repeat center;
}
#hero-image h1 {
margin: 215px 0 7px 0;
}
#hero-image h3 {
margin: 3% 0 7px 0;
}
/*#hero-image a {
margin: 3% 0 7px 0;
}*/
/*------------------------------------------------- Hero Image -------------------------------------------------*/
/*------------------------------------------------- navbar----------------------------------------------*/
.navbar {
background-color: rgba(15, 91, 121, 0.03);
background: rgba(15, 91, 121, 0.03);
border-color: rgba(15, 91, 121, 0.03);
margin-bottom: 0px;
/*Line 4213-4217 in Bootstrap.css*/
/*Goal effect: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_navbar_collapse&stacked=h*/
}
.navbar li {
color: #000;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: rgba(233, 237, 239, 0.42);
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(15, 91, 121, 0.03);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
/*Line 4513-4574 in Bootstrap.css define the colors of navbar texts and hover colors*/
/*---------------------------------------------------------------------------------------------------------------*/</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Nate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/index.css" rel="stylesheet">
<script src="js/jquery-2.2.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link rel='shortcut icon' type='image/x-icon' href='favicons/0.ico' />
</head>
<body>
<!-- Fixed Top Navbar, please add middle to top fixed navbar too when you can... -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Nate's Testing Place</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<!-- li class="active" -> transform button to grey -->
<li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span>&nbsp Log in</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<!-- Hero Image and texts -->
<div id="hero-image">
<div class="calltoaction">
<h1><b>Nate's Testing Place</b></h1>
<h3>Just a testing site, always open but not seven-eleven...</h3>
<!--<a href="#" class="btn btn-lg btn-info" role="button">Let's Go</a>-->
</div>
</div>
<!-- Hero Image and texts -->
<div class="containter widgetpadding">
<div class="col-md-4 col-xs-6">
<h4>My First Unity Game: Roller Madness (Project 2 of the coursera course)</h4>
<a href="Test.html" class="btn btn-info" role="button">Play Roller Madness</a>
</div>
<div class="col-md-4 col-xs-6">
<h4>Just a nevbar testing page, css is so tricky......</h4>
<a href="NavTest.html" class="btn btn-info" role="button">Go to nevbar test page</a>
</div>
<div class="col-md-4 col-xs-6">
<h4>Some installation info for installing Kali linux, no installation required now...</h4>
<a href="KaliLinux.html" class="btn btn-info" role="button">Kali Linux Installation info</a>
</div>
<div class="col-md-4 col-xs-6">
<h4>Text Tutorial for dual-booting Arch and Windows10 UEFI......</h4>
<a href="Arch.html" class="btn btn-info" role="button">Arch info</a>
</div>
<div class="col-md-4 col-xs-6">
<h4>Installing arch by installing Antergos is much more easier and pleasant......</h4>
<a href="Antergos.html" class="btn btn-info" role="button">Antergos info</a>
</div>
<div class="col-md-4 col-xs-6">
<h4>sdfsadfsdfsdfasdfawefregergtrhrtyhjytjtyjtyjtyjtyjtyjtyjtyjtryjtryjrtyjrtyjtyj</h4>
<a href="ITX.html" class="btn btn-info" role="button">aetvretevtdsfv</a>
</div>
</div>
<!--Back to Top Widget: http://html-tuts.com/back-to-top-button-jquery/ -->
<div class="">
</div>
<!--Back to Top Widget-->
</body>
</html></code></pre>
</div>
</div>
</p>
| 0 |
Laravel SwiftMailer : Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required
|
<p>I am using laravel 5.2, And the using Swift Mailer for password resetting.
<strong>I have 2-step verification on my gmail.</strong>.</p>
<p>As the google help says :</p>
<hr>
<p>If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.</p>
<hr>
<p>I have the following settings on <code>mail.php</code> :</p>
<pre><code>return [
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 465),
'from' => ['address' => '[email protected]', 'name' => 'Shafee'],
'encryption' => env('MAIL_ENCRYPTION', 'ssl'),
'username' => env('[email protected]'),
'password' => env('MY_Gmail_API_KEY'),
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => env('MAIL_PRETEND', false),
];
</code></pre>
<p>On the <code>.env</code> i have :</p>
<pre><code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=MY_Gmail_API_KEY
MAIL_ENCRYPTION=ssl
</code></pre>
<p>The following error comes up :</p>
<pre><code>Swift_TransportException in AbstractSmtpTransport.php line 383:
Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required.
Learn more at
530 5.5.1 https://support.google.com/mail/answer/14257 w10sm15831823wjk.18 - gsmtp
"
</code></pre>
| 0 |
Node JS auto restart all forever JS process when server goes down / crashes
|
<p>I am using forever js to keep my node server running 24/7 on AWS EC2.</p>
<p>I use this command</p>
<pre><code>forever start index.js
</code></pre>
<p>However, I notice that some time it randomly stops the process and my site goes down. I have to manually ssh into my server to run it again by doing:</p>
<pre><code>forever restartall
</code></pre>
<p>And then it goes backup. Is there any way by which I can define a timeout, lets say if the server/website does not respond for 200 in 5 sec, then restart all forever process automatically?</p>
<p>I am new to this, if any one can give me step by step example for my case, it would be awesome.</p>
| 0 |
Turn python script into a function
|
<p>Assume I wrote a script <code>morning.py</code> which does a simple print statement</p>
<pre><code># morning.py
print 'Good morning'
</code></pre>
<p>Some hours later I've realized that I have to use this script in another script named <code>evening.py</code>. I am aware of two options. First, to invoke <code>morning.py</code> as a subprocess</p>
<pre><code># evening.py
import subprocess
import shlex
process = subprocess.Popen(shlex.split('python morning.py'))
process.communicate()
</code></pre>
<p>This is the way I've initially chosen. The problem is that I want to pack my program (<code>morning</code> + <code>evening</code>) into a single executable. And to my understanding, from the exe file such call just won't work.</p>
<p>Another option is to turn module <code>morning</code> into a function. For instance, like that</p>
<pre><code># morning.py
def morning_func():
print 'Good morning'
</code></pre>
<p>Then I can simply call this function from the <code>evening</code> module</p>
<pre><code># evening
import morning
morning.morning_func()
</code></pre>
<p>Here the problem is that unlike <code>morning</code> my actual initial script is quite extended and messy. There is no single function that I can execute to simulate script running flow. Wrapping the whole script in a function just does not feel right.</p>
<p>What are possible solutions?</p>
| 0 |
Is it still possible to do server side verification of tokens in Firebase 3?
|
<p>Is it still possible to do server side verification of tokens in Firebase 3?</p>
<p>We generate custom tokens (JWT) on a server running Golang using our existing authentication system (using a Service Account).
The token is used on an iOS client using</p>
<pre><code>FIRAuth.auth()?.signInWithCustomToken(customToken)
</code></pre>
<p>Until there it all works fine. But when we pass the client token to the server retrieved from:</p>
<pre><code>FIRUser.getTokenWithCompletion({ token, error in ..})
</code></pre>
<p>we're not able to verify it. The JWT token is signed using RS256 and has an header.kid we can't recognize. The public key from the Service Account (which was used to sign the custom token) doesn't verify the client token.
Is the public key needed to validate the client token available?</p>
<p>I know it's possible to validate client tokens using the "verifyIdToken" call in Java or Javascript, but we hope to stil be able to do this in Golang using a standard JWT library.</p>
<p>This all worked fine in Firebase 2 (using HS256 and the Firebase secret).</p>
| 0 |
Dplyr - Filter if any variable is equal to a value
|
<p>I have a dataset <code>a</code> with 5 variables and want to filter it like this:</p>
<pre><code>a1 <- a %>% filter(var_1 != 1 , var_2 != 1 , var_3 != 1 , var_4 != 1 , variable_5 != 1)
</code></pre>
<p>I was wondering if anything like this (pseudo code) existed:</p>
<pre><code>a1 <- a %>% filter(anyvariable != 1)
</code></pre>
<p>In other words I would like to get rid of all the rows with value 1, no matter where it appears.
1 is just a random number. It could have been 9, 99, or whatever else!
Thanks!</p>
| 0 |
Change legend size in plotly chart
|
<p>Is there a way to change the legend size in plotly for R? I have not come across this option. I have looked at the docs on legends, <a href="https://plot.ly/r/legend/" rel="noreferrer">https://plot.ly/r/legend/</a>, but it does not mention this.</p>
| 0 |
Is there a switch to disable "cannot use temporary expression in write context" error?
|
<p>The error was added in PHP7 and I have problem with such code as:</p>
<pre><code>(some complex expression)->my_property = 1
</code></pre>
<p><em>Please note I am assigning to the field of the object, not to the object itself (assigning to temporary object does not make sense, I agree, but here it is <strong>not</strong> the case).</em></p>
<p>This gives me an error "cannot use temporary expression in write context". When I rewrite this as:</p>
<pre><code>$tmp = (some complex expression);
$tmp->my_property = 1;
</code></pre>
<p>Everything is fine. The problem is I have to have single expression (assignment is an expression), and since PHP does not support comma operator now I am toasted with two <strong>statements</strong>.</p>
<p>For me this is huge difference, because I cannot pass entire code as an expression further. Everything is valid inside that "complex expression" so I would love to simply disable that check in PHP.</p>
<p>Is it possible? How?</p>
<p><em>My code is written automatically (it is generated) and the outcome of the expression is a valid PHP object, the problem is PHP somehow does not notice it. Besides, the second form works.</em></p>
<p>Update: this is an <strong>example</strong> of complex expression I mentioned above:</p>
<pre><code>(($a = foo()) === 0 ? $a : bar())
</code></pre>
| 0 |
Angular Modal - closing/dismissing modal
|
<p>I am new to Angular and trying to implement a modal. Having problem closing/dismissing the modal - when I click the cancel button, nothing happens.
Here is the controller code:</p>
<pre><code>angular.module('navApp')
// Passing the $modal to controller as dependency
.controller('HomeCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.title = "Hello, Angm-Generator!";
$scope.open = function () {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalCtrl'
});
};
}])
.controller('ModalCtrl', function ($scope, $uibModalInstance) {
// Added some content to Modal using $scope
$scope.content = "ModalCtrl, Yeah!"
// Add cancel button
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
})
</code></pre>
<p>and here is the template view of the actual modal</p>
<pre><code><!-- Modal Script -->
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<button type="button" class="close" datadismiss="modal" aria-hidden="true">&times;</button>
<h3 class="modal-title">Hello from Modal!</h3>
</div>
<div class="modal-body">
Modal Content from: <b>{{ content }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-danger" ngclick="cancel()">Cancel</button>
</div>
</script>
</code></pre>
<p>Even clicking the cross on the top right of modal doesn't close the modal. Any ideas? Thanks:)</p>
| 0 |
How to detect click event in iframe using jquery
|
<p>This is my iframe:</p>
<pre><code>#htmlDiv {
position: absolute;
top: 0px;
left: 300px;
height: 650px;
width: 1130px;
}
#htmlFrame {
position: absolute;
top: 0px;
left: 0px;
margin: 10px 10px 10px 10px;
padding: 0px 0px 0px 0px;
height: 630px;
width: 1110px;
}
<div id="htmlDiv">
<iframe id="htmlFrame"></iframe>
</div>
$('#htmlFrame').click(function(){
alert('clicked');
});
</code></pre>
<p>But when I click inside the iframe, it doesn't show "clicked".<br>
How do I detect click inside iframe.</p>
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.