title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Show keyboard programmatically using React native | <p>How do I show Keyboard for TextInput programmatically using react native? Using a ScrollView, tapping between TextInput causes the keyboard to be dismissed. I want to show the Keyboard again using onFocus method of TextInput. Anyway to accomplish this?</p> | 0 |
Code exit status 255 | <p>I have written the below code for getting the only unique element in a given integer array.</p>
<pre><code>def lonelyinteger(a):
for x in a:
answer = a.count(x)
if(a.count(x) < 2)
answer=x
return answer
if __name__ == '__main__':
a = input()
b = map(int, raw_input().strip().split(" "))
print lonelyinteger(b)
</code></pre>
<p><strong>Error</strong></p>
<blockquote>
<p>File "solution.py", line 5
if(a.count(x) < 2)
^
SyntaxError: invalid syntax </p>
<p>Exit Status
255</p>
</blockquote>
<p>Please tell me where did I miss</p> | 0 |
Why don’t SVG images scale using the CSS “width” property? | <h1>HTML</h1>
<pre class="lang-html prettyprint-override"><code><div id="hero">
<div id="social">
<img src="facebook.svg" alt="Facebook">
<img src="linkedin.svg" alt="LinkedIn">
<img src="instagram.svg" alt="Instagram">
</div>
</div>
</code></pre>
<h1>CSS using SASS</h1>
<pre class="lang-css prettyprint-override"><code>#hero {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 300px;
#social {
width: 50%;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
img {
width: 2em;
}
}
}
</code></pre>
<p>I’m not able to resize SVGs using the CSS <code>width</code> property. Here is what I obtain with different approaches (note how icons collapse toward the middle of the <code>hero</code> <code>div</code>):</p>
<p><code>img { width: 2em; }</code></p>
<p><a href="https://i.stack.imgur.com/7fIsb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7fIsb.png" alt="enter image description here" /></a></p>
<p><code>img { width: 3em; }</code></p>
<p><a href="https://i.stack.imgur.com/7iw0h.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7iw0h.png" alt="enter image description here" /></a></p>
<p><code>img { width: 4em; }</code></p>
<p><a href="https://i.stack.imgur.com/Pbceu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Pbceu.png" alt="enter image description here" /></a></p>
<p>However, if I use the CSS <code>height</code> property:</p>
<p><code>img { height: 2em; }</code></p>
<p><a href="https://i.stack.imgur.com/n10yp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/n10yp.png" alt="enter image description here" /></a></p>
<p><code>img { height: 3em; }</code></p>
<p><a href="https://i.stack.imgur.com/B25nT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B25nT.png" alt="enter image description here" /></a></p>
<p><code>img { height: 4em; }</code></p>
<p><a href="https://i.stack.imgur.com/xcH8V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xcH8V.png" alt="enter image description here" /></a></p>
<p>I get the behaviour I need, but I’m not sure this is the right way. Why does this happen? Do you know better ways of resizeing SVG images (especially using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox" rel="noreferrer">Flexible Box Module</a>)?</p> | 0 |
How to get .mp4 videos from motion on a Raspberry Pi? | <p>I use <a href="http://www.lavrsen.dk/foswiki/bin/view/Motion/WebHome" rel="noreferrer">motion</a> on my laptop and it works perfectly in any format. But when I use it on my Raspberry Pi 3 (Raspbian Jessie) with the Raspberry Camera V2, the only formats that work are : <code>.avi</code> and <code>.swf</code>.</p>
<p>When I choose any other format, the output video is a "0 sec video" that is played and closed instantly.</p>
<p>I would like to have <code>.mp4</code> or <code>.ogg</code> output so I can read it easily with HTML5.</p>
<p>Here is the <a href="http://www.lavrsen.dk/foswiki/bin/view/Motion/ConfigOptionFfmpegVideoCodec" rel="noreferrer">motion codec documentation</a>.</p>
<p>Here is my config file :</p>
<pre><code>############################################################
# Daemon
############################################################
# Start in daemon (background) mode and release terminal (default: off)
daemon on
# File to store the process ID, also called pid file. (default: not defined)
process_id_file /var/run/motion/motion.pid
############################################################
# Basic Setup Mode
############################################################
# Start in Setup-Mode, daemon disabled. (default: off)
setup_mode off
# Use a file to save logs messages, if not defined stderr and syslog is used. (default: not defined)
#logfile /mnt/camshare/Cam1/motion.log
logfile /tmp/motion.log
# Level of log messages [1..9] (EMR, ALR, CRT, ERR, WRN, NTC, INF, DBG, ALL). (default: 6 / NTC)
log_level 2
# Filter to log messages by type (COR, STR, ENC, NET, DBL, EVT, TRK, VID, ALL). (default: ALL)
log_type all
###########################################################
# Capture device options
############################################################
# Videodevice to be used for capturing (default /dev/video0)
# for FreeBSD default is /dev/bktr0
#videodevice /dev/video0
# v4l2_palette allows to choose preferable palette to be use by motion
# to capture from those supported by your videodevice. (default: 17)
# E.g. if your videodevice supports both V4L2_PIX_FMT_SBGGR8 and
# V4L2_PIX_FMT_MJPEG then motion will by default use V4L2_PIX_FMT_MJPEG.
# Setting v4l2_palette to 2 forces motion to use V4L2_PIX_FMT_SBGGR8
# instead.
#
# Values :
# V4L2_PIX_FMT_SN9C10X : 0 'S910'
# V4L2_PIX_FMT_SBGGR16 : 1 'BYR2'
# V4L2_PIX_FMT_SBGGR8 : 2 'BA81'
# V4L2_PIX_FMT_SPCA561 : 3 'S561'
# V4L2_PIX_FMT_SGBRG8 : 4 'GBRG'
# V4L2_PIX_FMT_SGRBG8 : 5 'GRBG'
# V4L2_PIX_FMT_PAC207 : 6 'P207'
# V4L2_PIX_FMT_PJPG : 7 'PJPG'
# V4L2_PIX_FMT_MJPEG : 8 'MJPEG'
# V4L2_PIX_FMT_JPEG : 9 'JPEG'
# V4L2_PIX_FMT_RGB24 : 10 'RGB3'
# V4L2_PIX_FMT_SPCA501 : 11 'S501'
# V4L2_PIX_FMT_SPCA505 : 12 'S505'
# V4L2_PIX_FMT_SPCA508 : 13 'S508'
# V4L2_PIX_FMT_UYVY : 14 'UYVY'
# V4L2_PIX_FMT_YUYV : 15 'YUYV'
# V4L2_PIX_FMT_YUV422P : 16 '422P'
# V4L2_PIX_FMT_YUV420 : 17 'YU12'
#
v4l2_palette 7
# Tuner device to be used for capturing using tuner as source (default /dev/tuner0)
# This is ONLY used for FreeBSD. Leave it commented out for Linux
; tunerdevice /dev/tuner0
# The video input to be used (default: -1)
# Should normally be set to 0 or 1 for video/TV cards, and -1 for USB cameras
input -1
# The video norm to use (only for video capture and TV tuner cards)
# Values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour). Default: 0 (PAL)
norm 0
# The frequency to set the tuner to (kHz) (only for TV tuner cards) (default: 0)
frequency 0
# Rotate image this number of degrees. The rotation affects all saved images as
# well as movies. Valid values: 0 (default = no rotation), 90, 180 and 270.
rotate 0
# Image width (pixels). Valid range: Camera dependent, default: 352
#width 1024
width 640
# Image height (pixels). Valid range: Camera dependent, default: 288
#height 576
height 480
# Maximum number of frames to be captured per second.
# Valid range: 2-100. Default: 100 (almost no limit).
framerate 15
# Minimum time in seconds between capturing picture frames from the camera.
# Default: 0 = disabled - the capture rate is given by the camera framerate.
# This option is used when you want to capture images at a rate lower than 2 per second.
minimum_frame_time 0
# URL to use if you are using a network camera, size will be autodetected (incl http:// ftp:// mjpg:// or file:///)
# Must be a URL that returns single jpeg pictures or a raw mjpeg stream. Default: Not defined
;netcam_url http://127.0.0.1/cgi-bin/raspicam.sh
# Username and password for network camera (only if required). Default: not defined
# Syntax is user:password
; netcam_userpass value
# The setting for keep-alive of network socket, should improve performance on compatible net cameras.
# off: The historical implementation using HTTP/1.0, closing the socket after each http request.
# force: Use HTTP/1.0 requests with keep alive header to reuse the same connection.
# on: Use HTTP/1.1 requests that support keep alive as default.
# Default: off
netcam_keepalive off
# URL to use for a netcam proxy server, if required, e.g. "http://myproxy".
# If a port number other than 80 is needed, use "http://myproxy:1234".
# Default: not defined
; netcam_proxy value
# Set less strict jpeg checks for network cameras with a poor/buggy firmware.
# Default: off
netcam_tolerant_check off
# Let motion regulate the brightness of a video device (default: off).
# The auto_brightness feature uses the brightness option as its target value.
# If brightness is zero auto_brightness will adjust to average brightness value 128.
# Only recommended for cameras without auto brightness
auto_brightness off
# Set the initial brightness of a video device.
# If auto_brightness is enabled, this value defines the average brightness level
# which Motion will try and adjust to.
# Valid range 0-255, default 0 = disabled
brightness 0
# Set the contrast of a video device.
# Valid range 0-255, default 0 = disabled
contrast 0
# Set the saturation of a video device.
# Valid range 0-255, default 0 = disabled
saturation 0
# Set the hue of a video device (NTSC feature).
# Valid range 0-255, default 0 = disabled
hue 0
############################################################
# File "camera" support - read raw YUV data from a file
############################################################
#filecam_path /home/pi/test-cap/motion-mmal.capture
############################################################
# OpenMax/MMAL camera support for Raspberry Pi
############################################################
mmalcam_name vc.ril.camera
#mmalcam_control_params
#mmalcam_raw_capture_file /home/pi/motion-mmal.capture
# Switch this setting to "on" to use the still image mode of the Pi's camera
# instead of video. This gives a wider field of view, but requires
# a much slower frame-rate to achieve exposure stability
# (e.g. 0.25 fps or slower). You can use the minimum_frame_time
# parameter above to achieve this
mmalcam_use_still off
############################################################
# Round Robin (multiple inputs on same video device name)
############################################################
# Number of frames to capture in each roundrobin step (default: 1)
roundrobin_frames 1
# Number of frames to skip before each roundrobin step (default: 1)
roundrobin_skip 1
# Try to filter out noise generated by roundrobin (default: off)
switchfilter off
############################################################
# Motion Detection Settings:
############################################################
# Threshold for number of changed pixels in an image that
# triggers motion detection (default: 1500)
threshold 1500
# Automatically tune the threshold down if possible (default: off)
threshold_tune off
# Noise threshold for the motion detection (default: 32)
noise_level 32
# Automatically tune the noise threshold (default: on)
noise_tune on
# Despeckle motion image using (e)rode or (d)ilate or (l)abel (Default: not defined)
# Recommended value is EedDl. Any combination (and number of) of E, e, d, and D is valid.
# (l)abeling must only be used once and the 'l' must be the last letter.
# Comment out to disable
despeckle_filter EedDl
# Detect motion in predefined areas (1 - 9). Areas are numbered like that: 1 2 3
# A script (on_area_detected) is started immediately when motion is 4 5 6
# detected in one of the given areas, but only once during an event. 7 8 9
# One or more areas can be specified with this option. Take care: This option
# does NOT restrict detection to these areas! (Default: not defined)
; area_detect value
# PGM file to use as a sensitivity mask.
# Full path name to. (Default: not defined)
; mask_file value
# Dynamically create a mask file during operation (default: 0)
# Adjust speed of mask changes from 0 (off) to 10 (fast)
smart_mask_speed 0
# Ignore sudden massive light intensity changes given as a percentage of the picture
# area that changed intensity. Valid range: 0 - 100 , default: 0 = disabled
lightswitch 0
# Picture frames must contain motion at least the specified number of frames
# in a row before they are detected as true motion. At the default of 1, all
# motion is detected. Valid range: 1 to thousands, recommended 1-5
minimum_motion_frames 1
# Specifies the number of pre-captured (buffered) pictures from before motion
# was detected that will be output at motion detection.
# Recommended range: 0 to 5 (default: 0)
# Do not use large values! Large values will cause Motion to skip video frames and
# cause unsmooth movies. To smooth movies use larger values of post_capture instead.
pre_capture 2
# Number of frames to capture after motion is no longer detected (default: 0)
post_capture 2
# Event Gap is the seconds of no motion detection that triggers the end of an event.
# An event is defined as a series of motion images taken within a short timeframe.
# Recommended value is 60 seconds (Default). The value -1 is allowed and disables
# events causing all Motion to be written to one single movie file and no pre_capture.
# If set to 0, motion is running in gapless mode. Movies don't have gaps anymore. An
# event ends right after no more motion is detected and post_capture is over.
event_gap 60
# Maximum length in seconds of an mpeg movie
# When value is exceeded a new movie file is created. (Default: 0 = infinite)
# ATTENTION: when you're not using the motion build from the tutorial, it might fail with error 'Unknown config option "max_mpeg_time"'
# the use this line instead:
# max_movie_time 60
max_movie_time 60
# Always save images even if there was no motion (default: off)
emulate_motion off
############################################################
# Image File Output
############################################################
# Output 'normal' pictures when motion is detected (default: on)
# Valid values: on, off, first, best, center
# When set to 'first', only the first picture of an event is saved.
# Picture with most motion of an event is saved when set to 'best'.
# Picture with motion nearest center of picture is saved when set to 'center'.
# Can be used as preview shot for the corresponding movie.
output_pictures best
# Output pictures with only the pixels moving object (ghost images) (default: off)
output_debug_pictures off
# The quality (in percent) to be used by the jpeg compression (default: 75)
quality 75
# Type of output images
# Valid values: jpeg, ppm (default: jpeg)
picture_type jpeg
############################################################
# FFMPEG related options
# Film (movies) file output, and deinterlacing of the video input
# The options movie_filename and timelapse_filename are also used
# by the ffmpeg feature
############################################################
# Use ffmpeg to encode movies in realtime (default: off)
ffmpeg_output_movies on
# Use ffmpeg to make movies with only the pixels moving
# object (ghost images) (default: off)
ffmpeg_output_debug_movies off
# Use ffmpeg to encode a timelapse movie
# Default value 0 = off - else save frame every Nth second
ffmpeg_timelapse 0
# The file rollover mode of the timelapse video
# Valid values: hourly, daily (default), weekly-sunday, weekly-monday, monthly, manual
ffmpeg_timelapse_mode daily
# Bitrate to be used by the ffmpeg encoder (default: 400000)
# This option is ignored if ffmpeg_variable_bitrate is not 0 (disabled)
ffmpeg_bps 500000
# Enables and defines variable bitrate for the ffmpeg encoder.
# ffmpeg_bps is ignored if variable bitrate is enabled.
# Valid values: 0 (default) = fixed bitrate defined by ffmpeg_bps,
# or the range 2 - 31 where 2 means best quality and 31 is worst.
ffmpeg_variable_bitrate 5
# Codec to used by ffmpeg for the video compression.
# Timelapse mpegs are always made in mpeg1 format independent from this option.
# Supported formats are: mpeg1 (ffmpeg-0.4.8 only), mpeg4 (default), and msmpeg4.
# mpeg1 - gives you files with extension .mpg
# mpeg4 or msmpeg4 - gives you files with extension .avi
# msmpeg4 is recommended for use with Windows Media Player because
# it requires no installation of codec on the Windows client.
# swf - gives you a flash film with extension .swf
# flv - gives you a flash video with extension .flv
# ffv1 - FF video codec 1 for Lossless Encoding ( experimental )
# mov - QuickTime ( testing )
# ogg - Ogg/Theora ( testing )
#ffmpeg_video_codec msmpeg4
ffmpeg_video_codec mp4
# Use ffmpeg to deinterlace video. Necessary if you use an analog camera
# and see horizontal combing on moving objects in video or pictures.
# (default: off)
ffmpeg_deinterlace off
############################################################
# SDL Window
############################################################
# Number of motion thread to show in SDL Window (default: 0 = disabled)
#sdl_threadnr 0
############################################################
# External pipe to video encoder
# Replacement for FFMPEG builtin encoder for ffmpeg_output_movies only.
# The options movie_filename and timelapse_filename are also used
# by the ffmpeg feature
#############################################################
# Bool to enable or disable extpipe (default: off)
use_extpipe off
# External program (full path and opts) to pipe raw video to
# Generally, use '-' for STDIN...
;extpipe mencoder -demuxer rawvideo -rawvideo w=320:h=240:i420 -ovc x264 -x264encopts bframes=4:frameref=1:subq=1:scenecut=-1:nob_adapt:threads=1:keyint=1000:8x8dct:vbv_bufsize=4000:crf=24:partitions=i8x8,i4x4:vbv_maxrate=800:no-chroma-me -vf denoise3d=16:12:48:4,pp=lb -of avi -o %f.avi - -fps %fps
############################################################
# Snapshots (Traditional Periodic Webcam File Output)
############################################################
# Make automated snapshot every N seconds (default: 0 = disabled)
snapshot_interval 0
############################################################
# Text Display
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second, %T = HH:MM:SS,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level, \n = new line,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event - do not use with text_event!
# You can put quotation marks around the text to allow
# leading spaces
############################################################
# Locate and draw a box around the moving object.
# Valid values: on, off, preview (default: off)
# Set to 'preview' will only draw a box in preview_shot pictures.
locate_motion_mode off
# Set the look and style of the locate box if enabled.
# Valid values: box, redbox, cross, redcross (default: box)
# Set to 'box' will draw the traditional box.
# Set to 'redbox' will draw a red box.
# Set to 'cross' will draw a little cross to mark center.
# Set to 'redcross' will draw a little red cross to mark center.
locate_motion_style box
# Draws the timestamp using same options as C function strftime(3)
# Default: %Y-%m-%d\n%T = date in ISO format and time in 24 hour clock
# Text is placed in lower right corner
text_right %d.%m.%Y\n%T
# Draw a user defined text on the images using same options as C function strftime(3)
# Default: Not defined = no text
# Text is placed in lower left corner
; text_left CAMERA %t
text_left HofCam
# Draw the number of changed pixed on the images (default: off)
# Will normally be set to off except when you setup and adjust the motion settings
# Text is placed in upper right corner
text_changes off
# This option defines the value of the special event conversion specifier %C
# You can use any conversion specifier in this option except %C. Date and time
# values are from the timestamp of the first image in the current event.
# Default: %Y%m%d%H%M%S
# The idea is that %C can be used filenames and text_left/right for creating
# a unique identifier for each event.
text_event %Y%m%d%H%M%S
# Draw characters at twice normal size on images. (default: off)
text_double on
# Text to include in a JPEG EXIF comment
# May be any text, including conversion specifiers.
# The EXIF timestamp is included independent of this text.
;exif_text %i%J/%K%L
############################################################
# Target Directories and filenames For Images And Films
# For the options snapshot_, picture_, movie_ and timelapse_filename
# you can use conversion specifiers
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# Quotation marks round string are allowed.
############################################################
# Target base directory for pictures and films
# Recommended to use absolute path. (Default: current working directory)
target_dir /home/pi
# File path for snapshots (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-snapshot
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-snapshot
# File extension .jpg or .ppm is automatically added so do not include this.
# Note: A symbolic link called lastsnap.jpg created in the target_dir will always
# point to the latest snapshot, unless snapshot_filename is exactly 'lastsnap'
snapshot_filename %v-%Y%m%d%H%M%S-snapshot
# File path for motion triggered images (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-%q
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-%q
# File extension .jpg or .ppm is automatically added so do not include this
# Set to 'preview' together with best-preview feature enables special naming
# convention for preview shots. See motion guide for details
picture_filename %v-%Y%m%d%H%M%S-%q
# File path for motion triggered ffmpeg films (movies) relative to target_dir
# Default: %v-%Y%m%d%H%M%S
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H%M%S
# File extension .mpg or .avi is automatically added so do not include this
# This option was previously called ffmpeg_filename
movie_filename %v-%Y%m%d%H%M%S
# File path for timelapse movies relative to target_dir
# Default: %Y%m%d-timelapse
# Default value is near equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d-timelapse
# File extension .mpg is automatically added so do not include this
timelapse_filename %Y%m%d-timelapse
############################################################
# Global Network Options
############################################################
# Enable or disable IPV6 for http control and stream (default: off )
ipv6_enabled off
############################################################
# Live Stream Server
############################################################
# The mini-http server listens to this port for requests (default: 0 = disabled)
stream_port 8080
# Quality of the jpeg (in percent) images produced (default: 50)
stream_quality 50
# Output frames at 1 fps when no motion is detected and increase to the
# rate given by stream_maxrate when motion is detected (default: off)
stream_motion on
# Maximum framerate for stream streams (default: 1)
stream_maxrate 4
# Restrict stream connections to localhost only (default: on)
stream_localhost off
# Limits the number of images per connection (default: 0 = unlimited)
# Number can be defined by multiplying actual stream rate by desired number of seconds
# Actual stream rate is the smallest of the numbers framerate and stream_maxrate
stream_limit 0
# Set the authentication method (default: 0)
# 0 = disabled
# 1 = Basic authentication
# 2 = MD5 digest (the safer authentication)
stream_auth_method 0
# Authentication for the stream. Syntax username:password
# Default: not defined (Disabled)
; stream_authentication username:password
############################################################
# HTTP Based Control
############################################################
# TCP/IP port for the http server to listen on (default: 0 = disabled)
webcontrol_port 8081
# Restrict control connections to localhost only (default: on)
webcontrol_localhost off
# Output for http server, select off to choose raw text plain (default: on)
webcontrol_html_output on
# Authentication for the http based control. Syntax username:password
# Default: not defined (Disabled)
; webcontrol_authentication username:password
############################################################
# Tracking (Pan/Tilt)
#############################################################
# Type of tracker (0=none (default), 1=stepper, 2=iomojo, 3=pwc, 4=generic, 5=uvcvideo, 6=servo)
# The generic type enables the definition of motion center and motion size to
# be used with the conversion specifiers for options like on_motion_detected
track_type 0
# Enable auto tracking (default: off)
track_auto off
# Serial port of motor (default: none)
;track_port /dev/ttyS0
# Motor number for x-axis (default: 0)
;track_motorx 0
# Set motorx reverse (default: 0)
;track_motorx_reverse 0
# Motor number for y-axis (default: 0)
;track_motory 1
# Set motory reverse (default: 0)
;track_motory_reverse 0
# Maximum value on x-axis (default: 0)
;track_maxx 200
# Minimum value on x-axis (default: 0)
;track_minx 50
# Maximum value on y-axis (default: 0)
;track_maxy 200
# Minimum value on y-axis (default: 0)
;track_miny 50
# Center value on x-axis (default: 0)
;track_homex 128
# Center value on y-axis (default: 0)
;track_homey 128
# ID of an iomojo camera if used (default: 0)
track_iomojo_id 0
# Angle in degrees the camera moves per step on the X-axis
# with auto-track (default: 10)
# Currently only used with pwc type cameras
track_step_angle_x 10
[...]
</code></pre> | 0 |
Deepcopy in React | <p>In reducers,we always use <code>Object.assign({},state,newState)</code> to save a state. But <code>assign()</code> doesn't support deepcopy,because this method only copy a reference of multi-level object. This is my code in program.</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>const menuListState={
menuList: {},
menuListLoading:false
}
function getMenuList(state=menuListState,action=defaultAction){
switch(action.type){
//menuList begin
case actions.GET_MENULIST_SUCCESS:
return Object.assign({},state,{
menuList:action.data,
menuListLoading:false
});
default:
return state;
}
}</code></pre>
</div>
</div>
</p>
<p>The property <code>menuList</code> is a multi-level Object. And when <code>action.data</code> changes, will <code>state.menuList</code> be changed immediately before the method <code>assign()</code> work?</p> | 0 |
Python -- Opening multiple tabs using Selenium | <p>I am using Python. I am trying to open two tabs on chrome, each to a different website. This is my code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser=webdriver.Chrome()
browser.get('http:/reddit.com')
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
time.sleep(3)
browser.get('http://bing.com')
</code></pre>
<p>When I run it, the first tab is opened to reddit.com, and then another tab opens to my default webpage, and then bing.com is opened in the original tab. I want the first tab to go to Reddit and the second tab to go to bing, but <code>browser.get('website')</code> only acts on the first tab.</p> | 0 |
react-router " Cannot read property 'push' of undefined" | <p>i am quite new to react and react-router.</p>
<p>Problem with react is here that, on some pages of my application react-router is working and some giving error like this: "Cannot read property 'push' of undefined".</p>
<p>i am using react 0.14.1</p>
<p>My routing code looks like this:</p>
<pre><code>render(
<Router history={hashHistory}>
<Route path="/" component={Loginpanel}/>
<Route path="Index" component={Index}/>
<Route path="Form" component={Form} />
<Route path="Checkindex" component={Index}/>
<Route path="Signup" component={Signup}/>
<Route path="Admin" component={Admin}/>
<Route path="AdminEditDetails" component={AdminEditDetails}/>
<Route path="AdminDetails" component={AdminDetails}/>
</Router>,
document.getElementById('js-main'));
</code></pre>
<p>My component is like this now:</p>
<pre><code>class App extends React.Component {
constructor(props) {
super(props);
this.state= {
comments: AppStore.getAll();
};
}
componentWillMount() {
var length = this.state.comments.length;
var firstnumber = length - 4;
if(length == 0){
console.log("here comes");
this.props.router.push('/');
}
else{
console.log('work normally');
}
}
}
</code></pre>
<p>Can anyone help me with this? Thanks.</p> | 0 |
restframework 'tuple' object has no attribute '_meta' | <p>Django throws the next exception:</p>
<p>restframework 'tuple' object has no attribute '_meta'</p>
<p>Model</p>
<pre><code>class BDetail(models.Model):
lat = models.FloatField(blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
class Meta:
# managed = False
db_table = 'b_detail'
</code></pre>
<p>View</p>
<pre><code>from .models import BDetail
from .serializers import BDetailSerializer
from rest_framework import viewsets
class BDetailList(viewsets.ModelViewSet):
queryset = BDetail.objects.all()
serializer_class = BDetailSerializer
</code></pre>
<p>urls</p>
<pre><code>from django.conf.urls import url, include
from bdetail import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'bdetail', views.BDetailList)
urlpatterns = [
url(r'^', include(router.urls), name='bdetail')
]
</code></pre>
<p>serializers</p>
<pre><code>from .models import BDetail
from rest_framework import serializers
class BDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = BDetail,
fields = ('lat', 'lng')
</code></pre>
<p>Environment:</p>
<p>Request Method: GET
Request URL: <a href="http://apiix.verinmuebles.dev/v1/bdetail/" rel="noreferrer">http://apiix.verinmuebles.dev/v1/bdetail/</a></p>
<p>Traceback:</p>
<blockquote>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/exception.py"
in inner
39. response = get_response(request)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/views/decorators/csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/viewsets.py"
in view
87. return self.dispatch(request, *args, **kwargs)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py"
in dispatch
474. response = self.handle_exception(exc)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py"
in handle_exception
434. self.raise_uncaught_exception(exc)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py"
in dispatch
471. response = handler(request, *args, **kwargs)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/mixins.py"
in list
45. return self.get_paginated_response(serializer.data)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in data
701. ret = super(ListSerializer, self).data</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in data
240. self._data = self.to_representation(self.instance)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in to_representation
619. self.child.to_representation(item) for item in iterable</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in to_representation
460. fields = self._readable_fields</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/utils/functional.py"
in <strong>get</strong>
35. res = instance.<strong>dict</strong>[self.name] = self.func(instance)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in _readable_fields
354. field for field in self.fields.values()</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in fields
340. for key, value in self.get_fields().items():</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py"
in get_fields
946. info = model_meta.get_field_info(model)</p>
<p>File
"/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/utils/model_meta.py"
in get_field_info
36. opts = model._meta.concrete_model._meta</p>
<p>Exception Type: AttributeError at /v1/bdetail/ Exception Value:
'tuple' object has no attribute '_meta'</p>
</blockquote> | 0 |
React-native android WebView handle clicked Url before loading | <p>I'm showing a Website trough a WebView in react-native. On this Website there is a link to a PassWallet (.pkpass) file (not the only use case). When I click on any link on this Website I want to check whether it is an other Website or a .pkpass file or whatever. While this check is running I don't want to load anything, just wait until my function is finished and I'm knowing if I should open a Website or open another app or whatever. I want to make this on the JavaScript side because my whole routing functions are there and in my opinion react-native was built for this cases :-)</p>
<p>On iOS there is this beautiful function <code>onShouldStartLoadWithRequest</code> which exactly does what I need. </p>
<pre><code>_onShouldStartLoadWithRequest(e) {
if(checkUrl(e.url)) {
let Router = this.props.navigator.props.router;
let route = Router.getRouteFromUrl(e.url);
this.props.navigator.push(route);
return false;
}
return true;
}
</code></pre>
<p>I'm getting the event (e) and can check what url it's trying to load. I can even check with e.navigationType if it was a click or whatever. </p>
<p>Now on Android this function does not exists. On the native side there is the function <code>shouldOverrideUrlLoading</code> but this function is not implemented in react-native.
I found the following GitHub issue / PR <a href="https://github.com/facebook/react-native/pull/6478" rel="nofollow noreferrer">https://github.com/facebook/react-native/pull/6478</a>
I guess now, because this issue is closed and there are explanations for therefore, this function don't get implemented. </p>
<p>So I started to find a way by myself. I created a Native UI Component which displays a WebView and then implement this method.</p>
<p>CustomWebViewManager.java:</p>
<pre><code>package ch.mypackage;
import android.support.annotation.Nullable;
import android.webkit.WebView;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
public class CustomWebViewManager extends SimpleViewManager<CplusWebView> {
@Override
public String getName() {
return "CplusWebView";
}
@Override
protected CustomWebView createViewInstance(ThemedReactContext reactContext) {
return new CustomWebView(reactContext);
}
@ReactProp(name = "url")
public void setUrl(CustomWebView view, @Nullable String url) {
view.loadUrl(url);
}
@ReactProp(name = "javascriptEnabled")
public void setJavascriptEnabled(CustomWebView view, boolean enabled) {
view.getSettings().setJavaScriptEnabled(enabled);
}
}
</code></pre>
<p>CustomWebView.java</p>
<pre><code>package ch.couponplus;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.RCTEventEmitter;
public class CustomWebView extends WebView {
EventDispatcher eventDispatcher;
EventWebClient eventWebClient;
public CustomWebView(ThemedReactContext reactContext) {
super(reactContext);
eventWebClient = new EventWebClient();
setWebViewClient(eventWebClient);
}
protected class EventWebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"topChange",
event);
return true;
}
}
}
</code></pre>
<p>It works as expected. I can now trigger the <code>shouldOverrideUrlLoading</code> function in JS and make logs or whatever. </p>
<p>But my question is how can I now set <code>true</code> or <code>false</code> in Javascript to control my <code>shouldOverrideUrlLoading</code> function? And is there a possibility to make my own functions available? Until now I only managed to trigger the <code>onChange</code> event? </p>
<p>I just want to make the same as I made in iOS. Maybe someone comes up and tells me that this isn't possible for whatever reason but how should I or how do you handle cases like this? I know there are Url schemas but so much I know they don't work in this case. </p> | 0 |
Error in y - ymean : non-numeric argument to binary operator randomForest R | <p>I have a matrix which is about 37k x 1024 consisting of 1s and 0s as categorical variables to indicate the existence or absence of a feature vector. I ran this matrix through the randomForest package in R as follows : </p>
<pre><code>rfr <- randomForest(X_train,Y_train)
</code></pre>
<p>Where X_train is the matrix containing the categorical variables and Y__train is a vector consisting of labels for every row in the matrix. When i run this, i get the following error : </p>
<pre><code>Error in y - ymean : non-numeric argument to binary operator
In addition: Warning message:
In mean.default(y) : argument is not numeric or logical: returning NA
</code></pre>
<p>I checked for any null values or missing data but didnt find any. </p>
<p>I even made the whole thing into a data.frame and tried the following</p>
<pre><code>rfr <- randomForest(labels ~ ., data = featureDF)
</code></pre>
<p>Still had the same errors. </p>
<p>I would appreciate any help with this, thanks!</p> | 0 |
TypeScript + Express : req.params | <p>I have the following express route :</p>
<pre><code>app.get('/:id', function (req, res) {
var idNum: number = Number(req.params.id);
var idCast: number = +req.params.id;
var id: number = req.params.id;
console.log('typeof idNum ', typeof idNum , ' ', 'idNum== 0 : ', idNum== 0 , ' ', 'idNum=== 0 : ', idNum=== 0);
console.log('typeof idCast', typeof idCast, ' ', 'idCast == 0 :', idCast == 0, ' ', 'idCast === 0 :', idCast === 0);
console.log('typeof id ', typeof id , ' ', 'id == 0 : ', id == 0 , ' ', 'id === 0 :' , id === 0);
res.json({});
});
</code></pre>
<p>this returns : </p>
<pre><code>typeof idNum number idNum== 0 : true idNum=== 0 : true
typeof idCast number idCast == 0 : true idCast === 0 : true
typeof id string id == 0 : true id === 0 : false
</code></pre>
<p>I understand that typescript provide only compile-time type-checking, and I guess it means it's not aware that req.params provide arguments as strings.</p>
<p>Is there any way I can automatically cast my params to Number ? or at least raise an error of I didn't done it manually ? Else, it seems that tympescript, unless used in a full-typescript environnement is useless.</p>
<p>Endly, is there any "big" open source project using TypeScript with ExpressJS that I could read the source from ?</p> | 0 |
Best practices for draining or clearing a Google Cloud pubsub topic | <p>For pubsub topics with number of messages in the range of ~100k, what is the best practice for draining/dropping/clearing/deleting all messages using gcloud-java SDK? </p>
<p>Possible solutions:</p>
<ul>
<li><p>Deleting and recreating the subscribers and then the publishers</p></li>
<li><p>High concurrency pull+ack (easy to hit the quota this way) </p></li>
<li>Something else</li>
</ul>
<p>My hope is that this process can be fast (not more than ~60 seconds, say), robust, and uses supported SDK methods with minimal other code.</p> | 0 |
How to convert json Object to Document in mongodb using java | <p>I'm using the below sample json :</p>
<pre><code>JSONObject json=new JSONObject();
json.put("time_range", "22-23");
json.put("flow_id", "786");
</code></pre>
<p>And trying to convert to Document as follows :</p>
<pre><code>Document doc = (Document) JSON.parse(jsonlist.toString()); // conversion from json to Document
col.insertOne(doc); // inserting into Mongo collection
</code></pre>
<p>I'm facing the below error:</p>
<pre><code> java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to org.bson.Document
</code></pre>
<p>Can anyone please help me out regarding this issue ...</p> | 0 |
Golang Mongo Insert with self generated _Id using bson.NewObjectID() resulting in unexpected schema | <p>Hi i am using mongo and golang according to my use case i want to generate a _id before insertion, for that i am using</p>
<pre><code> bson.NewobjectId()
</code></pre>
<p>my struct is somewhat like this </p>
<pre><code>type Device struct {
Id bson.ObjectId `bson:"_id" json:"_id,omitempty"`
UserId string `bson:"userId" json:"userId"`
CategorySlug string `bson:"categorySlug" json:"categorySlug"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
ModifiedAt time.Time `bson:"modifiedAt" json:"modifiedAt"`
BrandId int `bson:"brandId" json:"brandId"`
Category string `bson:"category" json:"category"`
}
</code></pre>
<p>when i am using this json request </p>
<pre><code>{
"userId" : "gKn42jJD8uy8ksQpi",
"categorySlug" : "television",
"createdAt" : "2016-08-25T18:47:29.558Z",
"modifiedAt" : "2016-08-25T18:47:29.558Z",
"brandId" : 90,
"category" : "LED TV",
"dateOfPurchase" : "2016-08-25T18:47:29.558Z"
}
</code></pre>
<p>and decodes this into device type and after that initialize my id using
decode.ID = bson.NewObjectId()</p>
<p>but when i looked into my database the inserted value its strangely in this form</p>
<pre><code>{
"_id" : ObjectId("57bf425a34ce5ee85891b914"),
"0" : {
"_id" : ObjectId("57bf425ae03ec2179a000001"),
"userId" : "gKn42jJD8uy8ksQpi",
"categorySlug" : "television",
"createdAt" : ISODate("2016-08-25T18:47:29.558Z"),
"modifiedAt" : ISODate("2016-08-25T18:47:29.558Z"),
"brandId" : 90,
"category" : "LED TV",
"dateofpurchase" : ISODate("2016-08-25T18:47:29.558Z")
}
}
</code></pre>
<p>I dont know the reason why is this happening so i want my data in a proper mongo document . Please help me let know why is this thing happening and new _id is getting generated</p> | 0 |
Extract only quarter from a date in r | <p>I would like to extract ONLY the quarter from a date, e.g., to get an integer 1 from the date "2003-02-08". I have been trying something along this line</p>
<pre><code>library(mondate)
as.yearqtr(dat$DATE)
</code></pre>
<blockquote>
<p>"2003 Q1"</p>
</blockquote>
<pre><code>as.character(as.yearqtr(dat$DATE))[1]
</code></pre>
<blockquote>
<p>"2003 Q1"</p>
</blockquote>
<p>which hasn't been giving my desired result. Of course I can write conditions as follows</p>
<pre><code>library(data.table)
data$DATE = as.Date(data$DATE, format='%d%b%Y')
data$month=month(data$DATE)
setDT(data)[month==1, quarter:=1]
...
</code></pre>
<p>This will work, but is not elegant at all. Is there a more beautiful way of doing this?</p>
<p>Thank you lmo and user2100721! I really wish I could accept all of the answers! </p> | 0 |
MySQL FullText Search with Sequelize | <p>I want to implement MySQL full text search with sequelize. The version "sequelize": "^3.23.6". I tried to research about this but could not find =the documentation that guides how to implement this.
Here is the link that says FullText is supported by sequelize:
<a href="https://github.com/sequelize/sequelize/issues/2979" rel="noreferrer">https://github.com/sequelize/sequelize/issues/2979</a></p>
<p>But there is not exact documentation on how to do it and how to do a full text search query with sequelize.</p>
<p>Any links advice would be helpful </p>
<p>Thanks !</p> | 0 |
How to change marker icon in vue-google-maps | <p>I'm newbie in vuejs. I'm using <a href="https://github.com/GuillaumeLeclerc/vue-google-maps" rel="nofollow">vue-google-maps</a> to show markers and I wanna know how can I change the marker icon. I tried to add icon to marker tag but it doesn't work. Below my code :</p>
<p><strong>In my template, I have :</strong></p>
<pre><code><marker :position.sync="m.position" :icon.sync="m.icon" v-for="m in markers"></marker>
</code></pre>
<p><strong>and here is my script :</strong></p>
<pre><code>export default {
data: function data() {
return {
center: { lat: 33.533818415851705, lng: -3.746186887500016 },
zoom: 7,
markers: [{position: { lat: 34.263, lng: -6.582 }, icon:"../assets/marker-icon.png"}]
};}};
</code></pre>
<p>Can someone guide me please?</p> | 0 |
Install Tomcat on Mac OS X | <p>How do you install <a href="http://tomcat.apache.org/" rel="noreferrer">Tomcat</a> on Mac OS X?</p>
<p><a href="https://wolfpaulus.com/journal/mac/tomcat8/" rel="noreferrer">This guide</a> looks quite complicated.</p> | 0 |
ERROR in Error: Child compilation failed: Cannot find module 'handlebars' | <p>I've recently erased all <code>node_modules</code> and did a fresh <code>npm install</code>. And keep getting this error: </p>
<pre><code>ERROR in Error: Child compilation failed:
Cannot find module 'handlebars'
- compiler.js:76
[wallet-admin]/[html-webpack-plugin]/lib/compiler.js:76:16
- Compiler.js:214 Compiler.<anonymous>
[wallet-admin]/[webpack]/lib/Compiler.js:214:10
- Compiler.js:403
[wallet-admin]/[webpack]/lib/Compiler.js:403:12
- Tapable.js:67 Compiler.next
[wallet-admin]/[tapable]/lib/Tapable.js:67:11
- CachePlugin.js:40 Compiler.<anonymous>
[wallet-admin]/[webpack]/lib/CachePlugin.js:40:4
- Tapable.js:71 Compiler.applyPluginsAsync
[wallet-admin]/[tapable]/lib/Tapable.js:71:13
- Compiler.js:400 Compiler.<anonymous>
[wallet-admin]/[webpack]/lib/Compiler.js:400:9
Child html-webpack-plugin for "index.html":
ERROR in Cannot find module 'handlebars'
</code></pre>
<p>Not sure what is going on...I've tried changing all versions of:
<code>html-webpack-plugin</code>, <code>webpack</code>, <code>handlebars-loader</code> thinking it is a versioning issue. It doesn't seem to be. Any ideas?</p> | 0 |
Creating dynamic sitemap with php | <p>First let me tell you I am learning php. I want to create an automatically dynamic sitemap for my site. The script (suppose sitemap.php) will crawl all the links of my site and will create an array of 1000 urls. Once 1000 urls limit reaches, it will make an another page id with 1000 urls array. So that the script output will be like this :<br/></p>
<pre><code><sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.84"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/siteindex.xsd">
<sitemap>
<loc>http://exmaple.com/sitemap.php?page=1</loc>
</sitemap>
<sitemap>
<loc>http://example.com/sitemap.php?page=2</loc>
</sitemap>
</sitemapindex>
</code></pre>
<p>Page 1 will have 1000 urls in xml format and page 2 will have also and this will go on as the site is updated.I have tried so many codes from github and other seach pages from google. But have not found exactly what I need. Can you help please.</p> | 0 |
How to remove an offline emulator from avd devices? | <p>I've created a couple of AVD-s in Android Studio. They were launching on emulator port 5554. Then I've created another AVD via <code>android avd</code> application, and they are starting on port 5556. </p>
<p>Now with a single emulator running, I get the following output from <code>adb devices -l</code>:</p>
<pre><code>List of devices attached
emulator-5556 device
emulator-5554 offline
</code></pre>
<p>I'm using the tooling which cannot supply the <code>-s</code> (specific device) option to <code>adb</code>, so when trying to install an app, I get an error:</p>
<pre><code>error: more than one device/emulator
</code></pre>
<p>And I'd like that there be a single connected emulator: the only one that I'm running.</p>
<p>I thought that removing the old Android Studio-created devices would do the trick of removing the emulator-5554, but nope. Even new devices created in Studio will open on 5556. So I've ended up with a forever-offline zombie <code>emulator-5554</code> that screws up my build tooling.</p>
<p>How can I force the new emulators to be run on port 5554 and/or remove the offline <code>emulator-5554</code>?</p>
<p>(Running Ubuntu 16.04 if it matters.)</p> | 0 |
Kendo excel export - how do I export columns with a custom template? | <p>I have a kendo grid that I define declaritively.
I enable the excel export toolbar via <code>data-toolbar='["excel"]'</code></p>
<p>The problem is that this only exports the fields that do not have a template defined. (the first 3 in the grid below: Checkpoint, Location, Patrolled By), the other columns show up in the excel document, but the cells of those columns are all empty.</p>
<p>How can I get the values to show up in the excel export? I'm guessing it will require pre-processing of some sort before the excel gets exported, as the excel export function doesn't interpret my custom field html templates.</p>
<pre><code><div id="Checkpoints">
<div
...
data-toolbar='["excel"]'
data-excel='{ "fileName": "CheckpointExceptionExport.xlsx", "allPages": "true" }'
...
data-columns='[
{
"field": "checkpoint_name",
"title": "Checkpoint",
"filterable": { "cell": { "operator": "contains"}}},
{
"field": "location_name",
"title": "Location",
"filterable": { "cell": { "operator": "contains"}}
},
{
"field": "patrolled_by",
"title": "Patrolled By",
"filterable": { "cell": { "operator": "contains"}}
},
{
"field": "geotag",
"title": "GeoTag",
"template": kendo.template($("#geotagTemplate").html())
},
{
"field": "geofence",
"title": "GeoFence",
"template": kendo.template($("#geofenceTemplate").html())
},
{
"field": "completed",
"title": "Completed",
"template": kendo.template($("#completedTemplate").html())
},
{
"field": "gps",
"title": "GPS",
"template": kendo.template($("#gpsTemplate").html())
}
]'>
</div>
</div>
</code></pre>
<p>I've came across this snippet for handling the excel export event however I don't see a way to use this event handler in the way that I've defined the grid.</p>
<pre><code> <script>
$("#grid").kendoGrid({
excelExport: function(e) {
...
},
});
</script>
</code></pre> | 0 |
Jackson deserialize extra fields as Map | <p>I'm looking to deserialize any unknown fields in a JSON object as entries in a <code>Map</code> which is a member of a POJO.</p>
<p>For example, here is the JSON:</p>
<pre><code>{
"knownField" : 5,
"unknownField1" : "926f7c2f-1ae2-426b-9f36-4ba042334b68",
"unknownField2" : "ed51e59d-a551-4cdc-be69-7d337162b691"
}
</code></pre>
<p>Here is the POJO:</p>
<pre><code>class MyObject {
int knownField;
Map<String, UUID> unknownFields;
// getters/setters whatever
}
</code></pre>
<p>Is there a way to configure this with Jackson? If not, is there an effective way to write a <code>StdDeserializer</code> to do it (assume the values in <code>unknownFields</code> can be a more complex but well known consistent type)?</p> | 0 |
How do you test the content of a div or other element in enzyme/mocha/chai? | <p>I'm trying to verify that the content of a div matches what I'm expecting. What I have is:</p>
<pre><code>expect(wrapper.find('div.title').text().to.equal('A New Day');
</code></pre>
<p>However, this isn't working for me. Is this possible in enzyme/chai/mocha? </p>
<p>Thanks</p> | 0 |
How to write unit test case for BadRequest? | <p>I want to write Unit test cases for following code</p>
<p>HomeController.cs</p>
<pre><code>[HttpPost]
[ActionName("CreateDemo")]
public async Task<IHttpActionResult> CreateDemo([FromBody] MyRequest request)
{
if (request == null)
{
return BadRequest("request can not be null");
}
if (request.MyID == Guid.Empty)
{
return BadRequest("MyID must be provided");
}
}
</code></pre>
<p>I tried like following which is not correct way i guess so</p>
<pre><code> [TestMethod]
public async Task NullCheck()
{
try
{
var controller = new HomeController();
var resposne = await controller.CreateDemo(null);
Assert.AreEqual(); // not sure what to put here
}
catch (HttpResponseException ex) //catch is not hit
{
Assert.IsTrue(
ex.Message.Contains("request can not be null"));
}
}
</code></pre> | 0 |
How to set the default language of date in R | <p>I used a R package written by other people. In the package, it is supposed to create a file name as "Mar.12". However the file name is "三月.12” in my system since I am running it on an OS with Chinese language (windows 10). I have changed the display language to English in the Rconsole file but it does not help. I am wondering is there any method to change the default date to English in R without revising the original package? </p>
<p>Thanks in advance for help!</p> | 0 |
matplotlib not displaying image on Jupyter Notebook | <p>I am using ubuntu 14.04 and coding in jupyter notebook using anaconda2.7 and everything else is up to date . Today I was coding, every thing worked fine. I closed the notebook and when I reopened it, every thing worked fine except that the image was not being displayed.</p>
<pre><code>%matplotlib inline
import numpy as np
import skimage
from skimage import data
from matplotlib import pyplot as plt
%pylab inline
img = data.camera()
plt.imshow(img,cmap='gray')
</code></pre>
<p>this is the code i am using, a really simple one but doesn't display the image</p>
<pre><code><matplotlib.image.AxesImage at 0xaf7017ac>
</code></pre>
<p>this is displayed in the output area
please help</p> | 0 |
How to create a null pointer in a struct? | <p>How do I create null pointer properties in struct like in C++? I do not quite understand how to make a pointer to an empty space in the memory.</p>
<p><strong>C++</strong></p>
<pre class="lang-cpp prettyprint-override"><code>struct test{
string data;
assocc *el;
}
srtuct assocc {
T *data;
}
</code></pre>
<p><strong>Rust</strong></p>
<pre><code>struct test {
data: String,
ponts: *const Option<assocc<T>>,
}
struct assocc<T> {
data: T,
}
impl test {
fn new(data: String) -> test {
test {
data: data,
ponts: None,/*This don't work*/
}
}
}
impl<T> assocc<T> {
fn new(data: T) -> assocc {
assocc {
data: data,
}
}
}
</code></pre> | 0 |
Why are my Gradle builds dying with exit-code 137? | <p>I've been trying to compile and test a large project to use Gradle. The test run fine until they die unexpectedly. I dug around and resources said that this is due to a memory issue. If I reduce the number of tests in the suite, it runs fine.</p>
<p>I increased the memory by 4x increased the debugging level but I still don't follow what causes this. Here's the horribly cryptic stacktrace. The last line (scroll right) shows the memory settings that I've defined. </p>
<pre><code>...
...
...
1125 tests completed, 30 failed, 9 skipped
:test FAILED
:test (Thread[Daemon worker,5,main]) completed. Took 8 mins 39.684 secs.
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> Process 'Gradle Test Executor 1' finished with non-zero exit value 137
* Try:
Run with --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':test'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:154)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:52)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:151)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:99)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:93)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:62)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:93)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:82)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:94)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:43)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:78)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:48)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:52)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:40)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
BUILD FAILED at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.process.internal.ExecException: Process 'Gradle Test Executor 1' finished with non-zero exit value 137
Total time: 9 mins 38.624 secs
at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:367)
at org.gradle.process.internal.DefaultWorkerProcess.waitForStop(DefaultWorkerProcess.java:161)
at org.gradle.api.internal.tasks.testing.worker.ForkingTestClassProcessor.stop(ForkingTestClassProcessor.java:86)
at org.gradle.api.internal.tasks.testing.processors.RestartEveryNTestClassProcessor.endBatch(RestartEveryNTestClassProcessor.java:60)
at org.gradle.api.internal.tasks.testing.processors.RestartEveryNTestClassProcessor.stop(RestartEveryNTestClassProcessor.java:54)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.FailureHandlingDispatch.dispatch(FailureHandlingDispatch.java:29)
at org.gradle.messaging.dispatch.AsyncDispatch.dispatchMessages(AsyncDispatch.java:132)
at org.gradle.messaging.dispatch.AsyncDispatch.access$000(AsyncDispatch.java:33)
at org.gradle.messaging.dispatch.AsyncDispatch$1.run(AsyncDispatch.java:72)
... 2 more
Stopped 0 compiler daemon(s).
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':test'.] from daemon DaemonInfo{pid=48, address=[65adcc0f-8881-4511-b7a0-1b88c7016510 port:34390, addresses:[/0:0:0:0:0:0:0:1%lo, /127.0.0.1]], idle=false, context=DefaultDaemonContext[uid=14546872-57d6-4da6-8358-dc41cb7bb01d,javaHome=/usr/lib/jvm/java-8-oracle,daemonRegistryDir=/srv/myapplication/.gradle/daemon,pid=48,idleTimeout=120000,daemonOpts=-XX:MaxMetaspaceSize=320m,-XX:+DisableExplicitGC,-XX:+UseConcMarkSweepGC,-XX:NewSize=124m,-XX:SurvivorRatio=16,-Xms257m,-Xmx2049m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]} (build should be done).
</code></pre> | 0 |
Evaluating Logistic regression with cross validation | <p>I would like to use cross validation to test/train my dataset and evaluate the performance of the logistic regression model on the entire dataset and not only on the test set (e.g. 25%). </p>
<p>These concepts are totally new to me and am not very sure if am doing it right. I would be grateful if anyone could advise me on the right steps to take where I have gone wrong. Part of my code is shown below.</p>
<p>Also, how can I plot ROCs for "y2" and "y3" on the same graph with the current one?</p>
<p>Thank you</p>
<pre><code>import pandas as pd
Data=pd.read_csv ('C:\\Dataset.csv',index_col='SNo')
feature_cols=['A','B','C','D','E']
X=Data[feature_cols]
Y=Data['Status']
Y1=Data['Status1'] # predictions from elsewhere
Y2=Data['Status2'] # predictions from elsewhere
from sklearn.linear_model import LogisticRegression
logreg=LogisticRegression()
logreg.fit(X_train,y_train)
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
from sklearn import metrics, cross_validation
predicted = cross_validation.cross_val_predict(logreg, X, y, cv=10)
metrics.accuracy_score(y, predicted)
from sklearn.cross_validation import cross_val_score
accuracy = cross_val_score(logreg, X, y, cv=10,scoring='accuracy')
print (accuracy)
print (cross_val_score(logreg, X, y, cv=10,scoring='accuracy').mean())
from nltk import ConfusionMatrix
print (ConfusionMatrix(list(y), list(predicted)))
#print (ConfusionMatrix(list(y), list(yexpert)))
# sensitivity:
print (metrics.recall_score(y, predicted) )
import matplotlib.pyplot as plt
probs = logreg.predict_proba(X)[:, 1]
plt.hist(probs)
plt.show()
# use 0.5 cutoff for predicting 'default'
import numpy as np
preds = np.where(probs > 0.5, 1, 0)
print (ConfusionMatrix(list(y), list(preds)))
# check accuracy, sensitivity, specificity
print (metrics.accuracy_score(y, predicted))
#ROC CURVES and AUC
# plot ROC curve
fpr, tpr, thresholds = metrics.roc_curve(y, probs)
plt.plot(fpr, tpr)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate)')
plt.show()
# calculate AUC
print (metrics.roc_auc_score(y, probs))
# use AUC as evaluation metric for cross-validation
from sklearn.cross_validation import cross_val_score
logreg = LogisticRegression()
cross_val_score(logreg, X, y, cv=10, scoring='roc_auc').mean()
</code></pre> | 0 |
Angular2 How to get APP_BASE_HREF programmatically? | <p>How to get APP_BASE_HREF programmatically?</p>
<p>I have this in my app.module.ts (where APP_BASE='/'):</p>
<pre><code>{
provide: APP_BASE_HREF,
useValue: '<%= APP_BASE %>'
},
</code></pre>
<p>I'm trying:</p>
<pre><code>import { APP_BASE_HREF } from '@angular/common';
...
console.debug(APP_BASE_HREF.toString());
</code></pre>
<p>and in console I get:</p>
<pre><code>Token appBaseHref
</code></pre>
<p>and I need to get:</p>
<pre><code>http://localhost:5555/
</code></pre> | 0 |
How to use variables from different class in NLog.Config? | <p>I have a Class with a <code>static</code> field which holds a path.</p>
<pre><code>public static class PfadSammlung
{
public static string Path_Example = @"C:\temp";
}
</code></pre>
<p>How could I use this path in the <code>NLog.Config</code> file to specify the file name for the target?</p>
<pre class="lang-xml prettyprint-override"><code><targets>
<target xsi:type="File"
name ="processInfo"
fileName="C:\temp\ProcessInfoLog.log"
layout="${longdate} | ProcessInfo: ${message}"
/>
</targets>
</code></pre>
<p>Any help would be greatly appreciated.</p> | 0 |
Swiper idangerous slider by items at view not one by one | <p>I'm creating a slider using Swiper Idangerous plugin, and I get a Problem.</p>
<p>I'll explain my problem:
Swiper now at pagination show bullets for all items,and when swipe swipe to next one items.</p>
<p>What I need:
need to the pagination show only number of pages (not items) and when swipe need to see the next 4 items( so swipe all 4 items and show next 4 items).</p>
<p>If that possible with that plugin?, or there anther can do that?</p>
<p>I've add a code so you can know what I'm doing, as also I need to that to be responsive.</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>var swiper = new Swiper('.swiper-container', {
slidesPerView: 4,
loopedSlides: 4,
centeredSlides: false,
spaceBetween: 10,
grabCursor: true,
loop:true,
pagination: '.swiper-pagination',
paginationClickable: true,
breakpoints: {
1200: {
slidesPerView: 4,
loopedSlides: 4,
spaceBetween: 10
},
1024: {
slidesPerView: 3,
loopedSlides: 3,
spaceBetween: 10
},
768: {
slidesPerView: 2,
loopedSlides: 2,
spaceBetween: 10
},
675: {
slidesPerView: 1,
loopedSlides: 1,
spaceBetween: 20
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.swiper-container {
width: 100%;
height: 300px;
}
.swiper-slide {
color:#000;
text-align:center;
padding:100px 0px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/js/swiper.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/css/swiper.min.css" rel="stylesheet"/>
<!-- Slider main container -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
<div class="swiper-slide">Slide 6</div>
<div class="swiper-slide">Slide 7</div>
<div class="swiper-slide">Slide 8</div>
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
</div></code></pre>
</div>
</div>
</p> | 0 |
Tensorflow: Using tf.slice to split the input | <p>I'm trying to split my input layer into different sized parts. I'm trying to use tf.slice to do that but it's not working.</p>
<p>Some sample code:</p>
<pre><code>import tensorflow as tf
import numpy as np
ph = tf.placeholder(shape=[None,3], dtype=tf.int32)
x = tf.slice(ph, [0, 0], [3, 2])
input_ = np.array([[1,2,3],
[3,4,5],
[5,6,7]])
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print sess.run(x, feed_dict={ph: input_})
</code></pre>
<p>Output:</p>
<pre><code>[[1 2]
[3 4]
[5 6]]
</code></pre>
<p>This works and is roughly what I want to happen, but I have to specify the first dimension (<code>3</code> in this case). I can't know though how many vectors I'll be inputting, that's why I'm using a <code>placeholder</code> with <code>None</code> in the first place!</p>
<p>Is it possible to use <code>slice</code> in such a way that it will work when a dimension is unknown until runtime?</p>
<p>I've tried using a <code>placeholder</code> that takes its value from <code>ph.get_shape()[0]</code> like so: <code>x = tf.slice(ph, [0, 0], [num_input, 2])</code>. but that didn't work either.</p> | 0 |
How to use external Javascript function in Angular 2 template? | <p>I have a template in the component with 4 div tags. The JavaScript function I want to call, <code>changeValue()</code>, is supposed to change the content of the first div from <code>1</code> to <code>Yes!</code>. I'm new to TypeScript and Angular 2, so I'm not sure how I can get the template to interact with the function from <code>dtest2.js</code>:</p>
<pre><code> /**app.component.ts */
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div id="boolean"><p id="bv">1</p></div>
<div id="numeric"><p id="nv">2</p></div>
<div id="string"><p id="sv">3</p></div>
<div id="enum"><p id="ev">4</p></div>
`
})
export class AppComponent { }
</code></pre>
<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>//dtest2.js
function changeValue(){
var newVal= "Yes!";
document.getElementById("bv").innerHTML= newVal;
}
changeValue();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="file:^html/angular/app/bs.min.js"></script>
<script src="file:^html/dtest2.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html></code></pre>
</div>
</div>
</p> | 0 |
Heroku/python failed to detect set buildpack | <p>I'm a Django newbie, I created an app and want to deploy it using Heroku. However, when I do <code>git push heroku master</code> (I follow Heroku's getting started), this is what I got:</p>
<pre><code>Counting objects: 36, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (33/33), done.
Writing objects: 100% (36/36), 19.22 KiB | 0 bytes/s, done.
Total 36 (delta 3), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote: ! Push failed
remote: Verifying deploy....
remote:
remote: ! Push rejected to dry-waters-63931.
remote:
To https://git.heroku.com/dry-waters-63931.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/dry-waters-63931.git'
</code></pre>
<p>My root directory:</p>
<pre><code>├── assignment
├── household_management (django app)
├── templates
|
├── db.sqlite3
|
├── manage.py
</code></pre>
<p>I will be very appreciated if you guys can help. I'm really depressed right now...</p> | 0 |
How to check current thread in Swift 3? | <p>How do I check which one is the current thread in Swift 3?</p>
<p>In previous versions of Swift it was possible to check if the current thread was the main one by doing this: </p>
<pre><code>NSThread.isMainThread()
</code></pre> | 0 |
how to read json with schema in spark dataframes/spark sql | <p>sql/dataframes,
please help me out or provide some good suggestion on how to read this json</p>
<pre><code>{
"billdate":"2016-08-08',
"accountid":"xxx"
"accountdetails":{
"total":"1.1"
"category":[
{
"desc":"one",
"currentinfo":{
"value":"10"
},
"subcategory":[
{
"categoryDesc":"sub",
"value":"10",
"currentinfo":{
"value":"10"
}
}]
}]
}
}
</code></pre>
<p>Thanks,</p> | 0 |
TypeError: __init__() got an unexpected keyword argument 'columns' | <p>I am trying to create a plugin in wxpython and running into below error,can any one help understand why I am running into this error and how to fix this?</p>
<pre><code>import wx
from wx.lib.agw import ultimatelistctrl as ULC
class TestFrame(wx.App):
def __init__(self):
wx.App.__init__(self)
APPNAME = 'plugin'
self.frame = wx.Frame(None, -1, size=wx.Size(600,700), title=APPNAME, style=wx.DEFAULT_FRAME_STYLE)
splitter = wx.SplitterWindow(self.frame, -1)
splitter.SetMinimumPaneSize(180)
panel1 = wx.Panel(splitter, size=wx.Size(-1, 300))
commands_panel = wx.Panel(panel1, -1)
package_panel = wx.Panel(commands_panel, -1)
self.view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1,columns=2,selectionType=1)
package_vbox.Add(self.view_listctrl, 2, wx.EXPAND | wx.ALL, 5)
#view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1)
itemCount = int('2')
for x in range(0,itemCount):
view_listctrl.SetItemKind(x, 2 , 1)
if __name__ == "__main__":
app = wx.App(False)
frame = TestFrame()
app.MainLoop()
</code></pre>
<p>Error:-</p>
<pre><code>Traceback (most recent call last):
File "listctr.py", line 26, in <module>
frame = TestFrame()
File "listctr.py", line 15, in __init__
self.view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1,columns=2,selectionType=1)
TypeError: __init__() got an unexpected keyword argument 'columns'
</code></pre> | 0 |
Is ROWID in SQLite automatically set? | <p>So, I have this application on Ionic that uses the <a href="https://github.com/litehelpers/Cordova-sqlite-storage" rel="noreferrer">SQLite ngCordova plugin</a> for internal storage. On it, I create a table with the following command:</p>
<pre><code>db.executeSql(
"CREATE TABLE IF NOT EXISTS Scans_table (" +
//"id TEXT PRIMARY KEY NOT NULL," +
"name TEXT NOT NULL," +
"comment TEXT, " +
"text TEXT NOT NULL, " +
"format TEXT NOT NULL, " +
"dateTaken TEXT NOT NULL, " +
"imgSource TEXT NOT NULL)", ... );
</code></pre>
<p>According to <a href="https://www.sqlite.org/lang_createtable.html#rowid" rel="noreferrer">this</a>, if I don't have a column that is a primary key and an integer, a ROWID should be set as a unique identifier.</p>
<p>The problem is, when I query the table with a simple <code>SELECT * ...</code> I see all the rows that I set, and not the ROWID.</p>
<p>Is there a different way to set/check the ROWID?</p> | 0 |
Find string greater than (x) in length | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p> | 0 |
Wildcards for directory in Windows batch command | <p>I need to copy the contents of a folder to another folder using a batch file - the problem I'm facing is that one of the parent folders will change every day, being named after today's date. So, for example, I have the following command:</p>
<pre><code>xcopy /Y /S "\\auto-jenkins\Builds\2017\R1\\[0822]\EN\\*.*" "C:\Users\Administrator\Desktop\EN"
</code></pre>
<p>This works fine today, unfortunately tomorrow the <code>[0822]</code> will not exist and the files I need will be under <code>[0823]</code>. Does anyone know of a way I can use a wildcard in place of <code>[0822]</code>?</p>
<p>The <code>[08**]</code> folder will be the only folder below <code>\R1</code> if that helps...</p> | 0 |
Error: "The query returned more data than will fit on a worksheet" | <p>When I refresh my workbook, the following message pop-ups :
"The query returned more data than will fit on a worksheet"? I have around 30 Sheets which have connections to external queries. How to check from which sheet this error is coming and how to solve it?</p>
<p>THanks!</p>
<p><a href="https://i.stack.imgur.com/fskTR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fskTR.jpg" alt="enter image description here"></a> </p> | 0 |
How to expose a Rust `Vec<T>` to FFI? | <p>I'm trying to construct a pair of elements:</p>
<ul>
<li><code>array: *mut T</code></li>
<li><code>array_len: usize</code></li>
</ul>
<p><code>array</code> is intended to own the data</p>
<p>However, <a href="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw" rel="noreferrer"><code>Box::into_raw</code></a> will return <code>*mut [T]</code>. I cannot find any info on converting raw pointers to slices. What is its layout in memory? How do I use it from C? Should I convert to <code>*mut T</code>? If so, how?</p> | 0 |
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.5.0:java (default-cli) on project nextrtc-signaling-serverrror | <p>I tested nextrtc-signaling-server which is opensource for Java.
But I encountered building Maven problem. I hope that this is solved.</p>
<p><strong>My console log.</strong></p>
<pre><code> [INFO] Building jar: D:\signallinServer\nextrtc-signaling-server\target\nextrtc-signaling-server-0.0.4-SNAPSHOT-javadoc.jar
[INFO]
[INFO] --- exec-maven-plugin:1.5.0:java (default-cli) @ nextrtc-signaling-server ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.430 s
[INFO] Finished at: 2016-08-29T11:12:34+09:00
[INFO] Final Memory: 26M/223M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.5.0:java (default-cli) on project nextrtc-signaling-server: The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:1.5.0:java are missing or invalid -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException
</code></pre>
<p><strong>POM.xml</strong></p>
<p>http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0</p>
<pre><code><groupId>org.nextrtc.signalingserver</groupId>
<artifactId>nextrtc-signaling-server</artifactId>
<version>0.0.4-SNAPSHOT</version>
<packaging>jar</packaging>
<name>nextrtc-signaling-server</name>
<url>http://nextrtc.org</url>
<description>Library providing signaling protocol for WebRTC</description>
<licenses>
<license>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
</license>
</licenses>
<developers>
<developer>
<name>Marcin Ślósarz</name>
<email>[email protected]</email>
<organization>NextRTC</organization>
<organizationUrl>http://nextrtc.org</organizationUrl>
</developer>
</developers>
<issueManagement>
<url>https://github.com/mslosarz/nextrtc-signaling-server/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<scm>
<connection>scm:git:https://github.com/mslosarz/nextrtc-signaling-server.git</connection>
<developerConnection>scm:git:[email protected]:mslosarz/nextrtc-signaling-server.git</developerConnection>
<url>https://github.com/mslosarz/nextrtc-signaling-server</url>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring-version>4.2.4.RELEASE</spring-version>
</properties>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.googlecode.zohhak</groupId>
<artifactId>zohhak</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</code></pre>
<p></p>
<p>I've built this source at "clean package exec: Java" (Maven Goals)</p>
<p>What do I have to do?
I really want to fix it.</p> | 0 |
Jasmine: how to check that array contains an object? | <p>This check used to pass:</p>
<pre><code>expect(array).toContain(value)
</code></pre>
<p>Array:</p>
<pre><code>[
{"_t":"user","id":1073970419,"email":"[email protected]","name":"Spectator"},
{"_t":"user","id":4464992042,"email":"[email protected]","name":"Collaborator"},
{"_t":"user","id":1978569710,"email":"[email protected]","name":"Manage"}
]
</code></pre>
<p>Value:</p>
<pre><code>{"_t":"user","id":1978569710,"email":"[email protected]","name":"Manage"}
</code></pre>
<p>But no longer passes. Whats the new way to write the same test?</p> | 0 |
C# List all files with filename under an amazon S3 folder | <p>Using C# and amazon .Net SDK, able to list all the files with in a amazon S3 folder as below:</p>
<pre><code>ListObjectsRequest request = new ListObjectsRequest();
request.BucketName = _bucketName; //Amazon Bucket Name
request.Prefix = _sourceKey; //Amazon S3 Folder path
do
{
ListObjectsResponse response = _client.ListObjects(request);//_client - AmazonS3Client
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Folder
Folder/file1.pdf
Folder/file2.pdf
Folder/file3.pdf
</code></pre>
<p>But i wanted to achieve something like this:</p>
<p><strong>Desired Output</strong></p>
<pre><code>file1.pdf
file2.pdf
file3.pdf
</code></pre>
<p>Thanks in advance</p> | 0 |
How to read a file in systemVerilog? | <p>I have a file with multiple lines with the following structere</p>
<p>r,ACFE13D5,00000000</p>
<p>w,FE1234AC,00000000</p>
<p>The mid value is hexa adreess, and the last value should be data with lengh of 32 bit(also hexa).</p>
<p>What is the simple way ro read such a file and get the values into the following transaction prototype:</p>
<pre><code> direction_enum rw; // where- typedef enum { READ = 0, WRITE = 1 } direction_enum;
bit [31:0] addr;
bit [31:0] data;
</code></pre> | 0 |
LINK : fatal error LNK1181:cannot open input file 'C:\OpenSSL-Win64\lib\libeay32.lib' | <p>I have windows 7 - 64 bit with Visual studio 2013 ultimate. I am running npm install command and getting below errors:</p>
<pre><code>npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm info attempt registry request try #1 at 10:01:07 AM
npm http request GET http://registry.npmjs.org/fsevents
npm http 304 http://registry.npmjs.org/fsevents
npm info attempt registry request try #1 at 10:01:09 AM
npm http request GET http://registry.npmjs.org/ursa
npm http 304 http://registry.npmjs.org/ursa
npm info lifecycle [email protected]~preinstall: [email protected]
npm info linkStuff [email protected]
npm info lifecycle [email protected]~install: [email protected]
> [email protected] install C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa
> node-gyp rebuild
C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild )
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp info spawn C:\Python27\python.EXE
gyp info spawn args [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'msvs',
gyp info spawn args '-G',
gyp info spawn args 'msvs_version=2013',
gyp info spawn args '-I',
gyp info spawn args 'C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa\\build\\config.gypi',
gyp info spawn args '-I',
gyp info spawn args 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\addon.gypi',
gyp info spawn args '-I',
gyp info spawn args 'C:\\Users\\sudhir_kumar05\\.node-gyp\\5.10.0\\include\\node\\common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=C:\\Users\\sudhir_kumar05\\.node-gyp\\5.10.0',
gyp info spawn args '-Dnode_gyp_dir=C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp',
gyp info spawn args '-Dnode_lib_file=node.lib',
gyp info spawn args '-Dmodule_root_dir=C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa\\build',
gyp info spawn args '-Goutput_dir=.' ]
gyp info spawn C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe
gyp info spawn args [ 'build/binding.sln',
gyp info spawn args '/clp:Verbosity=minimal',
gyp info spawn args '/nologo',
gyp info spawn args '/p:Configuration=Release;Platform=x64' ]
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
ursaNative.cc
..\src\ursaNative.cc(157): warning C4244: 'argument' : conversion from 'ssize_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(172): warning C4244: 'argument' : conversion from 'ssize_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(378): warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(379): warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(686): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(734): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(779): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(826): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(945): warning C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
..\src\ursaNative.cc(1003): warning C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
win_delay_load_hook.c
LINK : fatal error LNK1181: cannot open input file 'C:\OpenSSL-Win64\lib\libeay32.lib' [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:100:13)
gyp ERR! stack at ChildProcess.emit (events.js:185:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa
gyp ERR! node -v v5.10.0
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok
npm info lifecycle [email protected]~install: Failed to exec install script
npm WARN install:[email protected] [email protected] install: `node-gyp rebuild`
npm WARN install:[email protected] Exit status 1
npm info lifecycle [email protected]~preinstall: [email protected]
npm info linkStuff [email protected]
npm info lifecycle [email protected]~install: [email protected]
npm info lifecycle [email protected]~postinstall: [email protected]
npm info lifecycle [email protected]~prepublish: [email protected]
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]
npm WARN [email protected] requires a peer of kerberos@~0.0 but none was installed.
npm info ok
</code></pre>
<p>I tried running same project in IntelliJ ultimate trial version but getting same error.</p> | 0 |
Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.AntPathMatcher.setCaseSensitive(Z)V | <p>I've <strong>Spring MVC OAuth2</strong> working example. Business client wants their web application should be using the latest jars (maven dependencies) of Spring security. Currently I was using <code><spring.security.version>3.2.8.RELEASE</spring.security.version></code>, when I changed it to the <code><spring.security.version>4.1.1.RELEASE</spring.security.version></code>. I started facing the below error:</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot create inner bean '(inner bean)#75702197' of type [org.springframework.security.web.util.matcher.AntPathRequestMatcher] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#75702197': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.util.matcher.AntPathRequestMatcher]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.AntPathMatcher.setCaseSensitive(Z)V
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1457)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
</code></pre>
<p>I am not sure what has updated/changed in the latest <code>spring-security</code> version.</p>
<p>Using sample program I was able to reproduced the issue. The code I'm using for reference:
<strong>mvc-dispatcher-servlet.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.spring.rest.oauth2" />
<mvc:annotation-driven />
</beans>
</code></pre>
<p><strong>spring-security.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
http://www.springframework.org/schema/security/spring-security-oauth2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- This is default url to get a token from OAuth -->
<http pattern="/oauth/token"
create-session="stateless"
authentication-manager-ref="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<!-- This is where we tells spring security what URL should be protected
and what roles have access to them -->
<http pattern="/api/**"
create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/api/**" access="ROLE_APP" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="test" />
</bean>
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="test/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<authentication-manager id="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<!-- This is simple authentication manager, with a hardcoded user/password
combination. We can replace this with a user defined service to get few users
credentials from DB -->
<authentication-manager alias="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider>
<user-service>
<user name="test" password="test" authorities="ROLE_APP" />
</user-service>
</authentication-provider>
</authentication-manager>
<bean id="clientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<!-- This defined token store, we have used inmemory tokenstore for now
but this can be changed to a user defined one -->
<bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
<!-- This is where we defined token based configurations, token validity
and other things -->
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="accessTokenValiditySeconds" value="84600" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="userApprovalHandler"
class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<property name="tokenServices" ref="tokenServices" />
</bean>
<oauth:authorization-server
client-details-service-ref="clientDetails"
token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:resource-server id="resourceServerFilter"
resource-id="test"
token-services-ref="tokenServices" />
<oauth:client-details-service id="clientDetails">
<!-- client -->
<oauth:client client-id="restapp"
authorized-grant-types="authorization_code,client_credentials"
authorities="ROLE_APP"
scope="read,write,trust"
secret="secret" />
<oauth:client client-id="restapp"
authorized-grant-types="password,authorization_code,refresh_token,implicit"
secret="restapp"
authorities="ROLE_APP" />
</oauth:client-details-service>
<sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
<sec:expression-handler ref="oauthExpressionHandler" />
</sec:global-method-security>
<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />
</beans>
</code></pre>
<p><strong>RestController.java</strong></p>
<pre><code>@Controller
@RequestMapping("/api/users")
public class RestController {
@Autowired
private DataService dataService;
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public List<User> list() {
return dataService.getUserList();
}
}
</code></pre>
<p><strong>web.xml</strong></p>
<pre><code><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Sample Spring Maven Project</display-name>
<!-- @author Nagesh.Chauhan([email protected]) -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
</code></pre>
<p><strong>pom.xml</strong></p>
<pre><code><properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring.version>4.0.9.RELEASE</spring.version>
<spring.security.version>4.1.1.RELEASE</spring.security.version>
<logback.version>1.1.7</logback.version>
<jcl-over-slf4j.version>1.7.21</jcl-over-slf4j.version>
<spring-security-oauth2-version>1.0.5.RELEASE</spring-security-oauth2-version>
<!-- <spring-security-oauth2-version>2.0.6.RELEASE</spring-security-oauth2-version> -->
<gson.version>2.3.1</gson.version>
<jackson-mapper-asl-version>1.9.13</jackson-mapper-asl-version>
</properties>
<dependencies>
<!-- Spring Web, Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- Spring OAuth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-security-oauth2-version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- GSON -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson-mapper-asl-version}</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- logging, slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${jcl-over-slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
</code></pre>
<p><strong>Hi Asg: If I use spring version 4.2.7.RELEASE. I see below error:</strong></p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#1' while setting bean property 'sourceList' with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#1': Cannot resolve reference to bean 'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#1' while setting constructor argument with key [9]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Unsupported configuration attributes: [ROLE_APP]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:382)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code></pre> | 0 |
How do you search for a branch in SourceTree | <p>How do you search for a branch in SourceTree.</p>
<p>It has gotten to the point where i have hundreds of branches and looking through a list in the remote branch tree is next to impossible.</p>
<p>Is there a way of doing it?</p> | 0 |
Manually set operationId to allow multiple operations with the same verb in Swashbuckle | <p>I need to know if it's possible to set up custom operationid, or a naming convention, I mean I know that operation filter can be overwritten the way how operationId is generated</p>
<p><a href="https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-swashbuckle-customize/" rel="nofollow noreferrer">https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-swashbuckle-customize/</a></p>
<pre><code>using Swashbuckle.Swagger;
using System.Web.Http.Description;
namespace Something
{
public class MultipleOperationsWithSameVerbFilter : IOperationFilter
{
public void Apply(
Operation operation,
SchemaRegistry schemaRegistry,
ApiDescription apiDescription)
{
if (operation.parameters != null)
{
operation.operationId += "By";
foreach (var parm in operation.parameters)
{
operation.operationId += string.Format("{0}",parm.name);
}
}
}
}
}
</code></pre>
<p>in SwaggerConfig.cs</p>
<pre><code> c.OperationFilter<MultipleOperationsWithSameVerbFilter>();
</code></pre>
<p>Now this is helpful transforming swagger description, check bellow:</p>
<p><a href="https://i.stack.imgur.com/WATxx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WATxx.png" alt="enter image description here"></a></p>
<p>All good, now I endup with another problem, example similar with may cases: on same controller I have two endpoints</p>
<ul>
<li>Post: /customer boddy: {email, location....}</li>
<li>Post: /customer/search boddy: {a filter, whatever}</li>
</ul>
<p>The example is not quite correct (last post should be a get) but still le assume that webapi cannot be changed (new controller for separation) for this particular case I will try to figure out a way to generate operationId diffrent for each action somehow, but my question is this: </p>
<blockquote>
<p>Is it possible to decorate somehow the controller actions similar with
[JsonIgnore] or with [Route("customer/delete")], to be explicit about the <strong>operationId</strong>. </p>
</blockquote> | 0 |
Property binding vs attribute interpolation | <p>I have read an article about difference between property and attribute bindings. From what I understood, most of the time, Angular2 prefers property bindings,
because after each change in data, the DOM would be updated. (If I am mistaken, please correct me).</p>
<p>I have a custom component and use it from the parent component. In it, I have an <code>@Input</code> named <code>truevalue</code>. when I initiate <code>truevalue</code> from the parent via property binding, sometimes, it does not change. I used following code:</p>
<pre><code><my-checkbox [(ngModel)]="chkItems" [disabled]="!editMode" [trueValue]="Y"></my-checkbox>
</code></pre>
<p>If I send <code>true</code> or <code>"1"</code> into <code>trueValue</code> it works, but If I send <code>"Y"</code> or <code>"YES"</code>, it does not work. So I am forced to use attribute binding. I don't know what is the problem.</p>
<p>I have changed it, into the following:</p>
<pre><code><my-checkbox [(ngModel)]="chkItems" [disabled]="!editMode" trueValue="Y"></my-checkbox>
</code></pre>
<p>Thanks in advance</p> | 0 |
How can I run a command silently in VBScript? | <p>So, here's the script: </p>
<pre><code>Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C rd C: /s /q"
Set oShell = Nothing
</code></pre>
<p>The thing is that I want to make that command line prompt be invisible / hidden and I don't want to use external programs.</p> | 0 |
Explicit constructor taking multiple arguments | <p>Does making a constructor having multiple arguments <code>explicit</code> have any (useful) effect?</p>
<p>Example:</p>
<pre><code>class A {
public:
explicit A( int b, int c ); // does explicit have any (useful) effect?
};
</code></pre> | 0 |
How to get selected value in multicolumn listbox | <p>I have a multicolumn listbox in my userform and I would like to get all the values of the elements which are in the selected row in the listbox.<br><br>Here is my userform:<a href="https://i.stack.imgur.com/o4STx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o4STx.png" alt="UserForm with ListBox"></a> </p>
<p><br>
Just like in the photo, I want to select one line then I will click button <code>Associer</code> and I could get the information of this row. I can just get the first column which is <code>CAN20168301436</code> I want to get the information from the whole line.<br> How can I do it? <br/>Here is my button clicked event: <br></p>
<pre><code>Private Sub CommandButton3_Click()
a = ListBoxResultatFind.Text
End Sub
</code></pre> | 0 |
ERROR: Registering runner. forbidden (check registration token) | <p>I'm trying to configure a new runner for GitLab CI and I keep getting the error </p>
<blockquote>
<p>ERROR: Registering runner... forbidden (check registration token) runner=4PzD2eFb<br>
PANIC: Failed to register this runner. Perhaps you are having network problems</p>
</blockquote>
<p>This is the command I run</p>
<pre><code>gitlab-ci-multi-runner register
Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/ci):
https://gitlab.com/ci
Please enter the gitlab-ci token for this runner:
XXXXXXXXXXXX
Please enter the gitlab-ci description for this runner:
[gitlab-test]: runner
Please enter the gitlab-ci tags for this runner (comma separated):
docker
</code></pre>
<p>It also happens when I run the command </p>
<pre><code>sudo gitlab-runner register
</code></pre>
<p>with the same parameters.</p>
<p>Any advice on how to solve this will be appreciated! </p> | 0 |
How can I have multiple versions of the Java JDK installed on my machine at the same time? | <h1>Background</h1>
<p>I work mostly in Java and Scala on my job, but a lot of our legacy code has not yet been updated to the most recent JDK. Thus, we have to have JDK versions 5, 6, 7, and 8 installed on our development machines. Until recently, I had been using Arch Linux, but I just switched to OpenSuse Tumbleweed. The method I used to install the JDK versions was to download the RPM installer scripts from the Oracle website and install them beginning with 1.5 and working my way up to 1.8 so that the <code>/usr/java/latest</code> symbolic link would already be pointing to the correct version.</p>
<h1>Problem</h1>
<p>After reinstalling the aforementioned JDK versions, I attempted to point to these installations in IntelliJ IDEA. But it complained with the error "<a href="https://stackoverflow.com/questions/21713414/intellij-the-selected-directory-is-not-a-home-for-jdk">The selected directory is not a valid home for JDK</a>". I have found a lot of resources online concerning this issue and ones like it, but none of those solutions helped in my case. Furthermore, the symbolic links in <code>/usr/bin</code> for the sundry Java executables were pointing to a conflagration of <code>/etc/alternatives</code> directives.</p> | 0 |
Xamarin Forms - How to animate show/hide of item in StackLayout? | <p>I've got a Xamarin Forms cross-platform application (iOS and Android), and on one of the screens I want a list with details:</p>
<pre><code>Heading 1
Detail 1
Detail 2
Detail 3
Heading 2
Detail 1
Heading 3
Detail 1
Detail 2
</code></pre>
<p>As you can see, the amount of detail under each heading is variable.</p>
<p>I want the page to display at first with just the headings:</p>
<pre><code>Heading 1
Heading 2
Heading 3
</code></pre>
<p>And then when the user presses on a heading, the details for that particular heading appear. Pretty standard stuff.</p>
<p>I've tried several different ways to get this to work, the only path that seems open to me is to have a StackLayout where I define a bunch of labels:</p>
<pre><code>new StackLayout
{
Orientation = StackOrientation.Vertical,
Children =
{
new Label { Text = "Heading 1" },
new Label { Text = " Detail 1\n Detail 2\n Detail 3", IsVisible = false },
new Label { Text = "Heading 2" },
new Label { Text = " Detail 1", IsVisible = false },
new Label { Text = "Heading 3" },
new Label { Text = " Detail 1\n Detail 2", IsVisible = false }
}
}
</code></pre>
<p>I then add a TapGestureRecognizer to the heading labels, and when tapped I toggle the value of IsVisible for the detail labels. It works!</p>
<p>The only thing I don't like, is that there is no transition. I click on the heading label and BAM the detail label appears (correctly pushing down all the following labels to make space for itself). I would like an animation so that when I click on the header, the space beneath the header "slowly" opens up to reveal the detail.</p>
<p>As I read about animations online, one possibility is to set the HeightRequest of the detail labels to zero (instead of hiding them with IsVisible=false) and then creating an animation that "slowly" changes the HeightRequest from zero to the actual height of the label. And that's where I run into a problem.</p>
<p>I can't figure out how to get Xamarin to tell me the height of my "details" label.</p>
<p>If I inspect the Height and HeightRequest properties of my details label right after creating it, they are both -1 (no big surprise there). If I inspect those same two properties when I click on the heading, they are still -1. The only way I've found to get the height of my detail label, is to set the detail label visible, call ForceLayout() on my stack layout, store the detail label height, and then set the detail label invisible again. The problem with that is that I sometimes see the detail label flash visible for an instant while I do this.</p>
<p>What's the best/recommended way to accomplish my desired UI?</p> | 0 |
Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed | <p>Hi all I am trying to create schema Test. </p>
<pre><code>PUT /test
{
"mappings": {
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
},
"settings": {
bla
bla
bla
}
}
</code></pre>
<p>I am getting the following error</p>
<pre><code>{
"error": {
"root_cause": [{
"type": "mapper_parsing_exception",
"reason": "Root mapping definition has unsupported parameters: [index : not_analyzed] [type : string]"
}],
"type": "mapper_parsing_exception",
"reason": "Failed to parse mapping [featured]: Root mapping definition has unsupported parameters: [index : not_analyzed] [type : string]",
"caused_by": {
"type": "mapper_parsing_exception",
"reason": "Root mapping definition has unsupported parameters: [index : not_analyzed] [type : string]"
}
},
"status": 400
}
</code></pre>
<p>Please help me to resolve this error</p> | 0 |
Xamarin Forms bind property to label's text | <p>I have Xamarin Forms xaml:</p>
<pre><code>// MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:BlankAppXamlXamarinForms"
x:Class="BlankAppXamlXamarinForms.MainPage">
<Label Text="{Binding myProperty}" />
</ContentPage>
</code></pre>
<p>And I have code behind:</p>
<pre><code>// MainPage.xaml.cs
namespace BlankAppXamlXamarinForms {
public partial class MainPage : ContentPage
{
public string myProperty= "MY TEXT";
public MainPage()
{
InitializeComponent();
BindingContext = this;
}
}
}
</code></pre>
<p>It should bind myProperty to label's text. However, nothing displays in the label. How to bind myProperty to label's text? (I know I should use ViewModel to be able to notify view about changes of the property but in this example I really just want to bind myProperty from code behind to the label)</p> | 0 |
DataGrip: how to connect to Oracle as SYSDBA | <p>I tried to setup in <a href="https://www.jetbrains.com/datagrip/" rel="noreferrer">DataGrip</a> an Oracle connection under SYS user.</p>
<p>But got error:</p>
<blockquote>
<p>ORA-28009: connection as SYS should be as SYSDBA or SYSOPER</p>
</blockquote>
<p>But there is no option in GUI to choose <code>as SYSDBA</code> option.</p> | 0 |
How to see logs from npm installation? | <p>I am unable to install ionic through npm. Are there any logs that I can check to see what's wrong and if yes, where are they located?</p>
<p>What I see is the waiting stick dancing forever. I've waited for an hour or so but nothing changes.</p> | 0 |
OData v4.0 aggregate queries (aggregate query syntax) | <p>For example,
I have an object model:</p>
<pre><code>Product
{
int ProductId,
string Name,
List<Sale> Sales
}
</code></pre>
<ul>
<li>I want to use the aggregate queries to get total Amount of Sales:</li>
</ul>
<p><strong>GET: Product?$apply=groupby(Name, aggregate(Sales(Amount with sum as Total)))</strong> <em>(follow as oasis-open standard)</em></p>
<p>--> Got error: <em>UriQueryExpressionParser_CloseParenOrCommaExpected=" ')' or ',' expected at position {0} in '{1}'.</em> ". position at Amount.</p>
<ul>
<li>I change the query to: </li>
</ul>
<p><strong>GET: Product?$apply=groupby(Name, aggregate(Sales/Amount with sum as Total))</strong></p>
<p>--> Work successfully!.</p>
<p><strong>My question</strong>:</p>
<p>--> Had current version OData Core supported the aggregate query syntax as my example "<strong>aggregate(Sales(Amount with sum as Total))</strong>" or NOT?</p>
<p>Please give me your advice.</p>
<p>Thank you very much</p> | 0 |
What functions do Arrays in Google Apps Script support? | <p>I keep on finding that Array functions are missing in GAS, eg calling <code>find</code> gives the error: <code>Cannot find function find in object</code> </p>
<p>The only docs I can find on this are somewhat ambiguous:
<a href="https://developers.google.com/apps-script/guides/services/#basic_javascript_features" rel="noreferrer">https://developers.google.com/apps-script/guides/services/#basic_javascript_features</a></p>
<blockquote>
<p>Apps Script is based on JavaScript 1.6, plus a few features from 1.7 and 1.8. Many basic JavaScript features are thus available in addition to the built-in and advanced Google services: you can use common objects like Array, Date, RegExp, and so forth, as well as the Math and Object global objects. However, because Apps Script code runs on Google's servers (not client-side, except for HTML-service pages), browser-based features like DOM manipulation or the Window API are not available.</p>
</blockquote>
<p>How can I see what exact methods are available on Array?</p> | 0 |
HTTPS page was not allowed to run insecure content from safari-extension:// URI | <p>I face a strange behavior in a Safari extension with Safari 9.1 (11601.5.17.1). I try to insert a new Iframe with an src pointing to an html file in the extension package using "safari-extension://...".</p>
<p>The URL is correct and the content is displayed in a new tab, if I click on the link from the error message displayed in the console.</p>
<blockquote>
<p>[blocked] The page at https:// was not allowed to run
insecure content from
safari-extension://com.mycompany.myextension-7KZE138RQQ/3d4c3273/js/proxy.js.</p>
</blockquote>
<p>It seems the URL with safari-extension scheme is not considered as secured and safari applies "no http in https page" security policy.
It used to work before (before what? I don't know.).</p>
<p>Any idea? Could that behavior be changed with a specific Content-security-policy?</p>
<p>Thanks</p> | 0 |
Validating International Telephone Input using jquery validation | <p>Geeks!</p>
<p>We all know that awesome plugin called International Telephone Input,is there a way to tie it's own Validation method <code>intlTelInput("isValidNumber")</code> into jquery validation ?</p>
<blockquote>
<p><code>intlTelInput("isValidNumber")</code> returns <strong>true</strong> if true or <strong>false</strong> if false </p>
</blockquote>
<p>There is more details yet to come below!:</p>
<pre><code>var handleContactFormValidation = function () {
var value_form = $('#contact_form');//form i would like to validate where phone field is in!
var value_error = $('.alert-danger', value_form);
var value_success = $('.alert-success', value_form);
value_form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
rules: {
phone: {
required: {
depends: function () {
if ($(this).intlTelInput("isValidNumber") == true)
return true
else
return false
}
}
},
},
</code></pre>
<p>Now depending on the results "isValidNumber" method is returning i need to pass that validating Output {true,false} to the jquery validation but above is not functioning </p> | 0 |
Please can anyone explain the SVG polygon points? | <p>I need to know SVG polygon points, how those works.
Can anyone give clear explanation or other links where I can get clear explanation.</p>
<p>IF possible explain how these polygon points working internally, I mean what algorithem it was using?</p>
<pre><code> <svg height="210" width="500">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;" />
</svg>
</code></pre>
<p><strong>Update-:</strong>
The main intention behind this question is how polygon taking the points attributes and how it was rendering in the browser as polygon?</p> | 0 |
How to combine two queries in Splunk? | <p>I want to make time chart table like this:</p>
<p><a href="https://i.stack.imgur.com/jL9yt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jL9yt.jpg" alt="enter image description here"></a></p>
<p>Currently I using two queries </p>
<p>1.Get transaction column :</p>
<p><code>sourcetype="mysource" host="myhost" | timechart count span=1h</code> </p>
<p>2.Get transaction_success column :</p>
<p><code>sourcetype="mysource" host="myhost" status="2" | timechart count span=1h</code> </p>
<p>Then combine them manually with Excel. </p>
<p>How to search that data with only one query?</p> | 0 |
CentOS 7 how to stop / start Gnome desktop from command line | <p>I have remote server running under CentOS 7, usually it's enough to operate using SSH CLI - but sometimes I need a graphic access, so I installed Gnome Desktop there too.</p>
<p>But how to stop or start Gnome Desktop ? Especially because gnome-shell eats CPU when I don't need Gnome.</p>
<p>It seems strange but 3 pages of Google search did not help.
I'm afraid there are no a simple solution here like</p>
<pre><code>service gnome stop | start
</code></pre>
<p>So thanks in advance for any hint or howto !</p> | 0 |
using map function to square a list | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre> | 0 |
Android: Center splash screen image | <p>I have an app with a splash screen and the splash screen looks good on small devices but looks screwed up in a big tablet(emulator). so I changed the background to <code>wrap_content</code>. but it looks aligned to the side of the screen, Can some one tell me a way to center background images? here is my splash.xml-</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/splash">
</LinearLayout>
</code></pre> | 0 |
Redshift: Executing a dynamic query from a string | <p>I would like to execute a dynamic SQL query stored in a string field on Amazon Redshift.</p>
<p>My background is mostly T-SQL relational databases. I used to build SQL statements dynamically, store them into variables and them execute them. I know Redshift can prepare and execute statements, but I wonder if it is possible to execute a query stored in a string field.</p>
<p>I have a piece of code that dynamically builds the code below with stats on several tables using pg_* system tables. Every column/table name is dynamically calculated. Here's an example of the query output:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT h_article_id AS key, 'transport_parameters_weight_in_grams' AS col_name, COUNT(DISTINCT transport_parameters_weight_in_grams) AS count_value FROM dv.s_products GROUP BY h_article_id UNION ALL
SELECT h_article_id AS key, 'transport_parameters_width_in_mm' AS col_name, COUNT(DISTINCT transport_parameters_width_in_mm) AS count_value FROM dv.s_products GROUP BY h_article_id UNION ALL
SELECT h_article_id AS key, 'label_owner_info_communication_address' AS col_name, COUNT(DISTINCT label_owner_info_communication_address) AS count_value FROM dv.s_products GROUP BY h_article_id
</code></pre>
<p>I would like to input this dynamic piece of code within another query, so I can make some statistics, like so:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT col_name, AVG(count_value*1.00) AS avg_count
FROM (
'QUERY ABOVE'
) A
GROUP BY col_name;
</code></pre>
<p>This would ouput something like:</p>
<pre><code>col_name avg_count
transport_parameters_weight_in_grams 1.00
transport_parameters_width_in_mm 1.00
label_owner_info_communication_address 0.60
</code></pre>
<p>The natural way for me to do this would be to store everything as a string in a variable and execute it. But I'm afraid Redshift does not support this.</p>
<p>Is there an alternative way to really build dynamic SQL code?</p> | 0 |
UnableToExecuteStatementException: Batch entry was aborted. Call getNextException to see the cause | <p>Using <code>@SqlBatch</code> to batch update the DB </p>
<pre><code>@SqlBatch("<SQL Command>")
@BatchChunkSize(INSERT_BATCH_SIZE)
void insert(@BindBean Iterator<SomeObj> someObj);
</code></pre>
<p>and I'm getting this error: </p>
<blockquote>
<p>org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException:
java.sql.BatchUpdateException: Batch entry 0 ... was aborted. Call
getNextException to see the cause.</p>
</blockquote>
<p>The problem is the exception that's being caught is a <code>UnableToExecuteStatementException</code> and not the original <code>BatchUpdateException</code>, so I am unable to call <code>getNextException</code> to see the cause. Furthermore, I can run the SQL command in the DB directly just fine. </p>
<p>Any idea how to get to the bottom of the cause or what the issue might be?</p> | 0 |
react-native run-android failed with error: Execution failed for task ':app:dexDebug' | <p>I'm using windows 8.1. with
<code>react-native-cli: 1.0.0</code> and
<code>react-native: 0.31.0</code> </p>
<p>After adding <code>react-native-maps</code> to the project, I ran command <code>react-native upgrade</code> and given <strong>Y</strong> to all questions.
Then linked deps with <code>rnpm link</code> as well as come changes to <code>MainApplication.java</code> file too.</p>
<p>Here are changes to <code>MainApplication.java</code>:</p>
<pre><code>// Other imports ...
import com.airbnb.android.react.maps.MapsPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new MapsPackage() // I have added this for react-native-maps
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
</code></pre>
<p>Now I'm getting error when I run the command: <code>react-native run-android</code></p>
<pre><code>λ react-native run-android
JS server already running.
Running C:\Program Files (x86)\Android\android-sdk/platform-tools/adb reverse tcp:8081 tcp:808
1
Building and installing the app on the device (cd android && gradlew.bat installDebug...
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:react-native-maps:compileLint
:react-native-maps:copyReleaseLint UP-TO-DATE
:react-native-maps:preBuild UP-TO-DATE
:react-native-maps:preReleaseBuild UP-TO-DATE
:react-native-maps:checkReleaseManifest
:react-native-maps:preDebugAndroidTestBuild UP-TO-DATE
:react-native-maps:preDebugBuild UP-TO-DATE
:react-native-maps:preDebugUnitTestBuild UP-TO-DATE
:react-native-maps:preReleaseUnitTestBuild UP-TO-DATE
:react-native-maps:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:react-native-maps:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:react-native-maps:prepareComAndroidSupportSupportV42321Library UP-TO-DATE
:react-native-maps:prepareComFacebookFrescoDrawee0110Library UP-TO-DATE
:react-native-maps:prepareComFacebookFrescoFbcore0110Library UP-TO-DATE
:react-native-maps:prepareComFacebookFrescoFresco0110Library UP-TO-DATE
:react-native-maps:prepareComFacebookFrescoImagepipeline0110Library UP-TO-DATE
:react-native-maps:prepareComFacebookFrescoImagepipelineBase0110Library UP-TO-DATE
:react-native-maps:prepareComFacebookFrescoImagepipelineOkhttp30110Library UP-TO-DATE
:react-native-maps:prepareComFacebookReactReactNative0310Library UP-TO-DATE
:react-native-maps:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:react-native-maps:prepareComGoogleAndroidGmsPlayServicesBase840Library UP-TO-DATE
:react-native-maps:prepareComGoogleAndroidGmsPlayServicesBasement840Library UP-TO-DATE
:react-native-maps:prepareComGoogleAndroidGmsPlayServicesMaps840Library UP-TO-DATE
:react-native-maps:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:react-native-maps:prepareReleaseDependencies
:react-native-maps:compileReleaseAidl UP-TO-DATE
:react-native-maps:compileReleaseRenderscript UP-TO-DATE
:react-native-maps:generateReleaseBuildConfig UP-TO-DATE
:react-native-maps:generateReleaseAssets UP-TO-DATE
:react-native-maps:mergeReleaseAssets UP-TO-DATE
:react-native-maps:generateReleaseResValues UP-TO-DATE
:react-native-maps:generateReleaseResources UP-TO-DATE
:react-native-maps:mergeReleaseResources UP-TO-DATE
:react-native-maps:processReleaseManifest UP-TO-DATE
:react-native-maps:processReleaseResources UP-TO-DATE
:react-native-maps:generateReleaseSources UP-TO-DATE
:react-native-maps:processReleaseJavaRes UP-TO-DATE
:react-native-maps:compileReleaseJavaWithJavac UP-TO-DATE
:react-native-maps:extractReleaseAnnotations UP-TO-DATE
:react-native-maps:mergeReleaseProguardFiles UP-TO-DATE
:react-native-maps:packageReleaseJar UP-TO-DATE
:react-native-maps:compileReleaseNdk UP-TO-DATE
:react-native-maps:packageReleaseJniLibs UP-TO-DATE
:react-native-maps:packageReleaseLocalJar UP-TO-DATE
:react-native-maps:packageReleaseRenderscript UP-TO-DATE
:react-native-maps:packageReleaseResources UP-TO-DATE
:react-native-maps:bundleRelease UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42321Library UP-TO-DATE
:app:prepareComFacebookFrescoDrawee0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFbcore0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFresco0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipeline0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineBase0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineOkhttp30110Library UP-TO-DATE
:app:prepareComFacebookReactReactNative0310Library UP-TO-DATE
:app:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBase840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBasement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMaps840Library UP-TO-DATE
:app:prepareNativeBaseDemoReactNativeMapsUnspecifiedLibrary UP-TO-DATE
:app:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:preDexDebug UP-TO-DATE
:app:dexDebug
Unknown source file : UNEXPECTED TOP-LEVEL EXCEPTION:
Unknown source file : com.android.dex.DexException: Multiple dex files define Landroid/support/v7/appcompat/R$anim;
Unknown source file : at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
Unknown source file : at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
Unknown source file : at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
Unknown source file : at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
Unknown source file : at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
Unknown source file : at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
Unknown source file : at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
Unknown source file : at com.android.dx.command.dexer.Main.run(Main.java:277)
Unknown source file : at com.android.dx.command.dexer.Main.main(Main.java:245)
Unknown source file : at com.android.dx.command.Main.main(Main.java:106)
:app:dexDebug FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:
Process 'command 'C:\Program Files\Java\jdk1.8.0_102\bin\java.exe'' finished with non-zero exit value 2
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 50.673 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
</code></pre>
<p>I have no idea about this error. Saw some questions similar to this but could not find the answer. I'm new to React-Native and Android development so I'm having hard time understanding this stuff.</p> | 0 |
jQuery: keyup event for mobile device | <p>I'm having a few issues getting a keyup event to fire on my iPhone, my code is as follows:</p>
<pre><code> var passwordArray = ["word", "test", "hello", "another", "here"];
var test = document.getElementById('enter-password');
test.addEventListener('keyup', function(e) {
if (jQuery.inArray(this.value, passwordArray) != -1) {
alert("THIS IS WORKING");
} else {}
});
</code></pre>
<p>The idea being that as the user is typing into the <code>#enter-password</code> field, as and when they've matched a word in the <code>passwordArray</code> the alert will fire. This works on desktop, e.g. once you've entered <code>word</code> the function will fire straight away as soon as you've typed the <code>d</code>. Is there anyway to get this to work for mobile too?</p> | 0 |
android-app link not working | <p>I'm following this example from Google I/O 2015.<br>
Demo webite: <a href="http://recipe-app.com/recipe/grilled-potato-salad" rel="noreferrer">http://recipe-app.com/recipe/grilled-potato-salad</a>
Demo app: <a href="http://search-codelabs.appspot.com/codelabs/android-deep-linking" rel="noreferrer">http://search-codelabs.appspot.com/codelabs/android-deep-linking</a></p>
<p>My test:<br>
I've installed the demo app from above link.
I did a Google search using Google Search app for "grilled potato salad" and found <a href="http://recipe-app.com/recipe/grilled-potato-salad" rel="noreferrer">http://recipe-app.com/recipe/grilled-potato-salad</a>.<br>
I would expect clicking on the link would open the app directly, not the disambiguation dialog (<a href="http://search-codelabs.appspot.com/img/android-deep-linking/img-5.png" rel="noreferrer">http://search-codelabs.appspot.com/img/android-deep-linking/img-5.png</a>).
However, the disambiguation dialog still shows to my surprise.</p>
<p>Isn't the <code><link rel="alternate" href="android-app://com.recipe_app/http/recipe-app.com/recipe/grilled-potato-salad" /></code> on the website useless then? </p>
<p>The app's manifest file:<br>
```
</p>
<pre><code><uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/CustomActionBarTheme" >
<activity
android:name=".client.HomeActivity"
android:label="@string/app_name"
android:exported="true"
android:theme="@android:style/Theme.Holo.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".client.RecipeActivity"
android:label="@string/app_name"
android:exported="true"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Holo.NoActionBar">
<intent-filter android:label="@string/app_name">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://recipe-app.com/recipe" -->
<data android:scheme="http"
android:host="recipe-app.com"
android:pathPrefix="/recipe" />
</intent-filter>
</activity>
<provider
android:name=".client.content_provider.RecipeContentProvider"
android:authorities="com.recipe_app" >
</provider>
</application>
</code></pre>
<p>
```</p> | 0 |
Why is shared_ptr<void> legal, while unique_ptr<void> is ill-formed? | <p>The question really fits in the title: I am curious to know what is the technical reason for this difference, but also the rationale ?</p>
<pre><code>std::shared_ptr<void> sharedToVoid; // legal;
std::unique_ptr<void> uniqueToVoid; // ill-formed;
</code></pre> | 0 |
Injecting Dependency programmatically asp.net core | <p>I'm just starting with <code>Asp.net core</code> <em>Dependency Injection</em>, and my concept could be inaccurate. <a href="https://docs.asp.net/en/latest/mvc/controllers/dependency-injection.html" rel="nofollow noreferrer">This docs.asp.net post</a> explains how to inject context to a controller. I have little confusion regarding injection, in testing perspective. Assume we have following scenario:</p>
<pre><code>public interface ITasksRepository
{
public void Create();
}
//This is fake implementation, using fake DbContext for testing purpose
public class TasksRepositoryFake : ITasksRepository
{
public void Create()
{
FakeDbContext.Add(sometask);
//logic;
}
}
//This is actual implementation, using actual DbContext
public class TasksRepository : ITasksRepository
{
public void Create()
{
DbContext.Add(someTask);
//logic;
}
}
</code></pre>
<p>Now in order to inject context in controller, we design it as:</p>
<pre><code>public class TasksController : Controller
{
public ITasksRepository TaskItems { get; set; }
public TodoController(ITaskRepository taskItems)
{
TaskItems = taskItems;
}
//other logic
}
</code></pre>
<p>What asp.net <code>core</code> provides as builtin feature is, we can register the dependency injection in startup class as follows:</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<ITasksRepository, TasksRepositoryFake>();
}
</code></pre>
<p>According to this logic, my <code>TaskRepositoryFake</code> will be injected to the controller. So far, everything is clear. My questions/confusions regarding this are as follows:</p>
<p><strong>Questions:</strong></p>
<ul>
<li>How can I use this builtin DI feature to inject the context using some logic? May be programatically, or configuration based, or environment based? <em>(for example, always inject fake context, when using 'test' environment? etc.)</em></li>
<li>Is it even possible? If we always have to change this manually in <em>StartUp</em> class, then how does this builtin DI feature serve us? Because we could have simply done that in controller, without this feature.</li>
</ul> | 0 |
How to add dynamically attribute in VueJs | <p>I'm using vuejs and I wanna know how to have control on inputs (add disabled attribute when necessary). Is there any way to add dynamically attribute in vuejs ? Below my <strong>Textfield component</strong> : </p>
<pre><code> <template>
<input type="text" placeholder="{{ placeholder }}" v-model="value">
</template>
<script>
export default {
props: {
disabled: {type: Boolean, default: false},
placeholder: {type: String, default: ""},
value: {twoWay: true, default: ""}
}
}
</script>
</code></pre>
<p><strong>Usage</strong> :</p>
<pre><code><textfield placeholder="Name" value.sync="el.name" :disabled="true"></textfield>
</code></pre> | 0 |
where datediff < 15 from today in query builder laravel | <p>I have field in my table product like this</p>
<pre><code>--exp_date--
2016-08-02
2016-08-28
2016-08-28
2016-08-23
2016-08-15
2016-08-05
2016-08-20
</code></pre>
<p><code>exp_date</code> already in <code>date</code> format in mysql<br>
I want to <code>select</code> data which date remaining <code>exp_date</code> less than 15 from today</p>
<p>i aleady try something like this</p>
<pre><code>$dn = date('Y-m-d'); //today date
$query = DB::table('product')->where(DB::raw('datediff(exp_date), $dn') < 15)->get();
</code></pre>
<p>but i get this error <br> <code>Object of class Illuminate\Database\Query\Expression could not be converted to int</code></p>
<p>how to fix it?</p>
<p>ps:<br>i used laravel 4.2 and prefer it's by query builder or raw query</p> | 0 |
Where to see the xml file after "adb shell uiautomator dump view.xml" | <p>I use command</p>
<pre><code>adb shell uiautomator dump view.xml
</code></pre>
<p>to dump the UI hierarchy of current Android screen. Then, I try to see the <strong>view.xml</strong>, I tried command:</p>
<pre><code>adb shell cat view.xml
</code></pre>
<p>but get error:</p>
<pre><code>/system/bin/sh: cat: view.xml: No such file or directory
</code></pre>
<p>How/Where can I see the dumped view.xml file?</p> | 0 |
requires a peer of grunt@>=0.4.0 | <p>Why do I get the error below? My grunt version is > v0.4.0</p>
<pre><code>npm install grunt-contrib-concat --save-dev
</code></pre>
<blockquote>
<p>+-- UNMET PEER DEPENDENCY grunt@>=0.4.0</p>
</blockquote>
<p>Error messages: </p>
<blockquote>
<p>..Projects\Hartz\Hartz>npm install grunt-contrib-concat --save-dev
[email protected] C:..\Projects\Hartz\Hartz
+-- UNMET PEER DEPENDENCY grunt@>=0.4.0 `-- [email protected]</p>
<p>npm WARN [email protected] requires a peer of grunt@>=0.4.0
but none was installed. npm WARN [email protected] requires a
peer of grunt@>=0.4.0 but none was installed. npm WARN [email protected] No
repository field.</p>
</blockquote>
<p>grunt -V </p>
<blockquote>
<p>grunt-cli v1.2.0 <br>grunt v1.0.1</p>
</blockquote> | 0 |
How to disable the div tag in angular 2 | <p>I am trying to disable the div tag after a success callback of that action. </p>
<p>please look my ion-content</p>
<pre><code><ion-content padding class="forgot-password">
<div [ngClass]="{active: isOn,disabled: isDisabled}">
<ion-item>
<ion-label floating>Email/Mobile</ion-label>
<ion-input type="text" [(ngModel)]="loginId"></ion-input>
</ion-item> <br><br>
<button class="float-right" (click)="generateOTP(!isOn);">Send OTP</button><br><br><br>
</div>
<br>
<div *ngIf="showRePasswd">
<ion-item>
<ion-label floating>Enter OTP</ion-label>
<ion-input type="text" [(ngModel)]="passwd"></ion-input>
</ion-item> <br><br>
<button class="float-right" (click)="resetPassword();">Send Password</button>
</div>
</ion-content>
</code></pre>
<p>here is my .ts file</p>
<pre><code>export class ForgotPasswordPage {
public loginId = "";
public passwd = "";
public showRePasswd = false;
isDisabled = false;
isOn = false;
constructor(private navCtrl: NavController, private logger: Logger, private user: Users) {
}
generateOTP(newstate) {
this.logger.info("invoking generateOTP FN");
var _this = this;
this.user.generateOTP(this.loginId, function(result,data){
if(result == '1') {
alert(data);
_this.showRePasswd = !_this.showRePasswd;
_this.isDisabled = true;
_this.isOn = newstate;
}
else {
//this.showRePasswd = this.showRePasswd;
alert(data);
}
})
}
resetPassword() {
this.logger.info("invoking resetPassword FN");
var _this = this;
this.user.resetPassword(this.passwd, function(result,data) {
if(result == '1') {
alert(data);
_this.navCtrl.push(LoginPage);
}
else {
alert(data);
}
})
}
}
</code></pre>
<blockquote>
<p>I tried <code>[ngClass]</code> but i am not able to make my div tag disable after the success callback.</p>
</blockquote>
<p>I also tried using <code>[disabled]</code> but not working</p>
<p>Here is a <a href="http://plnkr.co/edit/a4YdtmWywhJ33uqfpPPn?p=preview" rel="noreferrer">demo</a> for disable a div tag but in my case not working</p>
<blockquote>
<p>My requirement is to make my input field and button to be disabled after success callback</p>
</blockquote> | 0 |
How can I set the default position of a trackbar in OpenCV? | <p>In OpenCV, using the createTrackbar function, how can someone set the default slider position to a maximum?</p>
<p>I have several sliders, some representing minimum values, and some representing maximum values. It would be nice, if the sliders for a max value, started out at the maximum (255), rather than the minimum (0). </p>
<p>I have looked around on the <a href="http://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html" rel="noreferrer">OpenCV documentation pages</a>, but I have not located a solution.</p>
<pre><code>import cv2
import numpy as np
def nothing(x):
pass
# Create a black image, a window
#img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')
cv2.namedWindow('hsv')
cv2.namedWindow('masq')
cap = cv2.VideoCapture(0)
# create trackbars for color change
cv2.createTrackbar('R-low','image',0,255,nothing)
cv2.createTrackbar('R-high','image',0,255,nothing)
cv2.createTrackbar('G-low','image',0,255,nothing)
cv2.createTrackbar('G-high','image',0,255,nothing)
cv2.createTrackbar('B-low','image',0,255,nothing)
cv2.createTrackbar('B-high','image',0,255,nothing)
while(1):
ret, img = cap.read()
# Convert BGR to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# get current positions of four trackbars
rl = cv2.getTrackbarPos('R-low','image')
rh = cv2.getTrackbarPos('R-high','image')
gl = cv2.getTrackbarPos('G-low','image')
gh = cv2.getTrackbarPos('G-high','image')
bl = cv2.getTrackbarPos('B-low','image')
bh = cv2.getTrackbarPos('B-high','image')
lower = np.array([rl,gl,bl])
upper = np.array([rh,gh,bh])
print(rl)
img[:] = [bl,gl,rl]
# Threshold the HSV image to get only certain colors
mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(img,img, mask= mask)
cv2.imshow('image',img)
cv2.imshow('masq',mask)
cv2.imshow('hsv',hsv)
cv2.destroyAllWindows()
</code></pre>
<p>On load, it ends up looking like this:</p>
<p><a href="https://i.stack.imgur.com/6psbg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6psbg.png" alt="enter image description here"></a></p> | 0 |
How to uninstall Nagios and NRPE | <p>Can you tell me how can i uninstall nagios and NRPE.
I have tried this command to uninstall NRPE:</p>
<pre><code>sudo apt-get remove nagios-nrpe-server
</code></pre>
<p>but when I execute this command it's display to me the version of Nrpe installed</p>
<pre><code>./check_nrpe -H localhost
</code></pre>
<p>Thank you in advance </p> | 0 |
FreeRadius / Daloradius: Database connection error & extension not found | <p>I installed FreeRadius and the Webinterface Daloradius.
Unfortunately I'm not able to log in to <a href="http://radiusip/daloradius" rel="nofollow noreferrer">http://radiusip/daloradius</a>.</p>
<p>I always receive the error message:</p>
<p>Database connection error
Error Message: DB Error: extension not found</p>
<p>The Log always writes this, when I quit the Debugging (FreeRadius -X):</p>
<pre><code>tail -f /var/log/mysql/error.log:
2016-08-26T10:33:54.070388Z 444 [Note] Aborted connection 444 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.070498Z 443 [Note] Aborted connection 443 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.070613Z 442 [Note] Aborted connection 442 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.070677Z 441 [Note] Aborted connection 441 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.070788Z 440 [Note] Aborted connection 440 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.070979Z 439 [Note] Aborted connection 439 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.071049Z 438 [Note] Aborted connection 438 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.071159Z 437 [Note] Aborted connection 437 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.071274Z 436 [Note] Aborted connection 436 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
2016-08-26T10:33:54.071306Z 455 [Note] Aborted connection 455 to db: 'radius' user: 'freeradius' host: 'localhost' (Got an error reading communication packets)
</code></pre>
<p>The Password is 100 % Correct in all necessary Config-Files, I deactived the Firewall. I think it has to do with not properly closing connections and/or wrong permissions.</p>
<p>The Permissions from The MySql-User are:</p>
<pre><code>mysql> show grants;
+----------------------------------------------------------------+
| Grants for freeradius@localhost |
+----------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'freeradius'@'localhost' |
| GRANT ALL PRIVILEGES ON `radius`.* TO 'freeradius'@'localhost' |
+----------------------------------------------------------------+
2 rows in set (0.00 sec)
</code></pre>
<p>Any Ideas?</p>
<p>It is Ubuntu 16.04, Daloradius 0909 and FreeRadius V3</p> | 0 |
Examples of Kafka Rest | <p>Are there any good examples of the producer and consumer groups using the Kafka rest api in Java. Im not looking for simpleconsumer or kafka client examples of the producer and consumer. Any help is apprreciated.</p> | 0 |
Laravel Query builder and table names | <p>I noticed that I write the database table names quite a lot, and in different files, when I use the Query Builder. If I were to change the database table names, I would have to search and change quite many rows in my project.
Is this an issue your Laravel guys noticed and come up with an solution to?</p>
<p>I like the Eloquent approach which uses class models, instead of database names; but for some queries I think the Query Builder is a better solution (though I am no expert in this matter).</p> | 0 |
Access AWS API Gateway with IAM roles from Python | <p>I have an AWS API Gateway that I would like to secure using <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html" rel="noreferrer" title="IAM Roles">IAM Roles</a> .</p>
<p>I am looking for a package to help me accessing it using Python. I am trying to avoid implementing the entire <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html" rel="noreferrer" title="Version 4 Signing Process">Version 4 Signing Process</a>. I am sure there must be some library I can use.</p>
<p>I looked into <a href="https://github.com/DavidMuller/aws-requests-auth" rel="noreferrer" title="aws-requests-auth">aws-requests-auth</a> but it requires a "aws_service" to generate the signature. I looked also to boto3 but I am not able to find any way to just add authentication headers to a general request.</p> | 0 |
Deep Merge using Lodash | <p>I have two arrays of objects that contain addresses that have a label and an object for the actual address:</p>
<pre><code>var originalAddresses = [
{
label: 'home',
address: { city: 'London', zipCode: '12345' }
},
{
label: 'work',
address: { city: 'New York', zipCode: '54321' }
}
];
var updatedAddresses = [
{
label: 'home',
address: { city: 'London (Central)', country: 'UK' }
},
{
label: 'spain',
address: { city: 'Madrid', zipCode: '55555' }
}
];
</code></pre>
<p>Now I want to merge these arrays by <code>label</code> and compare the individual properties of the addresses and merge only the properties from the new address that are actually present. So the result should look like this:</p>
<pre><code>var result = [
{
label: 'home',
address: { city: 'London (Central)', zipCode: '12345', country: 'UK' }
},
{
label: 'work',
address: { city: 'New York', zipCode: '54321' }
},
{
label: 'spain',
address: { city: 'Madrid', zipCode: '55555' }
}
]
</code></pre>
<p><strong>How can I do this using <a href="https://lodash.com/" rel="noreferrer">lodash</a>?</strong> I tried a combination of <code>unionBy()</code> and <code>merge()</code>. With unionBy() I was able to compare and join the arrays by label, but this always replaces the whole object. I can sure merge the addresses but this doesn't happen by label then.</p> | 0 |
Upload a file to an FTP server from a string or stream | <p>I'm trying to create a file on an FTP server, but all I have is either a string or a stream of the data and the filename it should be created with. Is there a way to create the file on the server (I don't have permission to create local files) from a stream or string?</p>
<pre><code>string location = "ftp://xxx.xxx.xxx.xxx:21/TestLocation/Test.csv";
WebRequest ftpRequest = WebRequest.Create(location);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(userName, password);
string data = csv.getData();
MemoryStream stream = csv.getStream();
//Magic
using (var response = (FtpWebResponse)ftpRequest.GetResponse()) { }
</code></pre> | 0 |
Uncaught TypeError: this.state.data.map is not a function | <p>I am new to React, have seen some of the similar issues, but didn’t find why this happens. I am getting an “Uncaught TypeError: this.state.data.map is not a function”.
Here is the code. Please, help to find what is the problem.</p>
<pre><code>class Audienses extends React.Component {
constructor (props)
{
super(props);
this.state = {
data: ''
};
this.loadFromServer = this.loadFromServer.bind(this);
this.childeDelete = this.childeDelete.bind(this);
this.childeEdit = this.childeEdit.bind(this);
}
loadFromServer () {
var xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
this.setState({ data: data });
}.bind(this);
xhr.send();
}
componentDidMount() {
this.loadFromServer();
}
render () {
var audienses = this.state.data.map((value, index) => (
<OneElement key={value.id} audience={value.audience} description={value.description} />
));
/* or like this
var audienses = this.state.data.map(function(s) {
<OneElement key={s.id} audience={s.audience} description={s.description} onDeleteClick={this.childeDelete} oneEditClick={this.childeEdit} />
}).bind(this);
*/
return
<div>
<h1>Audiences</h1>
<table id="services">
<tr>
<th>Audience</th>
<th>Description</th>
<th></th>
<th></th>
</tr>
<tbody>
{audienses}
</tbody>
</table>
</div>;
}
}
</code></pre> | 0 |
ASP.NET Core Web API Authentication | <p>I'm struggling with how to set up authentication in my web service.
The service is build with the ASP.NET Core web api.</p>
<p>All my clients (WPF applications) should use the same credentials to call the web service operations. </p>
<p>After some research, I came up with basic authentication - sending a username and password in the header of the HTTP request.
But after hours of research, it seems to me that basic authentication is not the way to go in ASP.NET Core.</p>
<p>Most of the resources I found are implementing authentication using OAuth or some other middleware. But that seems to be oversized for my scenario, as well as using the Identity part of ASP.NET Core. </p>
<p>So what is the right way to achieve my goal - simple authentication with username and password in a ASP.NET Core web service?</p>
<p>Thanks in advance!</p> | 0 |
How can i convert my CAD(DWG) file to GeoJSON? | <p>I'm working on openlayers and need to change the format of dwg to GeoJSON with ArcGIS.
how can i do this?</p> | 0 |
Looking for Elasticsearch updateByQuery syntax example (Node driver) | <p>You have an Elasticsearch index with two docs:</p>
<pre><code>[
{
"_index": "myIndex",
"_type": "myType",
"_id": "es1472002807930",
"_source": {
"animal": "turtle",
"color": "green",
"weight": 20,
}
},
{
"_index": "myIndex",
"_type": "myType",
"_id": "es1472002809463",
"_source": {
"animal": "bear",
"color": "brown"
"weight": 400,
}
}
]
</code></pre>
<p>Later, you get this updated data about the bear:</p>
<pre><code>{
"color": "pink",
"weight": 500,
"diet": "omnivore",
}
</code></pre>
<p>So, you want to update the "color" and "weight" values of the bear, and add the "diet" key to the "bear" doc. You know there's only one doc with <code>"animal": "bear"</code> (but you don't know the _id):</p>
<p>Using the Nodejs driver, what updateByQuery syntax would update the "bear" doc with these new values?</p>
<p><strong>(NOTE: this question has been entirely edited to be more useful to the SO community!)</strong></p> | 0 |
How to work with ellipsis in bootstrap responsive table | <p>In a responsive table <code>text-overflow:ellipsis</code> is not working when the data increases in the <code>th</code> (as the <code>col-xs-2</code> width increases). </p>
<p><a href="https://i.stack.imgur.com/ES07c.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ES07c.png" alt="enter image description here"></a></p>
<p>Code below:</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-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="col-xs-2" style="text-overflow: ellipsis;">Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum</th>
<th class="col-xs-1">Firstname</th>
<th class="col-xs-1"> Lastname</th>
<th class="col-xs-4">Age</th>
<th class="col-xs-2">City</th>
<th class="col-xs-2">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Anna</td>
<td>Pitt</td>
<td>35</td>
<td>New York</td>
<td>USA</td>
</tr>
</tbody>
</table>
</div></code></pre>
</div>
</div>
</p> | 0 |
Convert img tag to display FontAwesome icon | <p>I have a third party product which outputs an icon via an <code><img></code> tag with a background-image set via css.</p>
<p>I could probably write some javascript to change the html tag itself to something different but I would rather change the css to display a FontAwesome icon using the <code>:before</code> and <code>content="{FontAwesomeText}"</code>. </p>
<p>However, I cant get this to work...does someone know if this is possible to do this?</p>
<p>Please see </p>
<pre><code>.x-tree-icon-leaf:before {
content: "";
font-size: 0.6em;
position: relative;
top: -3px;
}
.x-tree-icon-leaf {
font-family: FontAwesome;
width: 20px;
height: 20px;
display: inline-block;
color: #5fa2dd;
}
</code></pre>
<p><a href="https://jsfiddle.net/uz9q6m33/" rel="nofollow">https://jsfiddle.net/uz9q6m33/</a></p> | 0 |
Set WTForms submit button to icon | <p>I want a submit button that displays an icon rather than text. The button is a field in a WTForms form. I am using Bootstrap and Open Iconic for styling and icons. How do I set the submit field to display an icon?</p>
<pre><code>class MyForm(Form):
submit = SubmitField('')
</code></pre>
<pre><code>{{ form.submit }}
</code></pre>
<p><a href="https://stackoverflow.com/questions/30668029/creating-a-form-with-a-varying-number-of-repeated-subform-in-flask-wtforms">This post</a> refers to an <code>icon</code> method, but I can't find any more information on it.</p> | 0 |
How to center bootstrap checkbox form | <p><a href="http://i.stack.imgur.com/0kQaC.png" rel="nofollow">I need to center this checkboxes</a>
Could anybody help me center this checkboxes? i've try so many things already.</p>
<p>here's my code:</p>
<pre><code> <div class="row checkbox-row">
<div class="col-sm-6">
<div class="checkbox-inline">
<label class="checkbox-inline"><input type="checkbox" value="">Adult News</label>
</div>
</div>
<div class="row checkbox-row">
<div class="col-sm-6">
<div class="checkbox-inline">
<label class="checkbox-inline"><input type="checkbox" value="">Youth News</label>
</div>
</div>
</div>
</div>
</code></pre> | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.