text
stringlengths
64
89.7k
meta
dict
Q: sqlite database resets on each compile and run I have built up a basic database application in which user can insert records onto a table and app displays them on a TableView. Everything is working as it is supposed to be. For example, the new records do display even if we kill the app from app switcher and relaunch it from the springboard. BUT every time I build and run using Xcode, the database just goes to default records! The new records are just not there. Is it normal?... but what if I want to test my app for new records? Any fix? BTW, JFYI, below is the code I use to make editable DB. -(NSString *)createEditableDatabase{ // Check if DB already exists BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; NSString *writableDB = [documentsDir stringByAppendingPathComponent:@"Database.db"]; success = [fileManager fileExistsAtPath:writableDB]; //The editable DB already exists if (success) { return writableDB; } //The editable DB does not exist //Copy the default DB into App's Doc Dir. NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Database.db"]; success = [fileManager copyItemAtPath:defaultPath toPath:writableDB error:&error]; if (!success) { NSAssert1(0, @"Failed to create writable DB file: '%@'", [error localizedDescription]); } return writableDB; } A: While digging deeper, I noticed that the database modify date in finder was not updating when I inserted a record. So, I found out that I was still using old path to perform DB operations (not the Documents one). :) Now everything working fine. Anyways thanks Nick
{ "pile_set_name": "StackExchange" }
Q: Python + webkit + gtk on windows I am trying to do this script: PY WYSIWYG And it says I need Gtk and WebKit. I think this is what I need: Gtk WebKit So I downloaded WebKit but I got a folder instead of an installer or install information. Do I move it into the python folder or what do I do? A: You need PyGTK, here is a link to the download page with install instructions for Windows: http://www.pygtk.org/downloads.html You also need the Python bindings for Webkit, not just Webkit itself. Here is a link to an unofficial Windows binary, with install instructions, and a link to an unofficial Webkit runtime for Windows near the bottom too: http://opensourcepack.blogspot.com/2009/12/pywebkitgtk-windows-binary.html A: There is automated installer of (mostly) GTK libraries Python. It should have dependencies solved. It is unofficial. It contains webkit. I found it because I wanted webkit installer for Python. I tried it and it worked like charm. List of all plugins contained inside of it: PyGTK 2.17.0 with numpy support PyGobject 2.21.5 PyCairo 1.8.10 PyGtkspell, PyGTKhtml2, PyGDL 2.25.3 PyGDA 2.29.1 PyGST (Python Gstreamer) 0.10.20 PyWebkitGTK 1.18 PyClutter 1.3.2 with gst and gtk binding PyGTKGlExt 1.1.0 PyGoocanvas 0.14.1 PyGTKSourceview 2.10.0 PyGTKImageview 1.2.0 PyRSVG 2.30 PyScintilla 1.99 PMing 4.4 Python Poppler 0.12 GPL VIPSCC 7.24 PS: I actually had problem with other tutorial on webgui in Python mentioned here, then I found this page and Your tutorial worked. Thanks. :)
{ "pile_set_name": "StackExchange" }
Q: End note reference not in superscript For an article I write, I am using the endnotes package – I am a newbie and I cannot achieve the following: how to have reference in text like mytext [1] instead of mytext1 Here is my code: \documentclass[]{jacow} \begin{document} \section{Rationale}\label{rationale} Over the last 26 years, \emph{mytext}\endnote{\url{http://dummylink.com}} has been the main system we used. \end I have no idea what to change. Looking on the web I successfully changed the reference in the final notes section to have the square brackets: \patchcmd{\theendnotes} {\makeatletter} {\makeatletter\renewcommand\makeenmark{[\theenmark] }} {}{} I would like to do the same for the reference in text itself. A: If you only put \renewcommand\makeenmark{[\theenmark] } in your preamble (without the \patchcmd business) then every mark will be changed: \documentclass{article} \usepackage{endnotes,etoolbox} % the mark everywhere: \renewcommand\makeenmark{[\theenmark]} % the mark in the list of endnotes -- we need an extra space: \patchcmd{\theendnotes} {\makeatletter} {\makeatletter\renewcommand\makeenmark{[\theenmark] }}% notice the space! {}{} \begin{document} Text\endnote{bla} text \theendnotes \end{document}
{ "pile_set_name": "StackExchange" }
Q: Error linking libxxx.so in Native Client (NaCl) I am struggling to link libIrrlicht.so file with my example source files. Here is my makefile PROJECT:=testirrlicht LDFLAGS:=-lppapi_gles2 -lppapi_cpp -Iinclude -lppapi libs/libIrrlicht.so CXX_SOURCES:=testirrlicht.cc   THIS_MAKEFILE:=$(abspath $(lastword $(MAKEFILE_LIST))) NACL_SDK_ROOT?=$(abspath $(dir $(THIS_MAKEFILE))../..)   CXXFLAGS:=-pthread -g -Wall -Werror -I./include -D_IRR_STATIC_LIB_ -fabi-version=1   OSNAME:=win TC_PATH:=$(abspath $(NACL_SDK_ROOT)/toolchain/$(OSNAME)_x86_newlib) CXX:=$(TC_PATH)/bin/i686-nacl-g++   CYGWIN ?= nodosfilewarning export CYGWIN   all: $(PROJECT)_x86_32.nexe $(PROJECT)_x86_64.nexe   # Define 32 bit compile and link rules for C++ sources x86_32_OBJS:=$(patsubst %.cc,%_32.o,$(CXX_SOURCES)) $(x86_32_OBJS) : %_32.o : %.cc $(THIS_MAKE)         $(CXX) -o $@ -c $< -m32 -O0 -g $(CXXFLAGS)   $(PROJECT)_x86_32.nexe : $(x86_32_OBJS)         $(CXX) -o $@ $^ -m32 -O0 -g $(CXXFLAGS) $(LDFLAGS)   # Define 64 bit compile and link rules for C++ sources x86_64_OBJS:=$(patsubst %.cc,%_64.o,$(CXX_SOURCES)) $(x86_64_OBJS) : %_64.o : %.cc $(THIS_MAKE)         $(CXX) -o $@ -c $< -m64 -O0 -g $(CXXFLAGS)   $(PROJECT)_x86_64.nexe : $(x86_64_OBJS)         $(CXX) -o $@ $^ -m64 -O0 -g $(CXXFLAGS) $(LDFLAGS)     # Define a phony rule so it always runs, to build nexe and start up server. .PHONY: RUN RUN: all         python ../httpd.py Here is my compilation error: $ make /cygdrive/d/naclsdk/pepper_18/toolchain/win_x86_newlib/bin/i686-nacl-g++ -o testirrlicht_x86_3.nexe testirrlicht_32.o -m32 -O0 -g -pthread -g -Wall -Werror -I./include -D_IRR_STATIC_LIB_ -abi-version=1 -lppapi_gles2 -lppapi_cpp -Iinclude -lppapi libs/libIrrlicht.so /x86_64-nacl-ld: warning: libstdc++.so.6, needed by libs/libIrrlicht.so, not found (try using rpath or -rpath-link) /x86_64-nacl-ld: warning: libm.so.3c8d1f2e, needed by libs/libIrrlicht.so, not found (try usin -rpath or -rpath-link) /x86_64-nacl-ld: warning: libgcc_s.so.1, needed by libs/libIrrlicht.so, not found (try using -path or -rpath-link) /x86_64-nacl-ld: warning: libpthread.so.3c8d1f2e, needed by libs/libIrrlicht.so, not found (tr using -rpath or -rpath-link) /x86_64-nacl-ld: warning: libc.so.3c8d1f2e, needed by libs/libIrrlicht.so, not found (try usin -rpath or -rpath-link) libs/libIrrlicht.so: undefined reference to `wcscpy@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glAttachShader' libs/libIrrlicht.so: undefined reference to `operator new[](unsigned int)@GLIBCXX_3.4' libs/libIrrlicht.so: undefined reference to `glEnable' libs/libIrrlicht.so: undefined reference to `glBindAttribLocation' libs/libIrrlicht.so: undefined reference to `glHint' libs/libIrrlicht.so: undefined reference to `glLineWidth' libs/libIrrlicht.so: undefined reference to `wcslen@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `asin@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glIsEnabled' libs/libIrrlicht.so: undefined reference to `glGetShaderiv' libs/libIrrlicht.so: undefined reference to `memset@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glFrontFace' libs/libIrrlicht.so: undefined reference to `glGetActiveUniform' libs/libIrrlicht.so: undefined reference to `glBindRenderbuffer' libs/libIrrlicht.so: undefined reference to `glDisable' libs/libIrrlicht.so: undefined reference to `operator delete(void*)@GLIBCXX_3.4' libs/libIrrlicht.so: undefined reference to `glTexParameterf' libs/libIrrlicht.so: undefined reference to `glClear' libs/libIrrlicht.so: undefined reference to `gmtime@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glFramebufferTexture2D' libs/libIrrlicht.so: undefined reference to `__cxa_guard_release@CXXABI_1.3' libs/libIrrlicht.so: undefined reference to `strncpy@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `swprintf@GLIBC_2.2' libs/libIrrlicht.so: undefined reference to `glGetError' libs/libIrrlicht.so: undefined reference to `glUniform4iv' libs/libIrrlicht.so: undefined reference to `mbstowcs@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `strtod@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glStencilFunc' libs/libIrrlicht.so: undefined reference to `eglInitialize' libs/libIrrlicht.so: undefined reference to `fmod@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glStencilMask' libs/libIrrlicht.so: undefined reference to `glGetAttachedShaders' libs/libIrrlicht.so: undefined reference to `sscanf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glDisableVertexAttribArray' libs/libIrrlicht.so: undefined reference to `glDeleteProgram' libs/libIrrlicht.so: undefined reference to `glGenRenderbuffers' libs/libIrrlicht.so: undefined reference to `__cxa_guard_acquire@CXXABI_1.3' libs/libIrrlicht.so: undefined reference to `glUniformMatrix4fv' libs/libIrrlicht.so: undefined reference to `glUseProgram' libs/libIrrlicht.so: undefined reference to `glClearColor' libs/libIrrlicht.so: undefined reference to `glUniformMatrix3fv' libs/libIrrlicht.so: undefined reference to `strcmp@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glUniform1iv' libs/libIrrlicht.so: undefined reference to `sin@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `longjmp@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglCreateContext' libs/libIrrlicht.so: undefined reference to `localtime@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `ftell@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `sinf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglMakeCurrent' libs/libIrrlicht.so: undefined reference to `glDeleteBuffers' libs/libIrrlicht.so: undefined reference to `glReadPixels' libs/libIrrlicht.so: undefined reference to `glDeleteShader' libs/libIrrlicht.so: undefined reference to `_setjmp@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglQueryString' libs/libIrrlicht.so: undefined reference to `glCheckFramebufferStatus' libs/libIrrlicht.so: undefined reference to `strtoul@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `puts@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glEnableVertexAttribArray' libs/libIrrlicht.so: undefined reference to `glGenFramebuffers' libs/libIrrlicht.so: undefined reference to `glActiveTexture' libs/libIrrlicht.so: undefined reference to `glBufferData' libs/libIrrlicht.so: undefined reference to `acosf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `atol@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glColorMask' libs/libIrrlicht.so: undefined reference to `ferror@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglSwapBuffers' libs/libIrrlicht.so: undefined reference to `floorf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glBlendFunc' libs/libIrrlicht.so: undefined reference to `glDetachShader' libs/libIrrlicht.so: undefined reference to `tan@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGetProgramInfoLog' libs/libIrrlicht.so: undefined reference to `acos@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glCopyTexSubImage2D' libs/libIrrlicht.so: undefined reference to `fwrite@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `getenv@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `fseek@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glBindTexture' libs/libIrrlicht.so: undefined reference to `glRenderbufferStorage' libs/libIrrlicht.so: undefined reference to `fputc@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGetProgramiv' libs/libIrrlicht.so: undefined reference to `glDepthMask' libs/libIrrlicht.so: undefined reference to `malloc@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glStencilOp' libs/libIrrlicht.so: undefined reference to `strstr@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `cosf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `printf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glCreateShader' libs/libIrrlicht.so: undefined reference to `glDeleteTextures' libs/libIrrlicht.so: undefined reference to `strncmp@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGenerateMipmap' libs/libIrrlicht.so: undefined reference to `glBlendEquation' libs/libIrrlicht.so: undefined reference to `glBufferSubData' libs/libIrrlicht.so: undefined reference to `glCullFace' libs/libIrrlicht.so: undefined reference to `glCreateProgram' libs/libIrrlicht.so: undefined reference to `fflush@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `fread@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `stderr@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `memcpy@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glPixelStorei' libs/libIrrlicht.so: undefined reference to `glGetIntegerv' libs/libIrrlicht.so: undefined reference to `strlen@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGenBuffers' libs/libIrrlicht.so: undefined reference to `operator delete[](void*)@GLIBCXX_3.4' libs/libIrrlicht.so: undefined reference to `__errno_location@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `atan2f@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `atan2@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glDrawElements' libs/libIrrlicht.so: undefined reference to `glDeleteFramebuffers' libs/libIrrlicht.so: undefined reference to `glFramebufferRenderbuffer' libs/libIrrlicht.so: undefined reference to `cos@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglSwapInterval' libs/libIrrlicht.so: undefined reference to `glUniformMatrix2fv' libs/libIrrlicht.so: undefined reference to `glTexImage2D' libs/libIrrlicht.so: undefined reference to `eglGetError' libs/libIrrlicht.so: undefined reference to `pow@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glUniform2iv' libs/libIrrlicht.so: undefined reference to `glDepthFunc' libs/libIrrlicht.so: undefined reference to `memcmp@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `fopen@GLIBC_2.1' libs/libIrrlicht.so: undefined reference to `glDrawArrays' libs/libIrrlicht.so: undefined reference to `fmodf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glDeleteRenderbuffers' libs/libIrrlicht.so: undefined reference to `glClearDepthf' libs/libIrrlicht.so: undefined reference to `glScissor' libs/libIrrlicht.so: undefined reference to `time@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `fprintf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `atof@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glTexSubImage2D' libs/libIrrlicht.so: undefined reference to `powf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glVertexAttribPointer' libs/libIrrlicht.so: undefined reference to `atoi@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGetBooleanv' libs/libIrrlicht.so: undefined reference to `strcpy@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `wcscmp@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `memmove@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGetString' libs/libIrrlicht.so: undefined reference to `glBindBuffer' libs/libIrrlicht.so: undefined reference to `__assert_fail@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glPolygonOffset' libs/libIrrlicht.so: undefined reference to `glBindFramebuffer' libs/libIrrlicht.so: undefined reference to `glLinkProgram' libs/libIrrlicht.so: undefined reference to `glUniform3iv' libs/libIrrlicht.so: undefined reference to `abort@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glUniform1fv' libs/libIrrlicht.so: undefined reference to `glGetShaderInfoLog' libs/libIrrlicht.so: undefined reference to `__cxa_pure_virtual@CXXABI_1.3' libs/libIrrlicht.so: undefined reference to `sprintf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glUniform2fv' libs/libIrrlicht.so: undefined reference to `glShaderSource' libs/libIrrlicht.so: undefined reference to `__cxa_atexit@GLIBC_2.1.3' libs/libIrrlicht.so: undefined reference to `exit@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `snprintf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglBindAPI' libs/libIrrlicht.so: undefined reference to `operator new(unsigned int)@GLIBCXX_3.4' libs/libIrrlicht.so: undefined reference to `glViewport' libs/libIrrlicht.so: undefined reference to `glUniform3fv' libs/libIrrlicht.so: undefined reference to `gettimeofday@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glUniform4fv' libs/libIrrlicht.so: undefined reference to `eglGetDisplay' libs/libIrrlicht.so: undefined reference to `eglTerminate' libs/libIrrlicht.so: undefined reference to `glGetUniformLocation' libs/libIrrlicht.so: undefined reference to `glTexParameteri' libs/libIrrlicht.so: undefined reference to `eglCreateWindowSurface' libs/libIrrlicht.so: undefined reference to `free@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `logf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `setlocale@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `fclose@GLIBC_2.1' libs/libIrrlicht.so: undefined reference to `sqrtf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `glGenTextures' libs/libIrrlicht.so: undefined reference to `glCompileShader' libs/libIrrlicht.so: undefined reference to `ceilf@GLIBC_2.0' libs/libIrrlicht.so: undefined reference to `eglChooseConfig' libs/libIrrlicht.so: undefined reference to `sqrt@GLIBC_2.0' collect2: ld returned 1 exit status Makefile:58: recipe for target `testirrlicht_x86_32.nexe' failed make: *** [testirrlicht_x86_32.nexe] Error 1 A: Fixed the problem. I built library in glibc and the sample application using newlib. Now, I changed both to glibc and partially fixed some problem. $ make /cygdrive/d/naclsdk/pepper_18/toolchain/win_x86_glibc/bin/i686-nacl-gcc -o testirrlicht_x86_32.nexe testirrlicht_32.o -m32 -O0 -g -Wall -Iinclude -lpthread -lppapi_cpp -lppapi -lstdc++ -lgcc -lppapi_gles2 libs/libIrrlicht.so /libexec/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib32/libppapi_cpp.so: warning: warning: pthread_cancel is not implemented and will always fail libs/libIrrlicht.so: undefined reference to `eglCreateWindowSurface' libs/libIrrlicht.so: undefined reference to `eglBindAPI' libs/libIrrlicht.so: undefined reference to `eglCreateContext' libs/libIrrlicht.so: undefined reference to `eglMakeCurrent' libs/libIrrlicht.so: undefined reference to `eglGetDisplay' libs/libIrrlicht.so: undefined reference to `eglChooseConfig' libs/libIrrlicht.so: undefined reference to `eglInitialize' libs/libIrrlicht.so: undefined reference to `eglQueryString' /libexec/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib32/libppapi_cpp.so: undefined reference to `pp::CreateModule()' libs/libIrrlicht.so: undefined reference to `eglSwapInterval' libs/libIrrlicht.so: undefined reference to `eglSwapBuffers' libs/libIrrlicht.so: undefined reference to `eglGetError' libs/libIrrlicht.so: undefined reference to `eglTerminate' collect2: ld returned 1 exit status Makefile:58: recipe for target `testirrlicht_x86_32.nexe' failed make: *** [testirrlicht_x86_32.nexe] Error 1
{ "pile_set_name": "StackExchange" }
Q: xcode build failed no explanation My project has weirdly started failing with no error messages. Ive tried cleaning the project and this had no effect. I know this is all a bit vague but i havent done anything to revert or undo. its just randomly started to happen. Can anyone suggest a way of debugging what the problem is? Phil A: Have you tried clearing the derived data (Organizer->Projects / cmd + shift + 2) and then cleaning (cmd+shift+K)? Maybe closing xCode and rebooting? I've had it a few times and this worked for me sometimes.
{ "pile_set_name": "StackExchange" }
Q: Regex to remove text between / / line: bp(k) "by products" / text... / I have this line and I need a regex to remove everything between // (not //). Any ideas? I have tried: line = line.replaceAll("/.*?/", "/"+"/") but it wont work Edit: (sometimes I forget people cant read my mind :P) I need everything to be removed between / and /. Init there can be letters,',' or '_'. With the replacement I tried, it will leave the text as it is, no errors though A: .* is greedy - It's matching the closing '/' and anything else until the last '/' found in the line. Read up on regex usage, and try line = line.replaceAll("/[^/]+/", "//");
{ "pile_set_name": "StackExchange" }
Q: Simple parallelization with shared non-threadsafe resource in Scala I frequently want to parallelize a task that relies on a non-threadsafe shared resource. Consider the following non-threadsafe class. I want to do a map over a data: Vector[String]. class Processor { def apply: String => String } Basically, I want to create n threads, each with an instance of Processor and a partition of the data. Scala parallel collections have spoiled me into thinking the parallelization should be dirt simple. However, they don't seem well suited for this problem. Yes, I can use actors but Scala actors might become deprecated and Akka seems like overkill. The first thing that comes to mind is to have a synchronized map Thread -> Processor and then use parallel collections, looking up my Processor in this thread-safe map. Is there a better way? A: Instead of building your own synchronized map, you can use ThreadLocal. That will guarantee a unique Processor per thread. val processors = new ThreadLocal[Processor] { def initialValue() = new Processor } data.par.map(x => processors.get.apply(x))
{ "pile_set_name": "StackExchange" }
Q: How to post an image in base64 encoding via .ajax? I have some javascript code that uploads an image to a server. Below is the ajax call that works correctly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', type: 'POST', contentType: 'application/json', data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }', }) I now need to upload the image a a base64 encoding e.g. data: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z' But that doesn't work, i.e. the server doesn't recognise the data I send and complains. Does anyone know what the correct format is for sending base64 encoded data in the AJAX call ? A: Thanks for all the answers which helped me along. I had also posted the question to the forums on https://social.msdn.microsoft.com/Forums/en-US/807ee18d-45e5-410b-a339-c8dcb3bfa25b/testing-project-oxford-ocr-how-to-use-a-local-file-in-base64-for-example?forum=mlapi (more Project Oxford specific) and between their answers and your's I've got a solution. You need to send a Blob You need to set the processData:false and contentType: 'application/octet-stream' options in the .ajax call So my solution looks like this First a function to make the blob (This is copied verbatim from someone more gifted than I) makeblob = function (dataURL) { var BASE64_MARKER = ';base64,'; if (dataURL.indexOf(BASE64_MARKER) == -1) { var parts = dataURL.split(','); var contentType = parts[0].split(':')[1]; var raw = decodeURIComponent(parts[1]); return new Blob([raw], { type: contentType }); } var parts = dataURL.split(BASE64_MARKER); var contentType = parts[0].split(':')[1]; var raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); } and then $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/ocr?' + $.param(params), type: 'POST', processData: false, contentType: 'application/octet-stream', data: makeblob('data:image/jpeg;base64,9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z' }) .done(function(data) {alert("success");}) .fail(function() {alert("error");}); A: This is some working code from my own application. You will need to change the contentType and data args in your ajax operations. var video = that.vars.video; var code = document.createElement("canvas"); code.getContext('2d').drawImage(video, 0, 0, code.width, code.height); var img = document.createElement("img"); img.src = code.toDataURL(); $.ajax({ url: '/scan/submit', type: 'POST', data: { data: code.toDataURL(), userid: userid }, success: function (data) { if (data.error) { alert(data.error); return; } // do something here. }, error : function (r, s, e) { alert("Unexpected error:" + e); console.log(r); console.log(s); console.log(e); } });
{ "pile_set_name": "StackExchange" }
Q: Bonjour not advertising over BT I've been banging my head against this for the last week or so. I've already gone through the following resources: StackOverflow: Bonjour over bluetooth WITHOUT Gamekit ? (3844189) StackOverflow: How does Bonjour Over Bluetooth Work (3350094) StackOverflow: Using iOS GameKit's “Bluetooth Bonjour” with other platforms (8070998) Technical Q&A QA1753 -- Apple Developer WiTap sample application SRVResolver sample application DNSSDObjects sample application I'm using Mac OS 10.7, Xcode 4.5, an iPhone 4 with iOS 6, and an iPad 1 with iOS 5.1.1. My problem is this: I am modifying an application that currently uses GameKit's peer picker to connect between an iPad and a iP{hone|od touch}. We want to modify this to use Bonjour over Bluetooth instead because we've had issues with reconnecting the devices using Gamekit if the connection is lost. I've used dns_sd.h API to some success and have gotten the service to advertise and resolve over wifi, but even though I am passing kDNSServiceFlagsIncludeP2P I am not getting any success over bluetooth. I thought possibly Bluetooth Bonjour need a PAN established between devices already, but even pairing the iPad to the iMac and browsing for DNS-SD services gives me nothing...and the iPhone won't pair to the iPad anyway. A: I just finished solving this in my own app in the last 24 hours. I used the core classes from the OS X sample app DNSSDObjects. I only had to change three lines of code to add support for bluetooth. This works great in my iOS app. In DNSSDBrowser.m, the call to DNSServiceBrowse needs to have kDNSServiceFlagsIncludeP2P passed in for the 2nd parameter. In DNSSDRegister.m, the call to DNSServiceRegister needs the same change. In DNSSDService.m, the call to DNSServiceResolve also needs the same change. If you want to limit yourself to just bluetooth, and not WiFi, then the same three lines of code should be updated so the 3rd parameter is kDNSServiceInterfaceIndexP2P instead of kDNSServiceInterfaceIndexAny.
{ "pile_set_name": "StackExchange" }
Q: xmlhttprequest for local files I have the path to a file i want to send to a rest webservice the server. I am using the xmlhttprequest object. The post is as follows: var url = "http://localhost:8080/RestWSGS/jersey/gridsense"; var boundary = "--------------" + (new Date).getTime(); xmlHttp.open('POST', url, true); xmlHttp.onreadystatechange = function () { if (this.readyState != 4) return; var result =this.responseText; document.write(result); }; xmlHttp.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); var part =""; part += 'Content-Disposition: form-data; '; part += 'name="' + document.getElementById("filename").name + '" ; '; //alert(document.getElementById("filename").value); part += 'filename="'+ document.getElementById("filename").value + '";\r\n'; part += "Content-Type: application/xml"; part += "\r\n\r\n"; // marks end of the headers part part += 'filename="'+ document.getElementById("filename").value + '";\r\n'; part+= data; var request = "--" + boundary + "\r\n"; request+= part /* + "--" + boundary + "\r\n" */; request+= "--" + boundary + "--" + "\r\n"; alert(request); xmlHttp.send(request); The data i want to send is on the client local disk. I want to use the get method for it : var str = document.getElementById("filename").value; var data; var xmlhttp1 = getNewHTTPObject(); xmlhttp1.open("GET", "file:///New Folder/" +document.getElementById("filename").value , false); xmlhttp1.send(null); alert('hi' + xmlhttp1.status); xmlhttp1.onreadystatechange = function() { if (this.status == 0) { alert("resp " + this.responseText); data = this.responseText; } } The file:// does not work. If i put my file within the client directory and remove the file:/// then i can at least see xmlhttprequest open and give status 200 (i think ok!!). I read that for local file check status == 0 instead of readystatus == 4 so i did that but it still gives data variable as undefined and so the file does not go to the server. Initially when i had given the form action as my rest url it was uploading fine. Since I am not using html5 i cannot get the File object from the input type=file element. I want to use the xmlhttprequest object for this instead of the form element directly. Please help me with this problem with any suggestions or hints KAvita Even if i do the uploading using form submission how can i use the return value of the web service. Thats the reason I need to use xmlhttpRequest. If anyone can suggest how the return value from the action is used it will be great!! Kavita A: Historically, you can't query for local files from JavaScript (or shouldn't be allowed to, or something's odd). This would be a serious breach of security. There are only a few circumstances where you can do this, but in general they involve specific security settings requiring to be set for your browser, to either lift the limitation or to notify the current page's execution process that that is is granted this exceptional right. This is for instance doable in Firefox by editing the properties. It's also commonly OK when developing browser extensions (for instance for Chrome or FF) if they request the file access permissions. Another way to go around this limitation is to host a local web-server, and to declare virtual hosts on it to be able to do this sort of AJAX request to fetch local files. It's quite common for web-developers to resort to this trick (more like a standard, really) to have the benefits of local development but at the same time replicate a production system. You could for instance use a lightweight web-server like Jetty. (Another mean annoyance, that you seem to have encountered, is that some browsers - at least some relatively older FF versions, like 3.6.x - will sometimes return a positive error code like 200 when they requests are blocked according to their internal security policies. Can be pretty confusing for a while...). Finally, the newer HTML5 APIs do provide some new constructs to access local files. Considering reading: Reading Files in JavaScript using the File API Exploring the FileSystem APIs Other SO questions also provide additional pointers: Access local files from HTML5 Desktop Application in html folder Solutions to allowing intranet/local file access in an HTML5 application? A: I use an iframe. <div class="item" onclick="page(event)">HTML5</div> <iframe id="page" src=""> function page(e) { trigger = e.currentTarget.innerHTML; docname = new String(trigger + ".txt"); document.getElementById("page").src = docname; }
{ "pile_set_name": "StackExchange" }
Q: How to create downloadable link of google chart in image file In the code, I am trying to add a hyperlink below the chart. As I click it, it will take me to a new tab with a google chart image for download.Any helps? https://codepad.remoteinterview.io/KOURCFTBEG As I viewed a lot of examples, most of them put google.visualization.events.addListener(chart, 'ready',function() { console.log(chart.getChart().getImageURI()); document.getElementById('png').innerHTML = '<a href="' + chart.getChart().getImageURI() + '">Printable version</a>'; }); It seems to me that this would create a downloadable link to an image of the google chart on the <div id=png>But in my case, no link or clickable button is created. google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawBar); function drawBar() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses', 'Profit'], ['2013', 1001, 401, 201], ['2014', 1000, 400, 200], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, 350] ]); var options = { chart: { title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017', } }; //---------------------------// var chart = new google.charts.Bar(document.getElementById('chart_div')); // Wait for the chart to finish drawing before calling the getImageURI() method. google.visualization.events.addListener(chart, 'ready', function() { console.log(chart.getChart().getImageURI()); document.getElementById('png').innerHTML = '<a href="' + chart.getChart().getImageURI() + '">Printable version</a>'; }); chart.draw(data, options); } <body> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.0','packages':['corechart']},{'name':'visualization','version':'1.0','packages':['controls']}]}"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div> <div id='png'></div> </body> I followed the online source as similar as I can, but still get error like chart.getURI() is not function. Here is the online source I referred most. Here is Fiddle. A: By removing getChart() in chart.getChart().getImageURI()and ,in package, by modifying bar to corechart can do the work. google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawBar); function drawBar() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses', 'Profit'], ['2013', 1001, 401, 201], ['2014', 1000, 400, 200], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, 350] ]); var options = { chart: { title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017', } }; //---------------------------// var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); // Wait for the chart to finish drawing before calling the getImageURI() method. google.visualization.events.addListener(chart, 'ready', function() { // console.log(chart.getImageURI()); document.getElementById('png').innerHTML = '<a href="' + chart.getImageURI() + '">Printable version</a>'; }); chart.draw(data, options); } <body> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.0','packages':['corechart']},{'name':'visualization','version':'1.0','packages':['controls']}]}"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div> <div id='png'></div> </body>
{ "pile_set_name": "StackExchange" }
Q: Get ip address of source in mysql general query log? Is there some way for me to identify which server is doing an sql insert along with the details of the query? I don't know where my inserts are coming from and would like to identify the source A: If you are using PHP, then; Here is the code to display your ip address. $ip=@$REMOTE_ADDR; echo "<b>IP Address= $ip</b>"; IP address if the register_global is off If at php.ini if register_global is set to Off then we have to change the script a bit to get the address. Here it is $ip=$_SERVER['REMOTE_ADDR']; The IP address from which the user is viewing the current page. Note that changing register global setting my be a security problem particularly in live hosting environment so consult your host before in this aspects also. http://php.net/manual/en/reserved.variables.server.php
{ "pile_set_name": "StackExchange" }
Q: Simple limit. Used L'Hôpital's rule. Didn't work. $\lim_{x\rightarrow 0}f(x)$ $f(x)=\frac{\exp (\arcsin \left (x \right ))-\exp (\sin \left (x \right ))}{\exp (\arctan \left (x \right ))-\exp (\tan \left (x \right ))}$ I tried the L'Hôpital's rule as mentioned in the title and replaced ($\arcsin x$,$\arctan x$,$\sin x$,$\tan x$) with $\sim_{0}$ $x$ but still have an indeterminate form. Any hints please ? A: Alternatively, one may use Taylor series expansions, as $x \to 0$, $$ \begin{align} \sin x=& x-\frac{x^3}6+o(x^3) &\tan x=& x+\frac{x^3}3+o(x^3) \\\arcsin x=& x+\frac{x^3}6+o(x^3) &\arctan x=& x-\frac{x^3}3+o(x^3) \end{align} $$ and $$ e^u=1+u+\frac{u^2}2+\frac{u^3}6+o(u^3),\quad u \to0, $$giving, as $x \to 0$, $$ \frac{e^{\arcsin x}-e^{\sin x}}{e^{\arctan x}-e^{\tan x}}=\frac{\frac{x^3}3+o(x^3)}{-\frac{2x^3}3+o(x^3)}=\color{blue}{-\frac12}+o(1). $$ A: We can proceed as follows \begin{align} L &= \lim_{x \to 0}\frac{e^{\arcsin x} - e^{\sin x}}{e^{\arctan x} - e^{\tan x}}\notag\\ &= \lim_{x \to 0}e^{\sin x - \tan x}\cdot\frac{e^{\arcsin x - \sin x} - 1}{e^{\arctan x - \tan x} - 1}\notag\\ &= \lim_{x \to 0}\frac{e^{\arcsin x - \sin x} - 1}{\arcsin x - \sin x}\cdot\frac{\arcsin x - \sin x}{\arctan x - \tan x}\cdot\frac{\arctan x - \tan x}{e^{\arctan x - \tan x} - 1}\notag\\ &= \lim_{x \to 0}\frac{\arcsin x - \sin x}{\arctan x - \tan x}\notag\\ &= \lim_{x \to 0}\dfrac{\left(x + \dfrac{x^{3}}{6} + o(x^{3})\right) - \left(x - \dfrac{x^{3}}{6} + o(x^{3})\right)}{\left(x - \dfrac{x^{3}}{3} + o(x^{3})\right) - \left(x + \dfrac{x^{3}}{3} + o(x^{3})\right)}\notag\\ &= -\frac{1}{2}\notag \end{align}
{ "pile_set_name": "StackExchange" }
Q: Set list item permissions in Workflow 2013 I've created a workflow inside an "App for SharePoint 2013" project. I need to set special permissions to the curent list item inside this workflow. I read this http://social.technet.microsoft.com/Forums/sharepoint/en-US/e2e59b58-8623-472b-8314-f2967e5271e9/sharepoint-2013-workflow-update-list-item-permissions-in-workflow, and learned how to make it in SPD, but I need to do it inside an app, in visual studio. Did someone faced such problem? A: It's possible to set permissions using REST API in Workflow that runs under App identity. Please check my blog post about these methods: BreakRoleInheritance AddRoleAssignment Also we have released a set of SharePoint 2013 Workflow activities to work with permissions - Artezio SharePoint 2013 Workflow Activities. Please check.
{ "pile_set_name": "StackExchange" }
Q: JSON classes in Qt vs other JSON parsers in C++ I'm developing a server/client application in C++ and im using Qt as my IDE as well as some of its libraries. Performance-wise i was told that one of the best ways to transfer data between a server and client was via JSON. However i would like to know the performance differences between the default classes for parsing JSON in Qt (QJsonArray,QJsonObject.. etc) and other C++ parsers, like JSON++ for example.. A: If Qt classes are not performant enough, you can look at RapidJson: https://github.com/miloyip/rapidjson Performance comparision: http://code.google.com/p/rapidjson/wiki/Performance Good thing about RapidJson (apart from its speed) is easy installation and usage. From their website: rapidjson is a header-only library. That means, the only thing to be done is to copy rapidjson/include/rapidjson and its sub-directories to your project or other include paths. And example also from their wiki page: #include "rapidjson/document.h" #include <cstdio> int main() { const char json[] = "{ \"hello\" : \"world\" }"; rapidjson::Document d; d.Parse<0>(json); printf("%s\n", d["hello"].GetString()); return 0; }
{ "pile_set_name": "StackExchange" }
Q: Links do not work after translation into slim format I have an html code with rails. I need to translate it into slim format, I changed the file format, translated it with a convector and tried to run it as a result the links do not work, can you tell me why? head.html.erb <section id="header"> <div class='navigation-panel'> <button class='burger-button' id='header-burger-button container' onclick='burgerAction()'> <%= image_tag("header/burger.png") %> </button> <button class='contact-us-button burger-hidable container' onclick='scroller("contact")'> CONTACT US </button> <div class='menu-container burger-hidable container' style='display: none;'> <%= image_tag("header/menu.png") %> </div> <div class='nav-links burger-hidable' style='display: none;'> <p onclick='scroller("header")'>Home</p> <p onclick='scroller("services")'>Services</p> <p onclick='scroller("how-we-work")'>How We Work</p> <p onclick='scroller("team")'>Team</p> <p onclick='scroller("why-us")'>Why Us</p> <p onclick='scroller("portfolio")'>Portfolio</p> <p onclick='scroller("contact")'>Contact Us</p> </div> </div> </section> head.html.slim section#header .navigation-panel button.burger-button id=("header-burger-button container") onclick="burgerAction()" = image_tag("header/burger.png") button.contact-us-button.burger-hidable.container onclick="scroller(\"contact\")" CONTACT US .menu-container.burger-hidable.container style=("display: none;") = image_tag("header/menu.png") .nav-links.burger-hidable style=("display: none;") p onclick="scroller(\"header\")" Home p onclick="scroller(\"services\")" Services p onclick="scroller(\"how-we-work\")" How We Work p onclick="scroller(\"team\")" Team p onclick="scroller(\"why-us\")" Why Us p onclick="scroller(\"portfolio\")" Portfolio p onclick="scroller(\"contact\")" Contact Us A: I believe the problem is the escaped quotation inside the onclick attributes. Consider using single quotes inside your attributes' double quotes: onclick="scroller('header')". You can read more about escaping and quoting attributes here: https://www.rubydoc.info/gems/slim/frames#Output_without_HTML_escaping___
{ "pile_set_name": "StackExchange" }
Q: Add graphQL fragment to schema, and have available for all queries The following executes correctly in graphiQL fragment BookGridFields on Book { _id title } { allBooks { ...BookGridFields } } My question is, it possible to specify the fragment right in my schema, right below where my Book type is defined, like so type Book { _id: String title: String pages: Int weight: Float authors: [Author] } fragment BookGridFields on Book { _id title } So that I could just run queries like this { allBooks { ...BookGridFields } } without needing to define the fragment as part of my query. Currently the above errors with Unknown fragment \"BookGridFields\" A: Per the graphql docs, I see that fragments are a part of the query api and not valid syntax for setting up a schema. This leads me to conclude that it is not currently possible to specify a fragment in a schema. https://graphql.org/learn/queries/#fragments
{ "pile_set_name": "StackExchange" }
Q: double free or corruption error on free this is the piece of code i use to create my char array on heap int currentArraySize = 10; char **finalArray = malloc(sizeof(char*)*currentArraySize); char buf[6] = "hello"; for(int b=0; b<currentArraySize; b++ ) { char * tmpString = (char*)malloc(sizeof(char)*6); //copy the contents of buf to newly allocated space tmpString strncpy(tmpString,buf,6); finalArray[b] = tmpString; } //this should be a deep copy of finalArray char **copyArray = malloc(sizeof(char*)*currentArraySize); for(int c=0; c<currentArraySize; c++) { copyArray[c] = (char*)malloc(sizeof(char*)*6); //this supposed to copy the contents of finalArray[c] to copyArray[c] right? memcpy(copyArray[c], finalArray[c], sizeof(char)*currentArraySize); } and when i try to free it using for(int c = 0; c< currentArraySize; c++) free(finalArray[c]); //this gives me invalid ptr error free(finalArray); Without the memcpy part, everything is OK, but I'm somehow corrupting the memory using memcpy. I'm quite new to c, and i couldn't understand the root of the problem A: memcpy(copyArray[c], finalArray[c], sizeof(char)*currentArraySize); The last parameter should be at most sizeof(char)*6.
{ "pile_set_name": "StackExchange" }
Q: Pandas Multi-Index - Can't convert non-uniquely indexed DataFrame to Panel Given a time series data, I'm trying to use panel OLS with fixed effects in Python. I found this way to do it: Fixed effect in Pandas or Statsmodels My input data looks like this (I will called it df): Name Permits_13 Score_13 Permits_14 Score_14 Permits_15 Score_15 0 P.S. 015 ROBERTO CLEMENTE 12.0 284 22 279 32 283 1 P.S. 019 ASHER LEVY 18.0 296 51 301 55 308 2 P.S. 020 ANNA SILVER 9.0 294 9 290 10 293 3 P.S. 034 FRANKLIN D. ROOSEVELT 3.0 294 4 292 1 296 4 P.S. 064 ROBERT SIMON 3.0 287 15 288 17 291 5 P.S. 110 FLORENCE NIGHTINGALE 0.0 313 3 306 4 308 6 P.S. 134 HENRIETTA SZOLD 4.0 290 12 292 17 288 7 P.S. 137 JOHN L. BERNSTEIN 4.0 276 12 273 17 274 8 P.S. 140 NATHAN STRAUS 13.0 282 37 284 59 284 9 P.S. 142 AMALIA CASTRO 7.0 290 15 285 25 284 10 P.S. 184M SHUANG WEN 5.0 327 12 327 9 327 So first I have to transform it to Multi-index (_13, _14, _15 represent data from 2013, 2014 and 2015, in that order): df = df.dropna() df = df.drop_duplicates() rng = pandas.date_range(start=pandas.datetime(2013, 1, 1), periods=3, freq='A') index = pandas.MultiIndex.from_product([rng, df['Name']], names=['date', 'id']) d1 = numpy.array(df.ix[:, ['Score_13', 'Permits_13']]) d2 = numpy.array(df.ix[:, ['Score_14', 'Permits_14']]) d3 = numpy.array(df.ix[:, ['Score_15', 'Permits_15']]) data = numpy.concatenate((d1, d2, d3), axis=0) s = pandas.DataFrame(data, index=index, columns=['y', 'x']) s = s.drop_duplicates() Which results in something like this: y x date id 2013-12-31 P.S. 015 ROBERTO CLEMENTE 284 12 P.S. 019 ASHER LEVY 296 18 P.S. 020 ANNA SILVER 294 9 P.S. 034 FRANKLIN D. ROOSEVELT 294 3 P.S. 064 ROBERT SIMON 287 3 P.S. 110 FLORENCE NIGHTINGALE 313 0 P.S. 134 HENRIETTA SZOLD 290 4 P.S. 137 JOHN L. BERNSTEIN 276 4 P.S. 140 NATHAN STRAUS 282 13 P.S. 142 AMALIA CASTRO 290 7 P.S. 184M SHUANG WEN 327 5 P.S. 188 THE ISLAND SCHOOL 279 4 HENRY STREET SCHOOL FOR INTERNATIONAL STUDIES 255 4 TECHNOLOGY, ARTS, AND SCIENCES STUDIO 282 18 THE EAST VILLAGE COMMUNITY SCHOOL 306 35 UNIVERSITY NEIGHBORHOOD MIDDLE SCHOOL 277 4 THE CHILDREN'S WORKSHOP SCHOOL 302 35 NEIGHBORHOOD SCHOOL 299 15 EARTH SCHOOL 305 3 SCHOOL FOR GLOBAL LEADERS 286 15 TOMPKINS SQUARE MIDDLE SCHOOL 306 3 P.S. 001 ALFRED E. SMITH 303 20 P.S. 002 MEYER LONDON 306 8 P.S. 003 CHARRETTE SCHOOL 325 62 P.S. 006 LILLIE D. BLAKE 333 89 P.S. 011 WILLIAM T. HARRIS 320 30 P.S. 033 CHELSEA PREP 313 5 P.S. 040 AUGUSTUS SAINT-GAUDENS 326 23 P.S. 041 GREENWICH VILLAGE 326 25 P.S. 042 BENJAMIN ALTMAN 314 30 ... ... ... ... 2015-12-31 P.S. 054 CHARLES W. LENG 309 2 P.S. 055 HENRY M. BOEHM 311 3 P.S. 56 THE LOUIS DESARIO SCHOOL 323 4 P.S. 057 HUBERT H. HUMPHREY 287 2 SPACE SHUTTLE COLUMBIA SCHOOL 307 0 P.S. 060 ALICE AUSTEN 303 1 I.S. 061 WILLIAM A MORRIS 291 2 MARSH AVENUE SCHOOL FOR EXPEDITIONARY LEARNING 316 0 P.S. 069 DANIEL D. TOMPKINS 307 2 I.S. 072 ROCCO LAURIE 308 1 I.S. 075 FRANK D. PAULO 318 9 THE MICHAEL J. PETRIDES SCHOOL 310 0 STATEN ISLAND SCHOOL OF CIVIC LEADERSHIP 309 0 P.S. 075 MAYDA CORTIELLA 282 19 P.S. 086 THE IRVINGTON 286 38 P.S. 106 EDWARD EVERETT HALE 280 27 P.S. 116 ELIZABETH L FARRELL 291 3 P.S. 123 SUYDAM 287 14 P.S. 145 ANDREW JACKSON 285 4 P.S. 151 LYNDON B. JOHNSON 271 27 J.H.S. 162 THE WILLOUGHBY 283 22 P.S. 274 KOSCIUSKO 282 2 J.H.S. 291 ROLAND HAYES 279 13 P.S. 299 THOMAS WARREN FIELD 288 5 I.S. 347 SCHOOL OF HUMANITIES 284 45 I.S. 349 MATH, SCIENCE & TECH. 285 45 P.S. 376 301 9 P.S. 377 ALEJANDRINA B. DE GAUTIER 277 3 P.S. /I.S. 384 FRANCES E. CARTER 291 4 ALL CITY LEADERSHIP SECONDARY SCHOOL 325 18 However, when I try to call: reg = PanelOLS(y=s['y'],x=s[['x']],time_effects=True) I get an error: ValueError: Can't convert non-uniquely indexed DataFrame to Panel That's my first time using Pandas, this may be a simple question but I don't know what's the problem. As far as I got I have a multi-index object as required. I don't get why I have duplicates (I put a lot of drop_duplicates() try to get rid of any duplicated data -- which I don't think is the answer, though). If I have data for the same school for three years, shouldn't I have duplicate data somehow (looking just at the row Name, for example)? EDIT dfis 935 rows × 7 columns, after getting rid of NaNs rows. So I expected s to be 2805 rows × 2 columns, which is exactly what I have. If i run this: s = s.reset_index().groupby(s.index.names).first() reg = PanelOLS(y=s['y'],x=s[['x']],time_effects=True) I get another error: ValueError: operands could not be broadcast together with shapes (2763,) (3,) Thank you. A: Using the provided pickle file, I ran the regression and it worked fine. -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <x> Number of Observations: 2763 Number of Degrees of Freedom: 4 R-squared: 0.0268 Adj R-squared: 0.0257 Rmse: 16.4732 F-stat (1, 2759): 25.3204, p-value: 0.0000 Degrees of Freedom: model 3, resid 2759 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- x 0.1666 0.0191 8.72 0.0000 0.1292 0.2041 ---------------------------------End of Summary--------------------------------- I ran this in Jupyter Notebook
{ "pile_set_name": "StackExchange" }
Q: Best way to interpolate a numpy.ndarray along an axis I have 4-dimensional data, say for the temperature, in an numpy.ndarray. The shape of the array is (ntime, nheight_in, nlat, nlon). I have corresponding 1D arrays for each of the dimensions that tell me which time, height, latitude, and longitude a certain value corresponds to, for this example I need height_in giving the height in metres. Now I need to bring it onto a different height dimension, height_out, with a different length. The following seems to do what I want: ntime, nheight_in, nlat, nlon = t_in.shape nheight_out = len(height_out) t_out = np.empty((ntime, nheight_out, nlat, nlon)) for time in range(ntime): for lat in range(nlat): for lon in range(nlon): t_out[time, :, lat, lon] = np.interp( height_out, height_in, t[time, :, lat, lon] ) But with 3 nested loops, and lots of switching between python and numpy, I don't think this is the best way to do it. Any suggestions on how to improve this? Thanks A: scipy's interp1d can help: import numpy as np from scipy.interpolate import interp1d ntime, nheight_in, nlat, nlon = (10, 20, 30, 40) heights = np.linspace(0, 1, nheight_in) t_in = np.random.normal(size=(ntime, nheight_in, nlat, nlon)) f_out = interp1d(heights, t_in, axis=1) nheight_out = 50 new_heights = np.linspace(0, 1, nheight_out) t_out = f_out(new_heights) A: I was looking for a similar function that works with irregularly spaced coordinates, and ended up writing my own function. As far as I see, the interpolation is handled nicely and the performance in terms of memory and speed is also quite good. I thought I'd share it here in case anyone else comes across this question looking for a similar function: import numpy as np import warnings def interp_along_axis(y, x, newx, axis, inverse=False, method='linear'): """ Interpolate vertical profiles, e.g. of atmospheric variables using vectorized numpy operations This function assumes that the x-xoordinate increases monotonically ps: * Updated to work with irregularly spaced x-coordinate. * Updated to work with irregularly spaced newx-coordinate * Updated to easily inverse the direction of the x-coordinate * Updated to fill with nans outside extrapolation range * Updated to include a linear interpolation method as well (it was initially written for a cubic function) Peter Kalverla March 2018 -------------------- More info: Algorithm from: http://www.paulinternet.nl/?page=bicubic It approximates y = f(x) = ax^3 + bx^2 + cx + d where y may be an ndarray input vector Returns f(newx) The algorithm uses the derivative f'(x) = 3ax^2 + 2bx + c and uses the fact that: f(0) = d f(1) = a + b + c + d f'(0) = c f'(1) = 3a + 2b + c Rewriting this yields expressions for a, b, c, d: a = 2f(0) - 2f(1) + f'(0) + f'(1) b = -3f(0) + 3f(1) - 2f'(0) - f'(1) c = f'(0) d = f(0) These can be evaluated at two neighbouring points in x and as such constitute the piecewise cubic interpolator. """ # View of x and y with axis as first dimension if inverse: _x = np.moveaxis(x, axis, 0)[::-1, ...] _y = np.moveaxis(y, axis, 0)[::-1, ...] _newx = np.moveaxis(newx, axis, 0)[::-1, ...] else: _y = np.moveaxis(y, axis, 0) _x = np.moveaxis(x, axis, 0) _newx = np.moveaxis(newx, axis, 0) # Sanity checks if np.any(_newx[0] < _x[0]) or np.any(_newx[-1] > _x[-1]): # raise ValueError('This function cannot extrapolate') warnings.warn("Some values are outside the interpolation range. " "These will be filled with NaN") if np.any(np.diff(_x, axis=0) < 0): raise ValueError('x should increase monotonically') if np.any(np.diff(_newx, axis=0) < 0): raise ValueError('newx should increase monotonically') # Cubic interpolation needs the gradient of y in addition to its values if method == 'cubic': # For now, simply use a numpy function to get the derivatives # This produces the largest memory overhead of the function and # could alternatively be done in passing. ydx = np.gradient(_y, axis=0, edge_order=2) # This will later be concatenated with a dynamic '0th' index ind = [i for i in np.indices(_y.shape[1:])] # Allocate the output array original_dims = _y.shape newdims = list(original_dims) newdims[0] = len(_newx) newy = np.zeros(newdims) # set initial bounds i_lower = np.zeros(_x.shape[1:], dtype=int) i_upper = np.ones(_x.shape[1:], dtype=int) x_lower = _x[0, ...] x_upper = _x[1, ...] for i, xi in enumerate(_newx): # Start at the 'bottom' of the array and work upwards # This only works if x and newx increase monotonically # Update bounds where necessary and possible needs_update = (xi > x_upper) & (i_upper+1<len(_x)) # print x_upper.max(), np.any(needs_update) while np.any(needs_update): i_lower = np.where(needs_update, i_lower+1, i_lower) i_upper = i_lower + 1 x_lower = _x[[i_lower]+ind] x_upper = _x[[i_upper]+ind] # Check again needs_update = (xi > x_upper) & (i_upper+1<len(_x)) # Express the position of xi relative to its neighbours xj = (xi-x_lower)/(x_upper - x_lower) # Determine where there is a valid interpolation range within_bounds = (_x[0, ...] < xi) & (xi < _x[-1, ...]) if method == 'linear': f0, f1 = _y[[i_lower]+ind], _y[[i_upper]+ind] a = f1 - f0 b = f0 newy[i, ...] = np.where(within_bounds, a*xj+b, np.nan) elif method=='cubic': f0, f1 = _y[[i_lower]+ind], _y[[i_upper]+ind] df0, df1 = ydx[[i_lower]+ind], ydx[[i_upper]+ind] a = 2*f0 - 2*f1 + df0 + df1 b = -3*f0 + 3*f1 - 2*df0 - df1 c = df0 d = f0 newy[i, ...] = np.where(within_bounds, a*xj**3 + b*xj**2 + c*xj + d, np.nan) else: raise ValueError("invalid interpolation method" "(choose 'linear' or 'cubic')") if inverse: newy = newy[::-1, ...] return np.moveaxis(newy, 0, axis) And this is a small example to test it: import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d as scipy1d # toy coordinates and data nx, ny, nz = 25, 30, 10 x = np.arange(nx) y = np.arange(ny) z = np.tile(np.arange(nz), (nx,ny,1)) + np.random.randn(nx, ny, nz)*.1 testdata = np.random.randn(nx,ny,nz) # x,y,z # Desired z-coordinates (must be between bounds of z) znew = np.tile(np.linspace(2,nz-2,50), (nx,ny,1)) + np.random.randn(nx, ny, 50)*0.01 # Inverse the coordinates for testing z = z[..., ::-1] znew = znew[..., ::-1] # Now use own routine ynew = interp_along_axis(testdata, z, znew, axis=2, inverse=True) # Check some random profiles for i in range(5): randx = np.random.randint(nx) randy = np.random.randint(ny) checkfunc = scipy1d(z[randx, randy], testdata[randx,randy], kind='cubic') checkdata = checkfunc(znew) fig, ax = plt.subplots() ax.plot(testdata[randx, randy], z[randx, randy], 'x', label='original data') ax.plot(checkdata[randx, randy], znew[randx, randy], label='scipy') ax.plot(ynew[randx, randy], znew[randx, randy], '--', label='Peter') ax.legend() plt.show()
{ "pile_set_name": "StackExchange" }
Q: Module Build Failed when mapping Radio Input OK, so this has been bugging me for days, and I haven't found the answer yet. I imagine I am doing something dumb ("semi-colon problems" I call them), but I can't find it. I am also new to React, so please chide me if I am doing something totally wrong. I am getting the following error when I compile with webpack: ERROR in ./src/client/app/components/SelectorComponent.jsx Module build failed: SyntaxError: Unexpected token, expected , (12:56) 10 | console.log(race); 11 | return ( > 12 | <input type="radio" key={race._id}/>{race.raceDate} {race.location} {race.gender} {race.skill} {race.distance} | ^ 13 | ) 14 | })} 15 | <input type="radio"/>Casper 2017<br/> Here is my Component that is generating the error: import React from 'react'; class SelectorComponent extends React.Component { render() { return ( <div id='selector-component'> <h3>Race Selector</h3> <form> {this.props.races.map(function(race) { console.log(race); return ( <input type="radio" key={race._id}/>{race.raceDate} {race.location} {race.gender} {race.skill} {race.distance} ) })} <input type="radio"/>Casper 2017<br/> <input type="radio"/>Laramie 2017 </form> </div> ); } } export default SelectorComponent; Here is a list of things of a few ideas I have tried: Removing the 'key' attribute (Does not fix error) Using a paragraph tag (p) around the race data (Fixes error...but we want to use an input tag) Which is what leads me to believe the error revolves around something I am doing wrong with the input tag. Please let me know if you need anything else to help me. A: React v15 does not allow to return more than one parent element tag, meaning that if you have more than one element, these elements should be wrapped in a parent tag. In your case you are effectively trying to return several elements, because <input /> and text are treated as separate elements. You need to wrap these with a parent element. Most commonly this is done with <span> or <label> tags. Your modified code: {this.props.races.map(function(race) { console.log(race); return ( <label> <input type="radio" key={race._id}/>{race.raceDate} {race.location} {race.gender} {race.skill} {race.distance} </label> ) })}
{ "pile_set_name": "StackExchange" }
Q: How do I configure the Maven WAR plugin to execute the "inplace" goal by default? I’m using Maven 3.2.3 and the Maven War 2.6 plugin. I would like the “inlace” goal of the Maven WAR plugin to execute by default (without my having to explicitly specify “war:inlace” on the command line). So I created a profile to include the below <profile> <id>dev</id> <activation> <property> <name>!flag</name> </property> </activation> <build> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>2.4.1</version> <configuration> <filesets> <fileset> <directory>${project.basedir}/src/main/webapp/WEB-INF/classes</directory> </fileset> <fileset> <directory>${project.basedir}/src/main/webapp/WEB-INF/lib</directory> </fileset> </filesets> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <useCache>true</useCache> <workDirectory>/tmp/${project.artifactId}/war/work</workDirectory> </configuration> <goals> <goal>inplace</goal> </goals> </plugin> </plugins> </build> </profile> Using “mvn help:active-profiles”, I have verified this profile is being used when I run “mvn clean install” on my WAR project. However, the WAR is not assembled in place. For instance, I get the output [INFO] Packaging webapp [INFO] Assembling webapp [myproject] in [/Users/davea/Dropbox/workspace/myproject/target/myproject] [INFO] Processing war project [INFO] Copying webapp resources [/Users/davea/Dropbox/workspace/myproject/src/main/webapp] [INFO] Webapp assembled in [17460 msecs] Also I notice there are no “classes” or “lib” resources in my src/main/resources/WEB-INF folder. What do I need to configure differently to get my WAR to be built in-place? A: This can probably be classified as a duplicate of How to get Maven to run war:exploded but not war:war with a small twist. Instead of exploded it needs to be inplace: <pluginManagement> <plugins> <plugin> <!-- don't pack the war --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <!-- optional, depends on your setup --> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> <executions> <execution> <id>default-war</id> <phase>none</phase> </execution> <execution> <id>war-inplace</id> <phase>package</phase> <goals> <goal>inplace</goal> </goals> </execution> </executions> </plugin> ... </plugins> <pluginManagement>
{ "pile_set_name": "StackExchange" }
Q: Most performant way of range querying large PouchDB datasets I'm building an IoT application which collects a bunch of different metrics every second. On the client I'm displaying the data using charts. However, every time I change the time range of the charts/reload the page, it takes waaay too long to load all datapoints from the server. So I've started looking in to persistent storage in the browser, mainly using PouchDB. Then every time the browser refreshes, the data fetching will be much snappier. Of course you have to take Browser Quota etc into consideration, but that is a different issue. An example datapoint looks like this { "metricId": <String>, "metricName": <String>, "timestamp": <Unix Timestamp> "value": <Integer> } Approach 1 - Multiple databases, one index As I have many different metrics, I'm thinking of creating a new PouchDB database per metric, and then index on the timestamp. // (using pouchdb-find plugin) const db = new PouchDB(<metricName>); db.createIndex({ index: { fields: ['timestamp'] } }) db.find({ selector: { timestamp: { '$gte' : from, '$lte' : to }} }) Approach 2 - One database, multiple indices The other solution is to create one database to hold all the metrics, and have multiple indices instead. // (using pouchdb-find plugin) const db = new PouchDB('all_data'); db.createIndex({ index: { fields: ['metricId', 'metricName', 'timestamp'] } }); db.find({ selector: { $and: [ { metricId: metricId }, { metricName: metricName }, { timestamp: { '$gte' : from, '$lte' : to }} ] } }) Question Which is the most performant on the two, or is there a smarter way of creating the indices? Or is there a different approach without using PouchDB at all? A: Anwering my own question as I found a solution, not using PouchDB but using YDN-DB. Using Approach 1 above with multiple databases and one indexed column (of type integer timestamp), I've reached very good performance. Both writing and reading ~5000 rows takes about 300 ms. My tests showed that this approach is about 3x faster than using a compound index (Approach 2). Posting code here if anyone else stumbles upon this SO question. // Create unique DB with index const dbname = [metricId, metricName].join("_"); const schema = { stores: [{ name: 'metrics', indexes: [{ keyPath: 'timestamp' }] }] } const db = new ydn.db.Storage(dbname, schema); // writing data.. timestamp is unix timestamp db.put('metrics', { timestamp, value }, timestamp); // reading data const query = db.from('metrics').where('timestamp', '>=', from, '<=', to); query.list(5000).done(result => { console.log(result); });
{ "pile_set_name": "StackExchange" }
Q: file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4" I am pushing my docker image to AWS ECS. And, I am getting following error: file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4" Here is the full output: The push refers to repository [myaddress.dkr.ecr.us-east-1.amazonaws.com/myrepositoryname] 3d4763f6944c: Layer already exists 5d22ab3cff2d: Layer already exists 080db391ad2c: Layer already exists 7030a45b5de7: Layer already exists 5d98bab77a5b: Layer already exists f08694a3abdb: Layer already exists c4cfb93dc085: Layer already exists 1a38a1227cbb: Layer already exists caa05d68a0ed: Layer already exists 891119e77426: Layer already exists 1f912505da6e: Layer already exists f1e810a48819: Layer already exists a47630fbce4f: Layer already exists 09fc3edb847c: Layer already exists 6b60013e5875: Pushing [==================================================>] 323.9MB/323.9MB d6335a641f5e: Layer already exists 5c33df241050: Layer already exists ffc4c11463ee: Layer already exists file integrity checksum failed for "usr/lib/x86_64-linux-gnu/libfftw3.so.3.4.4" Is there any solution for the above issue? I tried to build an image again and also increased allocated memory in docker. A: This solution worked for me: docker system prune -a And then create a new image and push. A: I was getting a similar error, though in my case it was related to the NPM cache. file integrity checksum failed for "root/.npm/_cacache/content-v2/sha512/d1/32/a7a1c3a9679bc2b3533e44dd7850d81c4c257024e9f32854b681383a5ed1c191412124a0d316bea11daa019c2bee1bf18770034bd53db117aedc09339b0b All I had to do was full build with the --no-cache option, e.g.: docker build --no-cache . Push to AWS was successful after the full build.
{ "pile_set_name": "StackExchange" }
Q: Moving back my question to MO References on Gerbes question is migrated from MO to meta. It was never about MO. I was only giving information about search I have done. None of the comments except one has objection with this. None of the answers says anything about MO. I have even taken that users objection and removed information about MO. Can it go back to MO now? A: The question on MathOverflow has been restored. The corresponding question on Meta.MathOverflow has been deleted.
{ "pile_set_name": "StackExchange" }
Q: String Regex Help C# I'm trying to create a regex that reads a string, and if the last character is something like !"£$% etc, it ignores the last character, reads the string (to allow my code to look it up in a dictionary class) and then outputs the string, with the character on the end it ignored. Is this actually possible, or do I have to just remove the last character? So far... foreach(var line in yourReader) { var dict = new Dictionary<string,string>(); // your replacement dictionaries foreach(var kvp in dict) { System.Text.RegularExpressions.Regex.Replace(line,"(\s|,|\.|:|\\t)" + kvp.Key + "(\s|,|\.|:|\\t)","\0" + kvp.Value + "\1"); } } I've also been told to try this var trans = textbox1.Text; foreach (var kvp in d) //d is my dictionary so use yours { trans = trans.Replace(kvp.Key, kvp.Value); } textbox2.Text = trans; but have literally no idea what it does A: I didn't find any point using Regex, so I hope this will help: const int ARRAY_OFFSET = 1; List<char> ForbiddenChars = new List<char>() { '!', '@', '#', '$', '%', '^', '&', '*', '£' //Add more if you'd like }; string myString = "Hello World!&"; foreach (var forbiddenChar in ForbiddenChars) { if (myString[myString.Length - ARRAY_OFFSET] == forbiddenChar) { myString = myString.Remove(myString.Length - ARRAY_OFFSET); break; } } Edit: I checked the old code, and it had a problem: when the string's last "forbidden" characters were in order of the ForbiddenChars array it deleted all of them. if your string was "Hello World&!" it would delete both the ! and &. so I set a break; and it won't be a problem anymore.
{ "pile_set_name": "StackExchange" }
Q: Hard drive died, how do I get the OS X on new hard drive? I have a huge problem. My hard disk seems to be dead. I did a lot of things but I guess it's really gone. The thing is that I don't have CDs o DVDs of the OS X Lion (it's a macbook pro A1278 bought in 2012) and no backup in time machine. I lost all my files so I'm already grieving. The thing is, if I buy a new HDD, how do I get the OS X there? A: Buy an SSD instead of an HDD if you can afford one. Believe me, you'll thank us. You currently have a MacBook Pro with a fast Intel processor but an extraordinarily slow hard drive. Your failed hard drive was your computer's main performance bottleneck. Replace it with a fast SSD from a reputable manufacturer like Samsung or Intel, and your computer will perform far better than new. You could reinstall Lion using Internet Recovery. But, it would be much better to skip the outdated versions and install Yosemite. You can create a bootable Yosemite installation disk using an 8GB USB flash drive and a friend's Mac. Here are Apple's instructions for creating a bootable Yosemite install disk from an 8GB USB flash drive: Download the OS X Installer app from the Mac App Store. Mount the volume you want to convert into a bootable installer. This could be removable media such as a USB flash drive, or a secondary internal partition. You can then use the createinstallmedia tool to convert the volume from step two into a bootable installer based off the installer app from step one. To learn how to use createinstallmedia, use the following command in Terminal: /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia After you have created a Yosemite installation disk, insert it in your Mac's USB port and hold down Option as you power up. You will be able to boot from your Yosemite installation disk, just like you would from a Lion installation DVD. Non-technical users may prefer a more detailed walkthrough of creating a Yosemite installation disc. A: You may be able to do Internet Recovery by pressing Cmd+R during startup. If that is possible, then: Install the new HDD. Boot to Internet Recovery. Enter Disk Utility. Create the installation partition. Exit Disk Utility and choose to Reinstall Mac OS X. You can test this even with the bad HDD still in place. If your system did not come from Apple with installation DVDs, your system most likely supports Internet Recovery. You'll need an internet connection for it to work and, yep, it'll take some time to download that Lion image.
{ "pile_set_name": "StackExchange" }
Q: API to use XBox 360 as extender / enable UPnP AV Transport on XBox What I want to achieve is to be able to tell the XBox 360 to play a HTTP / MP3 stream from some server and I want to control this remotely (i.e. not use the XBox controller / TV screen). I know there is UPnP media servers that are detected by the XBox, but those require some setup and the main problem is that I would have to use my xbox to play the music. I want to build an Android App that can stream to the XBox while I control everything from the app. As such my idea is to run a HTTP server on the phone, detect the XBox and tell it to play the http URL which points back to the phone. I can find the XBox UPnP MediaRenderer interface, but it is not advertising the AVTransport Service (which is needed). I have tried the same thing with XBMC and it works (XBMC does have the AVTransport). Windows Media Center does use XBox as Extender, so it must be possible. The question is how. Maybe there is an Extender setup handshake that enables the AVTransport feature? A: This guy says that "protocols used between the extender and the media center are partially open" and gives some links to MSDN. But nothing like a hidden AVTransport interface which comes up after the device pairing, i'm afraid. No hope for something as embarassingly boring as standard SetAVTransportURI. The communication seems to be carried over "Remote Desktop Protocol channels" (whatever that is), which lefts me confused about why Microsoft bothered to implement MediaRenderer at all. Another shot at "embrace, extend, extinguish", i guess. Which is hilariously recursive because UPnP is based on Microsoft-invented SSDP. Any way, it's apparently a hardcore reverse engineering, packet capturing being a prominent tool. There is another project referenced from that page, aiming at recreating Media Center - basically what you would like to have. But stalled for almost 3 years. I think you're free to pick up :)
{ "pile_set_name": "StackExchange" }
Q: ASP.NET: UpdateProgress doesn't work with controls that have ClientIDMode="Static" Look at this markup: <asp:UpdatePanel ID="Panel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:DropDownList ID="cboBox1" ClientIDMode="Static" AutoPostBack="true" runat="server" /> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:DropDownList ID="cboBox2" runat="server" /> <asp:UpdateProgress ID="UpdateProgress1" style="display: inline" AssociatedUpdatePanelID="Panel1" DynamicLayout="false" DisplayAfter="0" runat="server"> <ProgressTemplate> <img src='<%= ResolveClientUrl("~/Images/indicator.gif")%>' border="0" alt="" /> </ProgressTemplate> </asp:UpdateProgress> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="cboBox1" EventName="SelectedIndexChanged" /> </Triggers> </asp:UpdatePanel> The UpdateProgress control worked initially, but broke when we added ClientMode="Static" to the cboBox1. Reverting it back to AutoID is not an option, so I need to find solutions that allow the UpdateProgress panel to work with ClientIDMode="Static". Also, could someone add "clientidmode" to the list of tags? A: Looks like this is a bug in PageRequestManager since postBackElement doesn't passed to beginRequest event handler. For this particular issue you may use following script: $(function () { $("#cboBox1").live("change", function () { window.setTimeout(function () { var progress = $find("<%= UpdateProgress1.ClientID %>"); // since you use 0 DisplayAfter property value you may // just call progress.set_visible(true); // without timeout usage window.setTimeout(function () { progress.set_visible(true); }, progress.get_displayAfter()); }, 0); }); });
{ "pile_set_name": "StackExchange" }
Q: go back before .text() is used On hover content is being replaced, but when the mouse leaves the element I want it to change back. How would I do this? $('.img-wrap').hover(function(){ $(this).find('h4').text('Go to site'); }); A: You need to store the original text in $.data in the first callback, then read it in the second callback. For example: $('.img-wrap').hover(function(){ var h4 = $(this).find('h4'); h4.data('oldText', h4.text()).text('Go to site'); }, function() { $(this).find('h4').text(function() { return $.data(this, "oldText"); }); });
{ "pile_set_name": "StackExchange" }
Q: How will Harry Potter be in danger if he did not return to his Aunt and Uncle's house? I just wondered that if Harry did not return to his Aunt and Uncle's house at the end of a Hogwarts year e.g, if he went straight to the Weasley's or Granger's house at the end of the school year, will Voldemort find out where he is living? If yes, how will he find out? A: Solemnity's answer, while nicely formatted, contains several errors. First, there is no "Sacrificial Protection" spell; this is an example of the HP Wikia featuring a spell that essentially someone just made up (which, of course, is not Solemnity's fault) -- I challenge anyone to find "Sacrificial Protection Spell" in the Harry Potter canon. Lily did not cast a spell -- she was murdered too fast for her to have done so. What we will find throughout the series is numerous references to the enchantments Lily bestowed upon Harry by sacrificing her own life in order to save Harry's. Harry is protected by his mother's enduring love. Dumbledore invoked the power of Lily's love by placing Harry with the Dursleys. In the letter Dumbledore left when Harry was an infant and was placed on the Dursleys' doorstep, Dumbledore explained what had happened to Lily and James, and implored the Dursleys to treat and raise Harry as if he were their son, which we know the Dursleys did not do. However, they allowed Harry to call number four Privet Drive his home, thus sealing and strengthening the magical enchantments already in place due to Lily's sacrifice. Dumbledore, by explaining the events surrounding the Potters' deaths and beseeching the Dursleys to take Harry in, sealed this magical protective bond, which went into place the minute Petunia accepted she would take Harry in. ‘The magic I evoked fifteen years ago means that Harry has powerful protection while he can still call this house home. However miserable he has been here, however unwelcome, however badly treated, you have at least, grudgingly, allowed him houseroom. This magic will cease to operate the moment that Harry turns seventeen; in other words, the moment he becomes a man. Half-Blood Prince - page 57 - Bloomsbury - chapter 3, Will and Won't Dumbledore did not invoke any further magic. He did not make number four Privet Drive Unplottable (otherwise, how could Arabella Figg keep an eye on Harry for Dumbledore) and he did not cast Protego totalum around the house. Again, I invite anyone to find evidence of this in canon. Voldemort knew Harry was at number four Privet Drive, but because of Lily's protective enchantments, he was unable to touch Harry there, through most of Goblet of Fire. However, by taking Harry's blood in Goblet of Fire, it would seem that Voldemort overcame Lily's enchantments. Harry showed them both the place where his robes were torn, and the cut beneath them. ‘He said my blood would make him stronger than if he’d used someone else’s,’ Harry told Dumbledore. ‘He said the protection my – my mother left in me – he’d have it, too. And he was right – he could touch me without hurting himself, he touched my face.’ [...] ‘Very well,’ [Dumbledore] said, sitting down again. ‘Voldemort has overcome that particular barrier. Harry, continue, please.’ Goblet of Fire - page 604 - Bloomsbury - chapter 36, The Parting of the Ways In every single book, Harry first returns to Privet Drive before heading out somewhere else, such as the Burrow. After Voldemort takes Harry's blood in Goblet of Fire, he's placed in some kind of protective custody after he returns to Privet Drive. In Order of the Phoenix the Advance Guard collects him from Privet Drive and takes him to number twelve Grimmauld Place. In Half-Blood Prince, Harry's taken to the Burrow, as he is in Deathly Hallows. He cannot go straight to the Burrow or straight to Grimmauld Place because he must first make contact with Privet Drive -- the place he calls home, even if in name only -- to keep Lily's enchantments in place. If he went straight to the Burrow or to Hermione's would Voldemort find out where he was living? Undoubtedly, because Lily's protective enchantments protecting Harry from detection from Voldemort would be broken and would afford him no further protection from Voldemort. As far as I can recall, it does not say in canon exactly how Voldemort would be able to find Harry once Lily's enchantments were broken. Correct me if I'm wrong, though. A: Slytherincess's answer is very good and thorough, but with one slight tweak. I believe the statement "Dumbledore did not invoke any further magic." is not entirely correct. In OotP, The Lost Prophecy chapter, Dumbledore clearly states he places a charm on Harry and "gives" Harry a shield: “But she took you,” Dumbledore cut across him. “She may have taken you grudgingly, furiously, unwillingly, bitterly, yet still she took you, and in doing so, she sealed the charm I placed upon you. Your mother’s sacrifice made the bond of blood the strongest shield I could give you.” One could argue that the charm Dumbledore refers to is simply the act of delivering Harry to Privet Dr. But the language he chooses makes it sound like he did a more significant magical act than simply dropping Harry off.
{ "pile_set_name": "StackExchange" }
Q: Cache.Session return null value I have create small function to store and retrieve the value inside static using session cache. but i am unable to get the data which i have stored in session cache. I am not getting any error on retrieve or inserting but Always return null value. Any one can help me. Here is My platform Cache setting Apex Controller : public class SessionCacheController { public static String name {get;set;} public static String check {get;set;} public static String dummy {get;set;} private static final String KEY = 'Key'; private static final String VALUE = 'Any value'; //adding key,value pair to cache public static void setData() { dummy='setData'; Cache.Session.put('MyPackagePrefix.PlatformCache.myName', 'Nithesh K'); Cache.Partition partition = Cache.Session.getPartition('PlatformCache'); partition.put(KEY, VALUE); } //retrieve value by key public static void getData() { dummy='getData'; Name=(String)Cache.Session.get('MyPackagePrefix.PlatformCache.myName'); system.debug('myName *** ' + Name); // return null Cache.Partition partition = Cache.Session.getPartition('PlatformCache'); check = (String) partition.get(KEY); system.debug('check *** ' + check); // return null } } Visual force Page <apex:page controller="SessionCacheController"> <apex:form > <apex:pageBlock id="pageSection"> <apex:outputText > My name {! Name } </apex:outputText> <br/> <apex:outputText > Check Key {! check } </apex:outputText> <br/> <apex:outputText > dummy {! dummy } </apex:outputText> <br/> </apex:pageBlock> <apex:commandButton value="setData" action="{!setData }" reRender="pageSection"/> <apex:commandButton value="getData" action="{!getData }" reRender="pageSection"/> </apex:form> </apex:page> When i click setData() command-button, Value is added cache.session and getData() value is retrieve from cache.session and render in visual force page . A: I have found answer for my question by Allocating space to Session Cache and Org Cache Allocation . I have forgot to change the value of Session Cache Allocation and Org Cache Allocation from 0 to some other value. without that it is not working.. Above session cache code only works if your created new Platform Cache. If you don't know how create a Platform Cache, Follow below link one by one First Follow this link to activate Request Trial Capacity Second Follow this link to create new platform cache If your finished with above two step then click on edit on platform cache which your newly created, Change trail value 0 to 5 in Session Cache Allocation and Org Cache Allocation and save it. How to use session cache
{ "pile_set_name": "StackExchange" }
Q: Semantic UI Minimize normal sidebar to icon sidebar I'm trying to customize the semantic-ui sidebar. I intend to create when i click the toggle button it will minimized to the labeled(icon) one. But it doesn't seems to be animated and the content(push content) doesn't seems to be pulled when i minimized it to the labeled icon sidebar. HTML <div class="ui left demo vertical inverted visible sidebar menu"> <a class="item"> <i class="home icon"></i> Home </a> <a class="item"> <i class="block layout icon"></i> Topics </a> <a class="item"> <i class="smile icon"></i> Friends </a> </div> <div class="pusher"> <a href="#" id="toggle-btn">Toggle</a> </div> JS $("#toggle-btn").click(function() { $(".ui.sidebar") .toggleClass("labeled icon"); }); And here's the codepen: http://codepen.io/andhikaribrahim/pen/rWNEzr Any help would be great! Thanks in advance. A: Checkout this Codepen. Add a class on the .pusher as well to animate it accordingly using jQuery. Also, use CSS transitions insert animations. For reference, CSS: .ui.left { transition: width .2s linear; } .labeled.icon { width: 84px !important; } .pusher.push { transform: translate3d(84px,0,0) !important; } JS: $("#toggle-btn").click(function() { $(".ui.sidebar").toggleClass("labeled icon"); $(this).parent().toggleClass('push'); }); Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: An easier of keeping data in the text fields in php if an error statement occurs I have a simple xhtml form with textboxes asking the user for their name, id, address etc. I have to use php to validate the data. For example in the ID field exactly 6 numerical values are allowed, if thats not the case, it shows an error to the user asking them to fix it. What i want do is, when the user clicks submit with the incorrect data, i want to keep the data in the field when the error shows up. I am currently doing that by:- <td><label for="customerid">*Customer ID: </label></td> <td><input type="text" value=" <?php if(($_POST['customerid'] != $id) || ($_POST["customerfname"] != $fname) || ($_POST["customerlname"] != $lname)){echo $_POST['customerid'];} ?>" id="customerid" name="customerid"/> I have just been modyifying that statement for all textboxes but as you can imagine it will get a little complicated if i have to do that for 10 boxes. i was wondering if it was an easier way to do this. bold UPDATED <td> <select name="state" id="state" value="<?php echo (isset($_POST["state"]) ? : ''); ?>"> <option value="--">--</option> <option value="ACT">ACT</option> <option value="NSW">NSW</option> <option value="NT">NT</option> <option value="QLD">QLD</option> <option value="SA">SA</option> </select> </td> A: Something like this? <input type="text" name="customerid" value="<?php echo (isset($_POST['customerid']) ? $_POST['customerid'] : ''); ?>"> Update - run your checks before the form is re-generated <?php if(($_POST['customerid'] != $id) || ($_POST["customerfname"] != $fname) || ($_POST["customerlname"] != $lname)) { // do nothing } else { $_POST['customerid'] = ''; } ?> <input type="text" name="customerid" value="<?php echo (isset($_POST['customerid']) ? $_POST['customerid'] : ''); ?>">
{ "pile_set_name": "StackExchange" }
Q: 2D Fourier transform of $1/(1+|\mathbf{r}|^6)$ In some physics literature I've been studying I ran into the Fourier transform of the function $$f(\mathbf{r}) = \frac{1}{1+|\mathbf{r}|^6},$$ where $\mathbf{r}$ is a two dimensional vector. These papers (#1, see p. 21; and #2, see p. 3) claim this equals $$\mathcal{F}[f(\mathbf{r})] = \left(\frac{2\pi^2}{3} \right) \left(\frac{e^{-k/2}}{k} \right) \left[e^{-k/2} - 2\sin(\pi/6 - \sqrt{3}k/2) \right],$$ where $k = |\mathbf{k}| = |(k_1,k_2)|$ with these being the Fourier variables corresponding to $\mathbf{r} = (x,y)$. Unfortunately, I cannot find any more details on the derivation of this result. Understanding it would hopefully help me understand some more of the physics. I've tried carrying out the Fourier integral myself, but to no avail (although I'm far from an expert on the topic). The FourierTransform function of Mathematica is also of disappointingly little help, despite it seeming like such a manageable result. I would appreciate any suggestions and/or pointers to transform rules that I may be missing that would make life easier. A: I) It is true that the 2D Fourier transform is $$ \begin{align} \hat{h}({\bf k})~&=~\iint_{\mathbb{R}^2} \! \frac{\mathrm{d}^2r}{2\pi} \exp\left(\pm i {\bf r}\cdot{\bf k} \right) h(r) \\ ~&=~\iint_{\mathbb{R}^2} \! \frac{\mathrm{d}^2r}{2\pi} \cos\left({\bf r}\cdot{\bf k} \right)h(r) \\ ~&=~\int_{0}^{\infty} \! \mathrm{d}r~r J_{0}(kr) h(r) \tag{1} \end{align}$$ for suitable functions $h$ that are independent of the polar variable $\theta$, cf. integral (9.1.18) in Ref. 3, Wikipedia, and above comment by Hans Engler. However, we shall take a different route in this answer. II) As a warmup to OP's question, consider the following function$^1$ $$g({\bf r})~=~\frac{1}{r^2+m^2}, \qquad {\rm Re}(m)~>~0. \tag{2}$$ The 2D Fourier transform reads $$ \hat{g}({\bf k}) ~=~\iint_{\mathbb{R}^2} \! \frac{\mathrm{d}^2r}{2\pi} \frac{\cos\left({\bf r}\cdot{\bf k} \right)}{r^2+m^2} ~=~\left. \int_{\mathbb{R}}\! \frac{\mathrm{d}x}{2\pi} \cos\left(xk \right) \int_{\mathbb{R}}\! \frac{\mathrm{d}y}{y^2+E^2} \right|_{E=\sqrt{x^2+m^2}}$$ $$~=~\left. \int_{\mathbb{R}}\! \frac{\mathrm{d}x}{2\pi} \frac{\cos\left(xk \right)}{2iE} \int_{\mathbb{R}}\! \mathrm{d}y\left( \frac{1}{y-iE} -\frac{1}{y+iE} \right)\right|_{E=\sqrt{x^2+m^2}}$$ $$~=~\left. \int_{\mathbb{R}}\! \frac{\mathrm{d}x}{2\pi} \frac{\cos\left(xk \right)}{2iE} \left[ {\rm Ln}(y-iE) -{\rm Ln}(y+iE) \right]_{y=-\infty}^{y=\infty}\right|_{E=\sqrt{x^2+m^2}}$$ $$~=~\int_{\mathbb{R}}\! \frac{\mathrm{d}x}{2} \frac{\cos\left(xk \right)}{\sqrt{x^2+m^2}}~=~K_0(m k)~\sim~\sqrt{\frac{\pi}{2km}}e^{-km}\quad\text{for}\quad k~\to~ \infty, \tag{3}$$ where we in the last equality used integral (9.6.25) in Ref. 3. Here $K_0$ is the modified Bessel function of 2nd kind. III) Now let us return to OP's question. From the partial fraction decomposition $$f({\bf r})~=~\frac{1}{r^6+1} ~=~\frac{1}{3}\sum_{n=-1}^1 \frac{\omega^{2n}}{r^2+\omega^{2n}},\qquad \omega~:=~\exp\left[\frac{i\pi}{3}\right]~=~\frac{1+i\sqrt{3}}{2},\tag{4}$$ the 2D Fourier transform reads $$ \hat{f}({\bf k}) ~=~\iint_{\mathbb{R}^2} \! \frac{\mathrm{d}^2r}{2\pi} \frac{\cos\left({\bf r}\cdot{\bf k} \right)}{r^6+1} ~=~\frac{1}{3}\sum_{n=-1}^1 \omega^{2n}K_0(\omega^n k) $$ $$\sim~\frac{1}{3}\sqrt{\frac{\pi}{2k}}\left(e^{-k}+2e^{-k/2}\sin\left(\frac{k\sqrt{3}}{2}\right)\right)\quad\text{for}\quad k~\to~ \infty, \tag{5}$$ which is our main result. IV) Finally in Table 1 below we check numerically the asymptotic expansion (5) (third column) compared to the exact formula (fourth column). In the second column we have calculated the characteristic sine factor from OP's Refs. 1 & 2. Note that Refs. 1 & 2 get the wrong sign, which can not be explained away by a different normalization convention. $\downarrow$ Table 1. $$ \begin{array}{ccccccc} \text{Wave number } k&& \frac{2}{3}\sqrt{\frac{\pi}{2k}}e^{-k/2}\sin\left(\frac{k\sqrt{3}}{2}-\frac{\pi}{6}\right)&& \frac{2}{3}\sqrt{\frac{\pi}{2k}}e^{-k/2}\sin\left(\frac{k\sqrt{3}}{2}\right) &&\text{Exact} ~\hat{f}(k) \\ \\ 4 &&1.1 \cdot 10^{-2} && -1.8 \cdot 10^{-2}&& -1.3 \cdot 10^{-2} \\ 11 &&4.2 \cdot 10^{-4} && -1.0 \cdot 10^{-4} && -9.2 \cdot 10^{-5} \\ 15 &&-1.2 \cdot 10^{-5} && 4.9 \cdot 10^{-5} && 4.8 \cdot 10^{-5} \\ 22 &&-9.4 \cdot 10^{-7} && 6.0 \cdot 10^{-6}&& 5.8 \cdot 10^{-6} \\ \end{array} $$ Conclusion: Taking into account possible different normalizations of the 2D Fourier transform, the main formula (5) does not agree with OP's Refs. 1 & 2, not even as an asymptotic large $k$ expansion. References: X. Antoine & R. Duboscq, Computer Physics Communications 193 (2015) 95; eq. (5.43). C.-H. Hsueh, T.-C. Lin, T.-L. Horng, & W.C. Wu, Phys. Rev. A 86 (2012) 013619; p. 3. Abramowitz & Stegun, Handbook of Mathematical Functions. -- $^1$ Formulas (2) and (3) are well-known in physics as the Euclidean 2D propagator/Greens function for a massive field with mass $m$, although the roles of the Fourier variables ${\bf r}\leftrightarrow {\bf k}$ are reversed.
{ "pile_set_name": "StackExchange" }
Q: storing complex data type in roaming settings What I want: I'm trying to store complex data types in roaming settings. This is how my object looks like: public abstract class Query { [DataMember] public Cube Cube { get; private set; } [DataMember] public List<Filter> Filters { get; private set; } [DataMember] public Slicer Slicer { get; set; } } What is the problem: Query q = ...; RoamingSettings.Values["query"] = q; is giving an error: Data type not supported What I have tried: Storing different members of Query class in different fields of composite settings. But the data members of Query class are again objects of different classes and hence cannot be stored in composite.Values["setting"]. Please refer: windows 8 app roaming storage with custom class. That question was answered by using the composite setting but is not applicable to mine. How do I proceed? A: Ankush, Looks like you are trying to shove a collection of custom objects into RoamingSettings, which is not quite what it is meant for. Local/Roaming Settings are stored usually in Registry and meant for simple name-value pairs. How about this - you take your entire object model and flatten it out for storage as a File? This way, you can easily serialize/deserialize your data and hydrate/dehydrate your object model in your App when needed. Also, the flattened content can be saved in the Roaming Folder for syncing across multiple user devices. Simply annotate your custom object properties as needed and use the DataContractSerializer to flatten/unflatten your data and persist an XML file in Roaming Folder. Just do not depend on an instant cloud sync; Windows will sync the file in Roaming Folder opportunistically. This MSDN quickstart should help: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700362.aspx Thanks!
{ "pile_set_name": "StackExchange" }
Q: TFS or other Bug Tracking Suggestions I currently work for a small web development company that provides an online ASP.NET web application. Currently we handle bugs by sending out an email to all of our developers and having them look into them manually. What we're looking for is a more automated way of tracking and monitoring this process by actually categorizing and reporting to management the types and quantity of bugs coming in on a weekly/monthly/quarterly basis. We have a Customer Facing help desk that monitors the types of Support Requests come in and the frequency and from this data we create our reports. Ideally what we'd like is a bug tracking system that allows us to gather this same type of data around the bugs that are in our system. Management is looking for a report that we can generate showing frequency and occurrence of different types of bugs. Is there a way to use TFS for this? A: There are many systems that can do what you are looking for, including Visual Studio ALM (TFS). It really depends on what else you want as well. http://nakedalm.com/why-should-i-use-visual-studio-alm-whether-tfs-or-vso/ If you only want bug tracking and you don't keep your code in source control, or don't manage your requirements then you can use TFS. However you would also get value from associations between code and bugs. Can you, or do you want to, answer: What parts of my code generate the most bugs?
{ "pile_set_name": "StackExchange" }
Q: Stata and Named Pipes Instead of decompressing via a temporary file, I can use named pipes to read .csv.gz and .dta.gz files directly in Stata as explained here. I have two questions about how to use named pipes in Stata in case someone is knowledgeable about them. The help advises to do the following (edit: which indeed works for me) #!/bin/sh fname=$1 rm -f mypipe.pip mknod mypipe.pip p zcat $fname > mypipe.pip & !myprog testfile.Z >& /dev/null < /dev/null infile a b c using mypipe.pip I'd like to understand why the following code does not work. !rm -f mypipe.pip && mknod mypipe.pip p && zcat filename.gz > mypipe.pip & infile a b c using mypipe.pip Is there is a similar way to use named pipes when saving and gzipping .dta files? I have tried to replicate the code above but without success. A: Edit: It's because you haven't recreated the code as called in the bash file + the stata do file. You've just done the bash file. Your code should read: !rm -f mypipe.pip && mknod mypipe.pip p && (zcat filename.gz > mypipe.pip &) >& /dev/null < /dev/null infile a b c using mypipe.pip If you could post what errors you're getting as per Nick's suggestion about clearing up what "does not work" means that would be helpful. In any case there are a few things you should try first (1) Create a bash script as per your link to the Stata website instead of trying to do it on one line (2) Make sure your filename has no spaces, or put double quotes around $fname (3) Make sure to chmod 775 /path/to/myprog to make it executable if you run *nix (4) Make a do file as per your link again (5) Put a pound sign after testfile.Z like the following : !myprog testfile.Z #>& /dev/null < /dev/null infile a b c using mypipe.pip this allows output to go to standard output so you can see whats going on. you can remove this after the problem is diagnosed. (6) Change the !myprog to !/path/to/myprog (7) Execute do mytest.do (8) Tell us what Stata is saying the error is if any remain. It works on my machine with .csv files so long as you specify all the variable names after infile, haven't got it to work with dta files. Here is the procedure First make a bash file called myprog as recommended #!/bin/sh cd /path/to/dir fname=$1 rm -r mypipe.pip mknod mypipe.pip p zcat $fname > /path/to/dir/mypipe.pip & make the script executable by typing in a terminal: `chmod 775 /path/to/dir/myprog' Then make a do file. I have a dataset called complete which I used to test the principal cd /path/to/dir insheet using complete.csv ds * global vars "`r(varlist)'" !7z a test.csv.gz complete.csv !/path/to/dir/myprog test.csv.gz >& /dev/null < /dev/null infile $vars using mypipe.pip, clear Success. I'm running Debian Linux Wheezy (actually #! but same deal), using Stata version 12
{ "pile_set_name": "StackExchange" }
Q: append bytes to string in java I have to deal with ascii structured file, I need to put these two constant bytes to the end of every line so that I can respect the file structure that was gave me: private final static int ENDRECORD = 0x0d; private final static int ENDLINE = 0x0a; I don't know if it's the classic "\n", is there a way I can put these two variables at the end of a string? Like: String line = line + ENDRECORD + ENDLINE; //I now this is wrong A: You're close. It's '\r' and '\n'. System.out.println((int) '\r'); System.out.println((int) '\n'); Output: 13 10 which is 0x0d and 0x0a, respectively. Use chars: private final static char ENDRECORD = '\r'; private final static char ENDLINE = '\n'; and String line = line + ENDRECORD + ENDLINE; Additionally, you can use StringBuilder for efficiency instead of concatenation. It's not necessary to get this to work, but it's standard to use it for building strings instead of concatenation with +.
{ "pile_set_name": "StackExchange" }
Q: Getting Count() for basic IQueryable instance I need to determine at runtime which view to populate recordSet from. However when I declare recordSet as IQueryable I lose access to functions like Count(). If I declare recordSet as IQueryable<View_A> then I have access, but I've locked in the type. Is there some more generic type I could use with IQueryable? IQueryable recordSet; if (Flag) recordSet = db.View_A.Where(v => v.ID == Id); else recordSet = db.View_B.Where(v => v.ID == Id); int recordCount = recordSet.Count(); //complains about Count(); A: The Count extension is meant for IQueryable<> type, which is why you cannot use it on IQueryable. However, covariance should allow your code to work if you declare your recordset this way: IQueryable<Object> recordSet; As noted by @hvd in the comments below, covariance here would only work with reference types.
{ "pile_set_name": "StackExchange" }
Q: How to use Formik ErrorMessage properly with formik using render props and design library for inputs? I want to trigger formik errors and touched whenever the input is clicked and the value is not correct . I pass formik props to the input component like this : const initialValues = { title: '' }; const validationSchema = yup.object({ title: yup.string().max(50, 'less than 50 words !!').required('required !!') }); function Add() { <Formik initialValues={initialValues} onSubmit={onSubmit} validationSchema={validationSchema}> {(props) => { return ( <Form> <AddTitle props={props} /> </Form> ); }} </Formik> ); } Here I'm trying to display error message whenever the input is touched and there is an error with it like this : import { Input } from 'antd'; function AddTitle(props) { console.log(props.props); return ( <Field name="title"> {() => { return ( <Input onChange={(e) => { props.props.setFieldValue('title', e.target.value) }} /> ); }} </Field> <ErrorMessage name="title" /> <P> {props.props.touched.title && props.props.errors.title && props.props.errors.title} </P> </React.Fragment> ); } But ErrorMessage and the paragraph below it doesn't work when the input is touched and empty . In console log it shows that input doesn't handle formik touched method and it only triggers the error for it : touched: __proto__: Object errors: title: "less than 50 words !" __proto__: Object How can I use ErrorMessage properly while passing in formik props to a component and using a third library for inputs ? A: Fixed the issue by adding the onBlur to the input and ErrorMessage is working fine : <Field name="title"> {() => { return ( <Input onBlur={() => props.props.setFieldTouched('title')} onChange={(e) => { props.props.setFieldValue('title', e.target.value); }} /> ); }} </Field> <P class="mt-2 text-danger"> <ErrorMessage name="title" /> </P>
{ "pile_set_name": "StackExchange" }
Q: Calling a stored procedure from a stored procedure in Cosmos Document DB? Is it possible to call one stored procedure from another stored procedure with Azure Cosmos DB (document DB)? If so, how? A: It's not supported but you can include user defined functions in your queries so with some creativity you can often get what you want. The design pattern most people use when they need to call multiple SPROCS is to use a message bus to trigger the later calls.
{ "pile_set_name": "StackExchange" }
Q: How often should I fertilize my lawn? How often should I fertilize my lawn? Should I follow a certain schedule? I have heard of people fertilizing on around holidays [US: Easter (sometime in April), Memorial day (last week of May), fourth of July, Labor day (first week of September)]. A: My decades ago hort 101 class said fertilizer is not really necessary if you use a mulching mower. If you bag the clippings or if you want thicker greener lawn you can apply fertilizer up to 3 times per year. The applications should be timed to catch the grass growing but not the weeds. Here in central Iowa with bluegrass/ryegrass/fescue lawns the grasses go brown/dormant during the hot part of the summer (July, August) and grow most vigorously in the cooler spring and fall. The weeds go nuts in the spring (April, May, June) - we do not want to encourage that! So the fertilization schedule works out to once in the first 1-2 weeks in September, again 2-3 weeks after that and (very optionally!) once in the early spring just after the ground thaws (first 1-2 weeks in April). A: Below are a few quotes from this answer I posted here on SE. Hopefully you find them of some benefit: Seeing as my lawnmower is a mulching mowing, I leave all the grass clippings on the lawn (free, natural fertilizer), except with first cut and last cut of the season. I collect up those cuttings and dispose of them via a community yard waste pile. Fertilize the lawn with corn gluten meal (by Bradfield because I can get it easily locally) in very early Spring, when I see the Forsythia shrub in flower in my area. For the first time this year I also decided to fertilize the lawn with corn gluten meal in mid June. Why? See "Table 4" here: Cool-season grasses: Application schedule for organic fertilizers Corn gluten meal isn't a "magic bullet" for controlling unwanted weeds (plants). I've read and been told that it can take at least 2 to 3 years (following recommended application rates on yearly bases) before seeing any results with this method. I make 5 gallons of compost tea each week (from late Spring to earlier Autumn "Fall") and apply the 5 gallon batch to the front garden one week, then the following week apply a new fresh 5 gallon batch to the back garden. I repeat that cycle for the period given previously. I have been doing this for 2 years now, and without question I have noticed a massive increase in worm activity eg lots of worm castings on the surface of the soil. I spread the 5 gallons of Compost Tea via a watering-can over approx 1800ft² (170m²). Lawn area is about the same front & back for me. So one week the front lawn gets treated, then the following week the back lawn gets treated, repeat, repeat... Around "Labor Day" (beginning of September, early Autumn "Fall") here in the US, I prepare any bare spots for reseeding. Reseed using an appropriate seed for my lawn type. Cover the whole lawn with ½ to 1 inch (12.5 to 25mm) thick layer of STA-certified compost (bought in bulk locally). Water as needed, ie Amount needed for good germination to take place. Fertilize the lawn with Ringer Lawn Restore (by Woodstream Corp) at the end of September, early October. You may also find the actual answer I pointed to above of some help: What's an organic way to discourage crabgrass from a large “lawn”? A: In upstate NY here - I usually fertilize mine once in Spring (late in May) once in the summer (around mid-July) and once in the Fall (around mid-Sept) and it seems to do the trick just fine.
{ "pile_set_name": "StackExchange" }
Q: What is the name of this circuit? simulate this circuit – Schematic created using CircuitLab I've tried to Google it but my keywords don't really yeild anything. I'd like to read more about this type circuit ; what applications its useful in ? How to select C1 ? From what I recall, it provides a DC gain of 1, but provides an AC gain set by the feedback resistors. Does it have a name ? Added I should have emphasized that the focus for this question is C1 and its location in the circuit. A: Yes - it has a name. In control theory this circuit is known as a PD-T1 unit. It has a proportional-derivative behaviour with a certain delay term T1. In filter terms, it works like a first-order high-pass with a superimposed constant gain. The transfer function is \$H(s)= 1 + sR1 \cdot \dfrac{C}{1+sR2C}\$ This device is used to enhance the phase (for stabilizing purposes) in a certain frequency range. Please note that application as a PD-T1 element requires \$R1>R2\$. More than that, the shown circuit is used as a simple non-inverting amplifier (gain: \$1+R1/R2\$) for single-supply operation. For this purpose, the non-inv. input is dc biased with 50% of the supply voltage - with the consequence that the input signal must be coupled via an input capacitor. Because the dc gain remains unity, the bias voltage is transferred to the output also with the gain of "1". BODE diagram: The magnitude starts at unity and begins to rise at \$wz=\dfrac{1}{(R1+R2)C}\$, then it stops rising at \$wp=1/R2C\$ at a gain value of \$1+(R1/R2)\$. The rising of the gain is connected with a corresponding phase enhancement. Because of the mentioned phase enhancement properties the PD-T1 block is also known as a "lead controller". A: I'd just call that a non inverting amplifier. Calculating the transfer function is quite easy if we can consider the op amp ideal. In DC C1 is open, so you don't have current in R1 nor R2, so the op amp is in the buffer configuration and the gain is 1. When f gets very big C1 is closed, the gain of the circuit is the usual 1+R1/R2 leading to a 2 gain for your values. You then expect a finite pole and a finite zero, the zero comes first than the pole kicks in. You can calculate the pole with the "seen resistance" method: C1 sees R1+R2 so \$\omega_p=\frac{1}{(R_1+R_2)C_1}\$. You can now calculate the zero pulsation as \$\omega_z=\omega_p\frac{A_0}{A_\infty}=\omega_p\frac{1}{2}\$
{ "pile_set_name": "StackExchange" }
Q: Rails check if the value corresponding to a hash key is an empty array A function in a rails 3 app returns the following hash {:"white-wines"=>[]} which I want to treat as a false result (meaning that if the hash value is an empty array I want to skip it). How can I achieve the above? A: Array#empty? and Hash#[] are the methods you need to look into. h = {:"white-wines"=>[]} puts "empty" if h[:"white-wines"].empty? #= > empty
{ "pile_set_name": "StackExchange" }
Q: What is the difference between BigInt and "Computer Algebra System" integers? Obviously I imagine a CAS does more than BigInt does. But I'm wondering if there is a difference in implementation between BigInt integers and CAS integers (whatever they may be, symbols?). Wondering because I would like to implement a robust math system eventually and am not sure yet if BigInt would be pointless if you had a CAS. What is the major difference between implementations of BigInt vs. CAS integer? A: Basically, a BigInt type is a CAS that knows only integers. Any CAS will include something very similar to a BigInt. But in addition to that, it needs to understand all the other objects and operations, and how they interact. The point of a CAS is that it implements the actual mathematical definitions instead of relying on hardware-supported types that are very fast but have implicit rounding or overflows.
{ "pile_set_name": "StackExchange" }
Q: How to make Smart Icon Animations (when Launch and Exit Apps) in Android? Smart Animated Icons is one of the Highlighted Features of MIUI 9.You can see the New Animation when you Launch and Exit Apps. Open/Launch the App and You can notice the Animation on its Icon when you exit the App. Animation seems to be cool and it gives you a live Experience as if Icons are Live. Take a look at the below GIFs to see the Animation on Icons. Facebook Smart Icon animation exmaple. Settings app Smart Icon animation For more smart App icon Animation understanding and information please check this link Smart Icon Animation 1) how to achieve this same features ? How can I do it in my app? 2) Android SDK that supports dynamic app icons ? is it possible to achieve this using <activity-alias> ? A: Yes, these are Smart Icon animations introduced in MIUI 9. MIUI does the icon animation by itself upon enabling it from system settings as mentioned here on Xiomi MIUI Offical forum. It happens only for some system apps and some famous social media platforms as of now, may happen for other famous app icons in the future too. But as they mentioned in the link, it is a part of the MIUI 9.0, and is not part of Android SDK. I too wish they include this feature as part of Android SDK to be shipped with the application. It would be intriguing.
{ "pile_set_name": "StackExchange" }
Q: Android @NonNull usefulness After a few reading and questions like this one I was wondering if there was a point in using @NonNull Android Support Annotation. I can see a very small warning from Android Studio if I attempt to call a method with a null parameter that is annotated as @NonNull. Just a warning?? What about Unit Testing ? Should I test the method with a null paramter? If I do ... I will get a NullPointerException and my test will fail. Let's say we are two developers. One working on the API and one testing the API in all kind of manners. As the second developer, it's my responsibility to test everything so that the API is bullet-proof. That's the whole point of Unit Testing, right ? So then ... what's the point of the first developer using @NonNull ? If someone else were to use this API with a null parameter ... then the API would throw a NPE. He then would think : "Urg, that API sucks... NPE !" and he would be right. That naughty dev for not checking if the parameter he sent is null or not should be faced with an IllegalArgumentException because it's his fault not that of the API's! Am I wrong ? I thought these annotations would enforce the compiler to show errors like attempting to call methodName(@NonNull Object object) with null parameter. Update 1 Alright thank you all for your comments. I'd like to summ up if possible regarding the "issue" I am facing here. In an abstract way. I write some code (an API, a Library, a Class, whatever) with private internal code wrapped by public methods that provides features. Assume these public methods will be used by anyone else (including me). Some of them take arguments that must never be null or else all hell breaks loose. Reading your comments, I am facing the following options : Keep on using contracts / annotations (@NonNull) supported by Java Documentation stipulating parameter must not be null. Don't check for null parameters (or else IDE will warn me) and, somehow, pray that I will never receive a null parameter ; Same as above, but enforce a null check (even though IDE will warn that condition will always be false) and throw IllegalArgumentException instead of causing an NPE in case I receive a null parameter ; Stop using contracts / annotations, use Java Doc to warn others dev and add manual check for all parameters. Finally, for unit testing ... I know I can not have bullet-proof code, but I like to "monkey-test" my code as much as possible to prevent unexpected behavior from my code as well to validate the process (which is at the base of Unit Testing, I believe)- A: Its main purpose is informational to your coworkers. One person is never the sole programmer of a large project. Using NotNull tells other programmers that the contract of the function means you can never send a null to it, so they don't do it. Otherwise I may make a logical assumption that calling setFoo(null) will clear Foo, whereas the API can't handle not having a Foo.
{ "pile_set_name": "StackExchange" }
Q: How can I make an array that holds types? I am trying to create an array that holds the class of the custom collectionView cell I would like to deque. Below I have provided an example of how I would like to use this array. cellType is a variable holding the class I would like to deque and cellClass is an array holding different classes. I have seen similar questions to this but all the answers seem to suggest using the an instance of the class such as className.self. Is it possible to create an array like this. Thank You. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cellType = cellClass[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! cellType cell.addRemoveCellDelegate = self cell.label.text = "\(indexPath)" switch indexPath.item { case 0: cell.backgroundColor = .magenta cell.screenLabel.text = screens[0] case 1: cell.backgroundColor = .purple cell.screenLabel.text = screens[1] case 2: cell.backgroundColor = .yellow cell.screenLabel.text = screens[2] case 3: cell.backgroundColor = .green cell.screenLabel.text = screens[3] default: cell.backgroundColor = .blue } return cell } A: First of all I suggest you to create a manager file. import Foundation class CollectionViewManager: NSObject { public var cells: [CellModel] = [] override init() { super.init() fillCells() } fileprivate func fillCells() { let arrayCellModels: [CellModel] = [ RowModel(type: .cellOne, title: "My First Cell"), RowModel(type: .cellTwo, title: "My Second Cell"), RowModel(type: .cellThree, title: "My Third Cell") ] arrayCellModels.forEach { (cell) in cells.append(cell) } } } protocol CellModel { var type: CellTypes { get } var title: String { get } } enum CellTypes { case cellOne case cellTwo case cellThree } struct RowModel: CellModel { var type: OptionsCellTypes var title: String init(type: CellTypes, title: String) { self.type = type self.title = title } } After that in your ViewController you should initialise your manager. Something like that. class ViewController: UICollectionViewController { let collectionViewManager = CollectionViewManager() // your code here } Next you make an ViewController extension. extension ViewController: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // number of items from your array of models return collectionViewManager.cells.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // init item let item = collectionViewManager.cells[indexPath.item] // than just switch your cells by type switch item.type { case .cellOne: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellOne.self), for: indexPath) as! CellOne { cell.backgroundColor = .red return cell case .cellTwo: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellTwo.self), for: indexPath) as! CellTwo { cell.backgroundColor = .blue return cell case .cellThree let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellThree.self), for: indexPath) as! CellThree { cell.backgroundColor = .yellow return cell } } }
{ "pile_set_name": "StackExchange" }
Q: Whats the connection in a ServiceBusTrigger? What is the connection that needs to be defined with my service bus trigger (topic) for my Azure Function? The Run looks like this public static void Run([ServiceBusTrigger("testtopic", "testsubscription", AccessRights.Manage, Connection = "")]string mySbMsg, TraceWriter log) Is it the connection string for the Policy under Shared access policy of the ServiceBus (Endpoint:sb://...)? A: Connection is the name of a variable which contains connection string to a bus. You need to keep this variable in Application Settings of your Function App (accessible through the portal) and locally in local.settings.json - {"Connection" : "Endpoint..."}
{ "pile_set_name": "StackExchange" }
Q: Difference Reserved Class B Networks 192.168 vs 172.16 So I understand that there used to be classful addresses allocated depending on the first octet of an IP a long time ago. Of those classes, private IP address ranges were given in each. Class A 10.*.*.* Class B 172.16-31.*.* Class C 192.168.0-255.* I understand that according the RFC 1918, because 192.168 technically starts in the class C range, it should be considered 256 class C networks. However, because there are 256 available class C networks in 192.168.xxx.xxx, would it be incorrect to refer to this as 1 class B network? A: A 'network' or 'subnet' is a set of ip-numbers that can connect to each other without the use of a router. A class C network has a maximum of 256 such ip-addresses. To get from one subnet to another subnet, a router is required. You can not call the 192.168.xxx.yyy block a single class B subnet, because the hosts at 192.168.1.xxx cannot directly connect to hosts in 192.168.2.xxx. The hosts are in different subnets. 192.168.xxx.yyy is an ip-block of 256 private class C networks. Classed networks assume fixed network masks for particular ip-ranges. So, for the networks in block 192.168.xxx.yyy, classed-only network software will set the network mask to be equivalent to 255.255.255.0 (or /24). Today most network software ignores the class of the network and will require a network mask for all ip number blocks. For instance, you can use 192.168.0.0 to 192.168.3.255 as a single classless subnet containing 1024 ip-addresses if you use network mask 255.255.252.0
{ "pile_set_name": "StackExchange" }
Q: How to Limit Object inside Transparent Rectangle Area - FabricJS? I am implementing designer functionality using FabricJS in my side. My Idea is to set the background image using setBackgroundImage from fabric, also i add specific area of transparent rectangle with size and position fetch from JCrop. Now come to my question, i want to restrict the object placement within that specific area of transparent rectangle. Let say i want to add text/image/shapes that should be in that limited area, i able to implement the background image, position of transparent rectangle and even circle shape object but i unable to find details to limit object place it inside transparent rectangle and only in that region. Here is my below code and working fiddle, If you see it in fiddle the image where you need to select the cropping portion and below that canvas background with transparent rectangle which is the one of same like crop selection. Now i want to limit the object placement anything to be in that transparent rectangle, right now i can place object in anywhere in the canvas. HTML <img src="https://images.unsplash.com/photo-1595438337199-d50ba5072c7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=330&q=80" id="target"> <div class="canvas-container" style="position: relative; user-select: none;"> <canvas id="c1" width="600" height="600" style="border:1px solid #ccc; position: absolute; left: 0px; top: 0px; touch-action: none; user-select: none;"></canvas> </div> JS function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) { var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return { width: srcWidth * ratio, height: srcHeight * ratio, aspectratio: ratio }; } jQuery(function($) { //alert("Testing"); var img = new Image(); img.onload = function() { var data = calculateAspectRatioFit(this.width, this.height, '400', '600'); console.log(data); jQuery('#target').attr('width', data.width); jQuery('#target').attr('height', data.height); jQuery('#pdr-drawing-area').html("Aspect Ratio: " + data.aspectratio); const stage = Jcrop.attach('target'); stage.listen('crop.change', function(widget, e) { const pos = widget.pos; console.log(pos.x, pos.y, pos.w, pos.h); //fabric js var canvas = new fabric.Canvas('c1'); var center = canvas.getCenter(); var img = 'https://images.unsplash.com/photo-1595438337199-d50ba5072c7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=330&q=80'; canvas.setBackgroundImage(img, function() { canvas.backgroundImage && canvas.backgroundImage.scaleToWidth(data.width); canvas.backgroundImage && canvas.backgroundImage.scaleToHeight(data.height); //canvas.sendToBack(img); canvas.renderAll(); }); console.log(pos.x * data.aspectratio); var rect = new fabric.Rect({ left: pos.x, top: pos.y, fill: 'transparent', width: (pos.w), height: (pos.h), strokeDashArray: [5, 5], stroke: "black", selectable: false, evented: false, //visible: false }); canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: pos.y + 2, left: pos.x + 2 })); canvas.add(rect); canvas.setHeight(data.height); canvas.setWidth(data.width); canvas.renderAll(); }); }, img.src = 'https://images.unsplash.com/photo-1595438337199-d50ba5072c7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=330&q=80'; }); A: Here is an example of how to restrict movement in FabricJS. I'm using the stateful property of the canvas, see function objectMoving below. var canvas = new fabric.Canvas("canvas"); canvas.stateful = true; function inside(p, vs) { var inside = false; for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) { var xi = vs[i].x, yi = vs[i].y; var xj = vs[j].x, yj = vs[j].y; var intersect = yi > p.y !== yj > p.y && p.x < ((xj - xi) * (p.y - yi)) / (yj - yi) + xi; if (intersect) inside = !inside; } return inside; } function getCoords(rect) { var coords = [] coords.push(rect.aCoords.tl); coords.push(rect.aCoords.tr); coords.push(rect.aCoords.br); coords.push(rect.aCoords.bl); coords.push(rect.aCoords.tl); return coords; } function objectMoving(e) { var cCoords = getCoords(parent); var inBounds = inside({ x: e.target.left + 30, y: e.target.top + 30 }, cCoords); if (inBounds) { e.target.setCoords(); e.target.saveState(); } else { e.target.left = e.target._stateProperties.left; e.target.top = e.target._stateProperties.top; } } var boundary = new fabric.Rect({ width: 310, height: 170, left: 5, top: 5, selectable: false, strokeDashArray: [5, 2], stroke: "blue", fill: "transparent" }); var parent = new fabric.Rect({ width: 250, height: 110, left: 35, top: 35, selectable: false, strokeDashArray: [2, 5], stroke: "black", fill: "transparent" }); var child = new fabric.Circle({ radius: 30, fill: "rgba(255,0,0,0.8)", top: 50, left: 50, hasControls: false, }); canvas.add(boundary); canvas.add(parent); canvas.add(child); canvas.on("object:moving", objectMoving); <canvas id="canvas" width="400" height="180"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script> In the function inside I'm using the ray-casting algorithm, you can read more about it here: https://github.com/substack/point-in-polygon/blob/master/index.js I prefer this algorithm because it opens the door for later allowing more complex shapes as the parent boundaries, it can work with a polygon of any shape. If you need any clarifications on that code let me know. Now you do need to integrate that into your project and dynamically change the parent boundaries as they change in the user in the "JCrop" selection
{ "pile_set_name": "StackExchange" }
Q: Уточняющий оборот Нужна ли запятая в скобках? Если бы предложение было построено чуть-чуть по-другому: регуляторы, использующие, также как и регуляторы прямого действия, энергию регулируемой среды, то оборот нужно было бы выделять обязательно. А если он стоит перед причастным оборотом? Появились регуляторы, также как и регуляторы прямого действия (,) использующие энергию регулируемой среды, но с усилителями, началось производство регуляторов косвенного действия, содержащих регулирующие клапаны и использующих для своей работы дополнительные источники энергии. A: Запятой не нужно, imho. А "так же" пишется раздельно в данном случае. Появились регуляторы, так же как и регуляторы прямого действия использующие энергию регулируемой среды, но с усилителями, началось производство регуляторов косвенного действия, содержащих регулирующие клапаны и использующих для своей работы дополнительные источники энергии. Ещё на мой взгляд, предложение лучше разбить на два: Появились регуляторы, так же как и регуляторы прямого действия использующие энергию регулируемой среды, но с усилителями. Началось производство регуляторов косвенного действия, содержащих регулирующие клапаны и использующих для своей работы дополнительные источники энергии.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to add images programmatically? I have a web service where I read various information from. One of these pieces of information is the name of an image. I have all the images stored locally in the drawables folder. What I have done right now is I read the string of the image I need from the web service. I want to use this string name and insert the image with the same string name from my drawable folder. Is this possible to do? Is it possible to do the following somehow? //Setup the image ImageView spotIvIcon = (ImageView)findViewById(R.id.spot_selected_image); String temp = "R.drawable."+spotImage; spotIvIcon.setImageResource(R.drawable.beer); What I do with the temp string. Is it possible to convert this string into the int I need? I have the beer in there just to test something out. Thanks A: So I found out how to do this. If anyone wanted to know how it's done use the following code: int path = getResources().getIdentifier(spotImage, "drawable", "com.androidpeople.tab"); spotIvIcon.setImageResource(path); Where: spotImage is the name of your string drawable is the type you want com.androidpeople.tab is your package name Works like a charm now.
{ "pile_set_name": "StackExchange" }
Q: Is there an Updatepanel control (like ASp.net) in java Im basically a .net developer, I am now working on a java web project, here i need to basically get values from the back end (say generating a random number) and update that random number every second on the front end, i want to use jquery for this, in ASP.net, i know that I can have an updatepanel and use _doPostBack to update the panel without refreshing the whole page. It might be a stupid question but im a java newbie. Any help/examples of something that does the same would be greatly appreciated. Thanks. A: In Java you would do something like this with JSF and a rendering kit like MyFaces or IceFaces. A .NET developer would need considerable time to learn these technologies. If you are going to use both .NET and Java, I recommend to invest some time to learn jQuery and client programming really well. This knowledge can serve you in both worlds. It is a trivial task to implement UpdatePanel functionality with jQuery. Just create a service that returns the content and load it with $.load().
{ "pile_set_name": "StackExchange" }
Q: ¿Comandos equivalentes a `nice` y `cpulimit`para windows 7? Quiero limitar el acceso de mis programas a los recursos del equipo para evitar que se quede colgado y así poder seguir trabajando en otras cuestiones mientras se ejecutan los programas en un segundo plano. Estoy buscando una forma genérica de hacerlo independientemente de cómo sean mis scripts. He visto que para quienes trabajan sobre Linux existen las opciones nice y cpulimit, pero yo trabajo sobre win7 (cambiar a Linux no es una opción ya que no soy yo quien decide la configuración del pc que uso). ¿Qué opciones tengo trabajando sobre windows para lograr un resultado equivalente a nice y cpulimit en win7? A: He desarrollado una función a partir de varios ejemplos que he visto en diferentes webs. Se puede utilizar indistintamente si trabajas sobre Windows o sobre Linux. Además, he implementado la opción de poder establecer el nivel de prioridad a traves de los parámetros pasados a la función, de modo que no solo se pueda reducir la prioridad, si no también incrementarla. El valor por defecto de los parámetros es aquel que corresponde a prioridad "normal" import win32api import win32process import win32con import sys import os def set_priority(win_n=2, py_n=0): """ Establece la prioridad del proceso. Es independiente del sistema operativo. Parameters ---------- win_n: int Determina el nivel de prioridad del proceso. py_n: int Determina el nivel de prioridad del proceso. """ # # Determinamos el sistema operativo y la version. try: sys.getwindowsversion() except AttributeError: isWindows = False else: isWindows = True # if isWindows: # Almacenamos los diferentes niveles de prioridad en una lista. prior_classes = [win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS] # Obtenemos el identificador del proceso, del proceso de llamada. # https://msdn.microsoft.com/en-us/library/windows/desktop/ms683180(v=vs.85).aspx pid = win32api.GetCurrentProcessId() # Abre un objeto de un proceso local existente. # https://msdn.microsoft.com/es-es/library/windows/desktop/ms684320(v=vs.85).aspx handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) # Establecemos la prioridad del proceso. # https://msdn.microsoft.com/es-es/library/windows/desktop/ms686219(v=vs.85).aspx win32process.SetPriorityClass(handle, prior_classes(win_n)) # else: os.nice(py_n) EDIT: Adjunto enlace a una web con otros ejemplos similares,
{ "pile_set_name": "StackExchange" }
Q: How to show/reveal hidden or invisible characters in NetBeans? How can you show/reveal hidden characters in NetBeans? In other editors, if this feature is turned on, a space might be shown as a small centered dot, and a tab as a right arrow. (This feature is useful to see if a file uses tabs or spaces for indentation, among other things.) A: This feature was missing for a long time—a feature request was created on November 1999 and it was finally implemented on August 2010 (NetBeans 6.10). You can enable/disable it at "View → Show Non-printable Characters". Bug history As of NetBeans 7.0.1, the definition for "non-printable" seems to include tabs and carriage returns but not regular white space char: NetBeans 7.1.0 finally displays spaces. However, now it has a new bug where consecutive tabs (or tabs & spaces combinations) collapse into one tab: NetBeans 7.4.0 fixes this: There're yet a couple of issues: The end of file is represented with the same symbol as line feeds, thus making it non-obvious to determine whether the file ends with EOL. Hidden chars are displayed in the same colour as regular text. These issues have not been addressed so far but they can be sort of mitigated with the Editor Whitespace third-party plugin, which: Hides the EOL and EOF markers (which aren't useful anyway). Displays other whitespace characters using always the same colour. A: in netbeans 7 you can enable display of spaces, tabs & line feeds like this: spaces download font from: http://netbeans.org/bugzilla/attachment.cgi?id=97902 install the ttf font tools > options > font & colors > Syntax > All Languages > Whitespaces choose the installed whitespace font more info about the netbeans 6 bug: http://netbeans.org/bugzilla/show_bug.cgi?id=4619 tabs & line feeds in netbeans 7 you can enable to see non-printable characters: view > show non-printable characters in netbeans 6 only the spaces part works A: Using Netbeans 8.0.1 View-> Show Non-Printable characters
{ "pile_set_name": "StackExchange" }
Q: Error "system" is ambiguous? I have a simple program, and it works fine, but the system("CLS"); and system("pause"); statements have red IntelliSense lines underneath them. When I move my cursor over them it says Error "system" is ambiguous. What is causing that? Here is my code: #include <iostream> #include <cmath> using namespace std; int main() { int choice = 0; const double PI = 3.14159; double sideSquare = 0.0; double radius = 0.0; double base = 0.0; double height = 0.0; cout << "This program calculates areas of 3 different objects." << endl; cout << "1.) Square" << endl; cout << "2.) Circle" << endl; cout << "3.) Right Triangle" << endl; cout << "4.) Terminate Program" << endl << endl; cout << "Please [Enter] your object of choice: "; cin >> choice; system("CLS"); // The problem is here... switch(choice) { case 1: cout << "Please [Enter] the length of the side of the square: "; cin >> sideSquare; cout << "The area is: " << pow(sideSquare, 2) << endl; break; case 2: cout << "Please [Enter] the radius of the circle: "; cin >> radius; cout << "The area is: " << PI * pow(radius, 2) << endl; break; case 3: cout << "Please [Enter] the base of the triangle: "; cin >> base; cout << endl << "Now [Enter] the height of the triangle: "; cin >> height; cout << "The area is: " << (base * height) / 2 << endl; break; default: cout << "Please [Enter] a valid selection next time." << endl; return 0; } system("pause"); // ... and here. return 0; } A: You need to #include <cstdlib> Source: http://en.cppreference.com/w/cpp/utility/program/system Also, try to avoid system, it's dangerous. To pause the program when it's finished, put a breakpoint on the } at the end of main. There isn't a standard way to clear the screen unfortunately. For future reference, the red squiggles are intellisense errors, which are shown by a different front-end than the one that actually compiles the code, so the red squiggles are sometimes wrong, especially with complex templates. In most cases, including this one, it's correct though.
{ "pile_set_name": "StackExchange" }
Q: What is the origin of the phrase "caught red-handed"? I'm just wondering: why "red"? A: On etymonline you will find that it is, presumably, from the blood on hands. There are other more detailed articles around, quote: Red-handed doesn't have a mythical origin however - it is a straightforward allusion to having blood on one's hands after the execution of a murder or a poaching session. The term originates, not from Northern Ireland, but from a country not so far from there, socially and geographically, i.e. Scotland. An earlier form of 'red-handed', simply 'red hand', dates back to a usage in the Scottish Acts of Parliament of James I, 1432. Red-hand appears in print many times in Scottish legal proceedings from the 15th century onward. For example, this piece from Sir George Mackenzie's A discourse upon the laws and customs of Scotland in matters criminal, 1674: "If he be not taken red-hand the sheriff cannot proceed against him."
{ "pile_set_name": "StackExchange" }
Q: Spring validation: can't convert from String to Date I'm doing some spring form validation, however I'm getting: Failed to convert property value of type 'java.lang.String' to required type 'ja va.util.Date' for property 'birthdate'; nested exception is java.lang.Illega lStateException: Cannot convert value of type [java.lang.String] to required typ e [java.util.Date] for property 'birthdate': no matching editors or conversi on strategy found However, in my modelAttribute form I have: @NotNull @Past @DateTimeFormat(style="S-") private Date birthdate; I thought the DateTimeFormat was responsible for this? I'm using the hibernate-validator 4.0. A: Theres a chance you'll have to use register a CustomDateEditor in your controller(s) to convert from a String to a Date. The example method below goes in your controller, but you'll have to change the date format to match whatever you're using. @InitBinder public void initBinder(WebDataBinder binder) { CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true); binder.registerCustomEditor(Date.class, editor); } A: In order to use @DateTimeFormat you need to install FormattingConversionServiceFactoryBean. <mvc:annotation-driven> does it implicitly, but if you cannot use it you need something like this: <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean id="annotationMethodHandlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean id="configurableWebBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="validator"><ref bean="validator"/> <proeprty name = "conversionService" ref = "conversionService" /> </bean> </property> </bean>
{ "pile_set_name": "StackExchange" }
Q: PHP Tidy & closing tags query I'm just curious as to why this works: $config = array('wrap' => 0,'show-body-only' => TRUE,); $str = '<p>Hello World!'; $tidy = tidy_parse_string($str, $config); tidy_clean_repair($tidy); echo (htmlentities($tidy)); //outputs <p>Hello World!</p> while this doesn't: $config = array('wrap' => 0,'show-body-only' => TRUE,); $str = 'Hello World!</p>'; $tidy = tidy_parse_string($str, $config); tidy_clean_repair($tidy); echo (htmlentities($tidy)); //outputs Hello World! A: I believe if you put <p> that most programs accept that as "until the end of the line" but if you put a </p> it is not able to match where it started and disregards it. (But I am not 100% sure)
{ "pile_set_name": "StackExchange" }
Q: Multiple aggregates in SSRS 2005 matrix How can I get the aggregate information to appear in a matrix as in this example: The query results are in a single row with columns representing each of the aggregate numbers. A: Assuming your data is something like this: You can set up a Matrix object to display something similar to your requirements: Here I dragged City and Item into the Matrix row and column field respectively, then added another Row Group based on Category and a Column Group based on Date. The end result is practically the same as your requirement: The big caveat here is that SSRS 2005 offers very limited options for customising a Matrix, i.e. things like adding new columns, but you can see the example report is pretty close so this is worth considering.
{ "pile_set_name": "StackExchange" }
Q: initialize GAE datastore with start data? this is my first question on stackoverflow and I'm new to programming: What is the right way to load data into the GAE datastore when deploying my app? This should only happen once at deployment. In other words: How can I call methods in my code, such that these methods are only called when I deploy my app? The GAE documentation for python2.7 says, that one shouldn't call a main function, so I can't do this: if __name__ == '__main__': initialize_datastore() main() A: Create a handler that is restricted to admins only. When that handler is invoked with a simple GET request you could have it check to see if the seed data exists and if it doesn't, insert it. Configuring a handler to require login or administrator status. Another option is to write a Python script that utilizes the Remote API. This would allow you to access local data sources such as a CSV file or a locally hosted database and wouldn't require you to create a potentially unwieldy handler. Read about the Remote API in the docs. Using the Remote API Shell - Google App Engine
{ "pile_set_name": "StackExchange" }
Q: Thanking a professor for their effort Some time ago I had emailed a professor regarding the original data of an experiment they'd conducted almost two decades ago. He replied today to apologize as he had unfortunately not found the data after looking for it for a while. How can I thank the professor for his efforts without coming off as condescending? Something like "Thank you very much for going to the trouble of finding the data" sounds to me like I still expect something and simply saying "Thank you for your effort" comes off as condescending to me, but this may be because I am not a native English speaker. A: It would be fine to simply write "Dear Professor X, Thank you for taking the time to look. Best wishes, JansthcirlU"
{ "pile_set_name": "StackExchange" }
Q: Sort Linq list with one column I guess it should be really simple, but i cannot find how to do it. I have a linq query, that selects one column, of type int, and i need it sorted. var values = (from p in context.Products where p.LockedSince == null select Convert.ToInt32(p.SearchColumn3)).Distinct(); values = values.OrderBy(x => x); SearchColumn3 is op type string, but i only contains integers. So i thought, converting to Int32 and ordering would definitely give me a nice 1,2,3 sorted list of values. But instead, the list stays ordered like it were strings. 199 20 201 Update: I've done some tests with C# code and LinqPad. LinqPad generates the following SQL: SELECT [t2].[value] FROM ( SELECT DISTINCT [t1].[value] FROM ( SELECT CONVERT(Int,[t0].[SearchColumn3]) AS [value], [t0].[LockedSince], [t0].[SearchColumn3] FROM [Product] AS [t0] ) AS [t1] WHERE ([t1].[LockedSince] IS NULL) ) AS [t2] ORDER BY [t2].[value] And my SQL profiler says that my C# code generates this piece of SQL: SELECT DISTINCT a.[SearchColumn3] AS COL1 FROM [Product] a WHERE a.[LockedSince] IS NULL ORDER BY a.[SearchColumn3] So it look like C# Linq code just omits the Convert.ToInt32. Can anyone say something useful about this? A: [Disclaimer - I work at Telerik] You can solve this problem with Telerik OpenAccess ORM too. Here is what i would suggest in this case. var values = (from p in context.Products where p.LockedSince == null orderby "cast({0} as integer)".SQL<int>(p.SearchColumn3) select "cast({0} as integer)".SQL<int>(p.SearchColumn3)).ToList().Distinct(); OpenAccess provides the SQL extension method, which gives you the ability to add some specific sql code to the generated sql statement. We have started working on improving this behavior. Thank you for pointing this out. Regards Ralph A: Same answer as one my other questions, it turns out that the Linq provider i'm using, the one that comes with Telerik OpenAccess ORM does things different than the standard Linq to SQL provider! See the SQL i've posted in my opening post! I totally wasn't expecting something like this, but i seem that the Telerik OpenAccess thing still needs a lot of improvement. So be careful before you start using it. It looks nice, but it has some serious shortcomings.
{ "pile_set_name": "StackExchange" }
Q: Probability of a random variable being no more than A, given that it is at least B Example question It is known that 30% of all laptops of a certain brand experience hard-drive failure within 3 years of purchase. Suppose that 20 laptops are selected at random. Let the random variable $X$ denote the number of laptops which have experienced hard-drive failure within 3 years of purchase. If it is known that at least 3 laptops experience hard-drive failure, what is the probability that no more than 6 laptops will experience hard-drive failure? I know $X\sim\operatorname{Bin}(20,0.3)$. I know how to calculate probabilities like $P(X = x), P(X \gt x), P(X \ge x),$ and $P(X \le x).$ Relevant formulae: $$P(X = x) = {n \choose p}p^x(1-p)^{n-x}$$ $$P(X \gt x) = 1 - P(X \leq x)$$ and if $X$ is discrete, $$P(X \ge x) = 1 - P(X \leq (x-1))$$ Additionally, what if the question was: If it is known that at least 3 laptops experience hard-drive failure, what is the probability that at least 6 laptops will experience hard-drive failure? or If it is known that no more than 6 laptops experience hard-drive failure, what is the probability that at least 3 laptops will experience hard-drive failure? A: $$ \Pr(X\le 6 \mid X\ge 3) = \frac{\Pr(X\le6\ \&\ X\ge 3)}{\Pr(X\ge 3)} = \frac{\Pr(X=3\text{ or } X=4 \text{ or } X=5 \text{ or }X=6)}{1 - \Pr(X=0\text{ or }X=1\text{ or } X=2) } $$
{ "pile_set_name": "StackExchange" }
Q: What's the difference between $.add and $.append JQuery I was wondering and couldn't get any best documentation that what's the difference between $.add and $.append when we have single element to add or append to a container. Thanks in Advance A: They are not at all related. .add() Add elements to the set of matched elements. e.g. If you want to do, $('div').css('color':'red'); $('div').css('background-color':'yellow'); $('p').css('color':'red'); Then, you can do, $('div').css('background-color':'yellow').add('p').css('color':'red'); Reference .append() Insert content, specified by the parameter, to the end of each element in the set of matched elements. $('div').append('p'); will append selected p on all selected div in dom. Reference A: Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. But it does not insert the element into the DOM, i.e using .add() the element will be added to the DOM but to see it in the page you have to insert it in the page using some insertion/append method. A: .add() for example: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> <p>a random paragraph</p> to change the color of the <li> elements AND the <p> element to red, you could write: $( "li" ).css( "background-color", "green" ); $( "p" ).css( "background-color", "green" ); or condensing the above by utilizing .add() $( "li" ).add( "p" ).css( "background-color", "green" ); .append() Will create a new element to add to the DOM and will appear as a child to the existing specified element. <div>one</div> <div>two</div> <ol> <li>item1</li> <li>item2</li> </ol> $("div").append('<p>'); will result in: <div>one</div> <p></p> <div>two</div> <p></p> <ol> <li>item1</li> <p></p> <li>item2</li> <p></p> </ol>
{ "pile_set_name": "StackExchange" }
Q: How do I find text between two words and export it to txt.file I have a CSV file which contains many lines and I want to take the text between <STR_0.005_Long>, and µm,5.000µm. Example line from the CSV: Straightness(Up/Down) <STR_0.005_Long>,4.444µm,5.000µm,,Pass,‌​2.476µm,1.968µm,25,0‌​.566µm,0.720µm This is the script that I am trying to write: $arr = @() $path = "C:\Users\georgi\Desktop\5\test.csv" $pattern = "(?<=.*<STR_0.005_Long>,)\w+?(?=µm,5.000µm*)" $Text = Get-Content $path $Text.GetType() | Format-Table -AutoSize $Text[14] | Foreach { if ([Regex]::IsMatch($_, $pattern)) { $arr += [Regex]::Match($_, $pattern) Out-File C:\Users\georgi\Desktop\5\test.txt -Append } } $arr | Foreach {$_.Value} | Out-File C:\Users\georgi\Desktop\5\test.txt -Append A: Use a Where-Object filter with your regular expression and simply output the match to the output file: Get-Content $path | Where-Object { $_ -match $pattern } | ForEach-Object { $matches[0] } | Out-File 'C:\Users\georgi\Desktop\5\test.txt' Of course, since you have a CSV, you could simply use Import-Csv and export the value of that particular column: Import-Csv $path | Select-Object -Expand 'column_name' | Out-File 'C:\Users\georgi\Desktop\5\test.txt' Replace column_name with the actual name of the column. If the CSV doesn't have a column header you can specify one via the -Header parameter: Import-Csv $path -Header 'col1','col2','col3',... | Select-Object -Expand 'col2' | Out-File 'C:\Users\georgi\Desktop\5\test.txt'
{ "pile_set_name": "StackExchange" }
Q: Cannot expand and substitute the contents of a variable in Bash I am using Gitbash, GNU bash, version 4.3.46(2)-release (x86_64-pc-msys). I am running a bash script that looks like this CODE CHUNK 1 curl -i -X POST \ -H "Content-Type:application/json" \ -H "x-customheader:customstuff" \ -d \ '{ Gigantic json payload contents in here }' \ 'http://localhost:5000/api/123' This works fine. Basically it posts a giant payload to an endpoint and all is well. The problem is when I attempt to substitute the url for a value from a variable, I get a curl error, curl: (1) Protocol "'http" not supported or disabled in libcurl CODE CHUNK 2 stuff=\'http://localhost:5000/api/123\' curl -i -X POST \ -H "Content-Type:application/json" \ -H "x-customheader:customstuff" \ -d \ '{ Gigantic json payload contents in here }' \ $stuff If I echo $stuff immediately after the stuff=\'http://localhost:5000/api/123\', I get 'http://localhost:5000/api/123'. This is the same value as I had hard-coded in code chunk 1, single ticks and all. There is something hiding behind the scenes in how that url is being evaluated after the variable has been expanded. I need to get the same behavior as a hard coded url. A: Look closely at this error message: curl: (1) Protocol "'http" not supported or disabled in libcurl Notice the single-quote in front of http. The curl command surely knows the http protocol, but not the 'http protocol! The way you wrote it, the single-quotes are part of the value of stuff: stuff=\'http://localhost:5000/api/123\' Remove those, write like this: stuff='http://localhost:5000/api/123' If you have variables inside your real string, and you want them expanded, then use double-quotes instead of single-quotes: stuff="http://localhost:5000/api/123" Equally important, when you use $stuff as a parameter of curl, you must double-quote it. If you just write curl $stuff, then the shell may interpret some characters in $stuff before passing to curl. To protect from that, you must write curl "$stuff". The complete command: curl -i -X POST \ -H "Content-Type:application/json" \ -H "x-customheader:customstuff" \ -d \ '{ Gigantic json payload contents in here }' \ "$stuff" Finally, make sure that after each \ at the end of lines, there's nothing after the \ on each line, the \ must be at the very end.
{ "pile_set_name": "StackExchange" }
Q: A strange little number - $6174$. Take a 4 digit number such that it isn't made out the same digit $(1111, 2222, .. . $ etc$)$ Define an operation on such a four digit number by taking the largest number that can be constructed out of these digits and subtracting the smallest four digit number. For example, given the number $2341$, we have, $4321 - 1234 = 3087$ Repeating this process with the results (by allowing leading zeroes) we get the following numbers: $8730 - 0378 = 8352$ $8532 - 2358 = 6174$ What's more interesting is that with $6174$ we get $7641 - 1467 = 6174$ and taking any four digit number we end up with 6174 after at most 7 iterations. A bit of snooping around the internet told me that this number is called the Kaprekar's constant. A three digit Kaprekar's contant is the number 495 and there's no such constant for two digit numbers. My question is, how can we go about proving the above properties algebraically? Specifically, starting with any four digit number we arrive at 6174. I know we can simply test all four digit numbers but the reason I ask is, does there exist a 5 digit Kaprekar's constant? Or an $n$-digit Kaprekar's constant for a given $n$? A: Note: For fun and curiosity I avoid a programming language and stick to algebraic expressions with the intention to feed this through Gnuplot: The basic operation is $$ F(n) = F_+(n) - F_-(n) $$ where $F_+$ maps to the maximum digit number and $F_-$ maps to the minimum digit number. We only consider the case of base $10$ non-negative $4$ digit numbers $$ (d_3 d_2 d_1 d_0)_{10} = \sum_{k=0}^3 d_k \, 10^k $$ To provide $F_+$ and $F_-$ we need a way to sort a set of four digits. This can be done by applying $\min$ and $\max$ functions $$ \begin{align} \min(a, b) &:= \frac{a + b - |a - b|}{2} \\ \max(a, b) &:= \frac{a + b + |a - b|}{2} \end{align} $$ like this: We start with calculating intermediate values $s_k$, $t_k$ $$ \begin{matrix} s_0 = \min(d_0, d_1) \\ s_1 = \max(d_0, d_1) \\ s_2 = \min(d_2, d_3) \\ s_3 = \max(d_2, d_3) \end{matrix} \quad\quad \begin{matrix} t_0 = \min(s_0, s_2) \\ t_1 = \max(s_0, s_2) \\ t_2 = \min(s_1, s_3) \\ t_3 = \max(s_1, s_3) \end{matrix} $$ and then get $$ d^+_0 = t_0 \quad\quad d^-_0 = t_3 \\ d^+_1 = \min(t_1, t_2) \quad\quad d^-_1 = \max(t_1, t_2) \\ d^+_2 = \max(t_1, t_2) \quad\quad d^-_2 = \min(t_1, t_2) \\ d^+_3 = t_3 \quad\quad d^-_3 = t_0 $$ where $d^+_k$ are the digits sorted to maximize and $d^-_k$ are the digits sorted to minimize. One can visualize this as a sorting network d0 \ \ min: s0 --> min: t0 ----> dp0 dm3 / max: s1 ^ max: t1 / \ / \ d1 \/ \ min: dp1 dm2 d2 /\ / max: dp2 dm1 \ / \ / \ min: s2 v min: t2 / max: s3 --> max: t3 ----> dp3 dm0 / d3 For example $$ \begin{align} d^-_2 &= \min(t_1, t_2) \\ &= \min(\max(s_0, s_2), \min(s_1, s_3)) \\ &= \min(\max(\min(d_0, d_1), \min(d_2, d_3)), \min(\max(d_0, d_1), \max(d_2, d_3))) \end{align} $$ which is a complicated term but otherwise still a function of the $d_k$. Then we need a way to extract the $k$-th digit: $$ \pi^{(k)}\left( (d_3 d_2 d_1 d_0)_{10} \right) = d_k $$ this can be done by the usual $$ \pi^{(3)}(n) = \left\lfloor \frac{n}{1000} \right\rfloor \\ \pi^{(2)}(n) = \left\lfloor \frac{n - 1000\, \pi^{(3)}(n)}{100} \right\rfloor \\ \pi^{(1)}(n) = \left\lfloor \frac{n - 1000\, \pi^{(3)}(n) - 100\, \pi^{(2)}(n)}{10} \right\rfloor \\ \pi^{(0)}(n) = n - 1000\, \pi^{(3)}(n) - 100\, \pi^{(2)}(n) - 10\, \pi^{(1)}(n) $$ Rewriting this for Gnuplot gives: min(a,b) = (a + b - abs(a - b))/2.0 max(a,b) = (a + b + abs(a - b))/2.0 dp0(d0,d1,d2,d3) = min(min(d0,d1),min(d2, d3)) dp1(d0,d1,d2,d3) = min(max(min(d0,d1),min(d2,d3)), min(max(d0,d1),max(d2,d3))) dp2(d0,d1,d2,d3) = max(max(min(d0,d1),min(d2,d3)), min(max(d0,d1),max(d2,d3))) dp3(d0,d1,d2,d3) = max(max(d0,d1),max(d2, d3)) pi3(n) = floor(n / 1000.0) pi2(n) = floor((n-1000*pi3(n))/ 100.0) pi1(n) = floor((n-1000*pi3(n)-100*pi2(n))/ 10.0) pi0(n) = n-1000*pi3(n)-100*pi2(n)-10*pi1(n) fp(n) = dp0(pi0(n),pi1(n),pi2(n),pi3(n)) + 10*dp1(pi0(n),pi1(n),pi2(n),pi3(n)) + 100*dp2(pi0(n),pi1(n),pi2(n),pi3(n)) + 1000*dp3(pi0(n),pi1(n),pi2(n),pi3(n)) dm0(d0, d1, d2, d3) = dp3(d0,d1,d2,d3) dm1(d0, d1, d2, d3) = dp2(d0,d1,d2,d3) dm2(d0, d1, d2, d3) = dp1(d0,d1,d2,d3) dm3(d0, d1, d2, d3) = dp0(d0,d1,d2,d3) fm(n) = dm0(pi0(n),pi1(n),pi2(n),pi3(n)) + 10*dm1(pi0(n),pi1(n),pi2(n),pi3(n)) + 100*dm2(pi0(n),pi1(n),pi2(n),pi3(n)) + 1000*dm3(pi0(n),pi1(n),pi2(n),pi3(n)) f(x) = fp(x) - fm(x) This works quite nice: gnuplot> print fp(3284), fm(3284) 8432.0 2348.0 But it turns out that using the graphics is not precise enough to identify fixed points. In the end one needs a computer programm to check all numbers $n \in \{ 0, \ldots, 9999 \}$ for a proper fixed point from $\mathbb{N}^2$. Note: The $\mbox{equ}$ function was used to set the arguments with repeated digits to zero. eq(d0,d1,d2,d3) = (d0 == d1) ? 0 : (d0 == d2) ? 0 : (d0 == d3) ? 0 : (d1 == d2) ? 0 : (d1 == d3) ? 0 : (d2 == d3) ? 0 : 1 equ(n) = eq(pi0(n),pi1(n),pi2(n),pi3(n)) Update: Maybe one can do it better, the calculation precision is good enough: gnuplot> print fp(6174), fm(6174), f(6174) 7641.0 1467.0 6174.0 # <- fixed point! gnuplot> print fp(6173), fm(6173), f(6173) 7631.0 1367.0 6264.0 gnuplot> print fp(6175), fm(6175), f(6175) 7651.0 1567.0 6084.0 Update: This seems to work: gnuplot> set samples 10000 gnuplot> plot [0:9999] [0:1] abs(f(x)*equ(x) - x) < 0.1 Note: The algebraic expressions I used made analysis not easier, the terms are too unwieldy to give the insight to determine the fixed points. It boiled down to to trying out every argument and checking the function value via a computer.
{ "pile_set_name": "StackExchange" }
Q: How to cleanly get user input from the middle of model's method in Model-View-Viewmodel architecture? I am writing an app that listens on a network connection, and when some data arrive, it replies back, and depending on incoming data, it may need to ask user (show dialog) before replying back. I don't know how to do this cleanly in M-V-VM architecture: the events and binding to observable collections are nice if I need to just update GUI based on incoming data, but what if I actually need an anwer from user before replying back? And to make things worse, I want to do it synchronously, because I want my reply algorithm to be at one place, not partitioned into multiple callbacks with unclear 'who-calls-who' responsibilities. Simply, something like HandleMessage(Message msg){ string reply; if (msg.type == 1) { reply = ... } else { string question = msg... reply = ShowModalDialog(question); // MVVM violation! } sender.Send(reply); } but I don't want to call view or viewmodel from model, as model needs to be reusable and testable - I don't want popping dialogs in every test run, and it would be violation of MVVM! No events (they are just one-way as far as i know, and have no backwards channel to get reply to event origin) or databinding, as it would be asynchronous. Is this doable? This is a question I asked several test driven development propagators, and so far, I didn't get practically usable answer. Yet, a need for some additional input in the middle of processing is fairly common. Thanks! EDIT: this is application logic, so it clearly belongs to model, and even if in this case it didn't, I'd like to know the solution for cases when I really need user's input in the middle of business logic routine in model. A: This is one of those problems that MVVM doesn't solve on it's own. One solution would be to use a service to query the user and then have the ViewModel use that service. In my project we're using PRISM which besides providing a services framework also provides other tools for making GUI development easier. Here's a writeup of how services work in PRISM. So specifically in your case I would create some sort of IOC, register a query service with it, then in the ViewModel pass in the IOC and then use the IOC to get the query service, and use that to query the user. More work? Sure. But it means you can replace the query service with another implementation for testing by simply replacing it in the IOC. MVVM + Services = Ultimate Power!
{ "pile_set_name": "StackExchange" }
Q: What is the fourth dimension of a Tesseract? Is the fourth dimension of the Tesseract time? Is that why it is represented as a moving 3D structure on Wikipedia? I am asking because I have trouble understanding what it is. A: It isn't time. The tesseract is an object in 4 (or higher) space dimensions. However, since we live in 3 dimensions, it is not possible for us to see a tesseract in all its glory. What we can see is the projection of a tesseract on a 3d plane. Now, depending on which plane is chosen for the projection, the tesseract looks different. The diagram on Wiki is trying to give you the best possible "view" of the tesseract by rotating the plane on which the projection is being done, thereby allowing you to see all possible projections of the tesseract. In fact, the text below the picture clearly states this A 3D projection of an 8-cell performing a simple rotation about a plane which bisects the figure from front-left to back-right and top to bottom EDIT: Based on comments below, I'm adding the following notes - Firstly, a tesseract is a mathematical construct. It is a description of what a higher dimensional object would look like if such higher dimensions existed. Secondly, how do you conclude that you do not have such objects popping out of the 4th dimension, if it existed? You must remember that the world that you and I can see need not be the entire story. It may be true that higher dimensions exist but we can't access it. That is a totally logical possibility. For instance, imagine an ant walking on a piece of paper. As far as the ant is concerned, it knows only of the 2 dimensions of the paper. Does that mean that the 3rd dimension that it cannot see doesn't exist? No! It simply means that the ant can only see and make sense of objects living on the paper or projections of three-dimensional objects on that paper. If the ant were smart enough, by studying the properties of the projected objects, it could infer the existence of the 3rd dimension without ever having seen it. The same logic applies to us. We will never be able to directly see the 4th dimension, but imprints of its existence might be present in the 3 dimensions that we can see. By properly understanding these, we can make progress. PS - String theorists believe that the world has 9 dimensions (+1 time dimension).
{ "pile_set_name": "StackExchange" }
Q: How to fix?: mysql> show variables like 'plugin_dir'; Does not show plugin_dir location After this post I continued to try to setup MySQL memcached User-Defined Functions as per these instructions: http://stanley-huang.blogspot.com/2010/04/level-3-install-memcached-user-defined.html But now when trying to find the plugin_dir location I get: mysql> show variables like 'plugin_dir'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | plugin_dir | | +---------------+-------+ 1 row in set (0.00 sec) It's blank. What did I miss? Thanks A: Check your my.cnf [mysqld] plugin_dir=/path/to/plugin/directory
{ "pile_set_name": "StackExchange" }
Q: Unexpected thread behavior. Visibility I have the following code: public static boolean turn = true; public static void main(String[] args) { Runnable r1 = new Runnable() { public void run() { while (true) { while (turn) { System.out.print("a"); turn = false; } } } }; Runnable r2 = new Runnable() { public void run() { while (true) { while (!turn) { System.out.print("b"); turn = true; } } } }; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } In class we've learned about "Visibility" problems that may occur when using un-synchronized code. I understand that in order to save time, the compiler will decide the grab turn to the cache in the CPU for the loop, meaning that the thread will not be aware if the turn value was changed in the RAM because he doesn't check it. From what I understand, I would expected the code to run like this: T1 will see turn as true -> enter loop and print -> change turn to false -> gets stuck T2 will think turn hasn't changed -> will get stuck I would expect that if T1 will start before T2: only 'a' will be printed and both threads will run in an infinite loop without printing anything else However, when I'm running the code sometimes I get a few "ababa...." before both threads will stuck. What am I missing ? EDIT: The following code does what I expect it: the thread will run in a infinite loop: public class Test extends Thread { boolean keepRunning = true; public void run() { long count = 0; while (keepRunning) { count++; } System.out.println("Thread terminated." + count); } public static void main(String[] args) throws InterruptedException { Test t = new Test(); t.start(); Thread.sleep(1000); t.keepRunning = false; System.out.println("keepRunning set to false."); } } How are they different from each other ? A: When I run the code, sometimes I get a few "ababa...." before both threads will stuck. I suspect that what is happening is that the behavior is changing when the code is JIT compiled. Before JIT compilation the writes are visible because the interpreter is doing write-throughs. After JIT compilation, either the cache flushes or the reads have been optimized away ... because the memory model allows this. What am I missing ? What you are missing is that you are expecting unspecified behavior to be consistent. It doesn't have to be. After all, it is unspecified! (This is true, even if my proposed explanation above is incorrect.)
{ "pile_set_name": "StackExchange" }
Q: ul li css issue for menu I am trying to change from anchor tag to ul li but it doesn't seem to work. Can you find out where I need to change CSS of my code? Original link:https://codepen.io/arkev/pen/DzCKF My code: https://codepen.io/SankS/pen/YRNzGK <ul> <li><a href="#" class="active">Browse</a></li> <li><a href="#">Compare</a></li> <li><a href="#">Order Confirmation</a></li> <li><a href="#">Checkout</a></li> </ul> A: Minor changes in css and change 'active' class to li element /*custom font*/ @import url(https://fonts.googleapis.com/css?family=Merriweather+Sans); * { margin: 0; padding: 0; } html, body { min-height: 100%; } a{text-decoration:none;} body { text-align: center; padding-top: 100px; background: #689976; background: linear-gradient(#689976, #ACDACC); font-family: 'Merriweather Sans', arial, verdana; } .breadcrumb { /*centering*/ display: inline-block; box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.35); overflow: hidden; border-radius: 5px; /*Lets add the numbers for each link using CSS counters. flag is the name of the counter. to be defined using counter-reset in the parent element of the links*/ counter-reset: flag; } .breadcrumb li { text-decoration: none; outline: none; display: block; float: left; font-size: 12px; line-height: 36px; color: white; /*need more margin on the left of links to accomodate the numbers*/ padding: 0 10px 0 60px; background: #666; background: linear-gradient(#666, #333); position: relative; } /*since the first link does not have a triangle before it we can reduce the left padding to make it look consistent with other links*/ .breadcrumb li:first-child { padding-left: 46px; border-radius: 5px 0 0 5px; /*to match with the parent's radius*/ } .breadcrumb li:first-child:before { left: 14px; } .breadcrumb li:last-child { border-radius: 0 5px 5px 0; /*this was to prevent glitches on hover*/ padding-right: 20px; } /*hover/active styles*/ .breadcrumb li.active, .breadcrumb a:hover { background: #333; background: linear-gradient(#333, #000); } .breadcrumb li.active:after, .breadcrumb li:hover:after { background: #333; background: linear-gradient(135deg, #333, #000); } /*adding the arrows for the breadcrumbs using rotated pseudo elements*/ .breadcrumb li:after { content: ''; position: absolute; top: 0; right: -18px; /*half of square's length*/ /*same dimension as the line-height of .breadcrumb a */ width: 36px; height: 36px; /*as you see the rotated square takes a larger height. which makes it tough to position it properly. So we are going to scale it down so that the diagonals become equal to the line-height of the link. We scale it to 70.7% because if square's: length = 1; diagonal = (1^2 + 1^2)^0.5 = 1.414 (pythagoras theorem) if diagonal required = 1; length = 1/1.414 = 0.707*/ transform: scale(0.707) rotate(45deg); /*we need to prevent the arrows from getting buried under the next link*/ z-index: 1; /*background same as links but the gradient will be rotated to compensate with the transform applied*/ background: #666; background: linear-gradient(135deg, #666, #333); /*stylish arrow design using box shadow*/ box-shadow: 2px -2px 0 2px rgba(0, 0, 0, 0.4), 3px -3px 0 2px rgba(255, 255, 255, 0.1); /* 5px - for rounded arrows and 50px - to prevent hover glitches on the border created using shadows*/ border-radius: 0 5px 0 50px; } /*we dont need an arrow after the last link*/ .breadcrumb li:last-child:after { content: none; } /*we will use the :before element to show numbers*/ .breadcrumb li:before { content: counter(flag); counter-increment: flag; /*some styles now*/ border-radius: 100%; width: 20px; height: 20px; line-height: 20px; margin: 8px 0; position: absolute; top: 0; left: 30px; background: #444; background: linear-gradient(#444, #222); font-weight: bold; } .flat li, .flat li:after { background: white; color: black; transition: all 0.5s; } .flat li a {color:black;} .flat li a:hover{background:none;} .flat li:before { background: white; box-shadow: 0 0 0 1px #ccc; } .flat li:hover, .flat li.active, .flat li:hover:after, .flat li.active:after { background: #9EEB62; } <!-- a simple div with some links --> <!-- another version - flat style with animated hover effect --> <div class="breadcrumb flat"> <ul> <li class="active"> <a href="#">Browse</a> </li> <li><a href="#">Compare</a></li> <li><a href="#">Order Confirmation</a></li> <li><a href="#">Checkout</a></li> </ul> </div> <!-- Prefixfree --> <script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js" type="text/javascript" type="text/javascript"></script>
{ "pile_set_name": "StackExchange" }
Q: MYSQL MIN on Average of Inner Join Given that there are two tables: events users Each user is allowed to have one or more events. Each event can only be owned by one user. I put together the following query to average the difference between the corresponding created_at timestamps of events and users. SELECT ( SELECT AVG(TIMESTAMPDIFF(DAY, users.created_at, events.created_at)) FROM users INNER JOIN events ON users.id = events.user_id WHERE events.created_at IS NOT NULL AND users.created_at IS NOT NULL ) AS "Difference between created_at of user and created_at of user's first event, averaged across all users." However, how would one go about only including the FIRST overlap, where the timestamp of the event.created_at is lowest? I believe at present, that the code would take the difference between each and every timestamp and the created_at, and average those out. What I am trying to accomplish to get the differences for every user between his/her first created event, do this for every user in the database, and average the results. The solution is probably quite simple, but I was unable to come up with a working query. Any help or advice appreciated! A: I think you will need a subquery to find the earliest event so that you get one row in the event join...something like this? SELECT AVG(TIMESTAMPDIFF(DAY, u.created_at, e.created_at)) FROM users u INNER JOIN events e ON u.id = e.user_id INNER JOIN ( SELECT user_id, MIN(created_at) minDate FROM events GROUP BY user_id ) m ON m.user_id = u.user_id AND e.created_at = m.minDate WHERE e.created_at IS NOT NULL AND u.created_at IS NOT NULL In case that's not clear, what I've done there is taken your original join giving all events for each user, but this is then joined against the earliest event for each user, so we just end up with one row per user who has at least one event. This can be simplified as we don't need need that first join against events, we can just join users against that subquery... SELECT AVG(TIMESTAMPDIFF(DAY, u.created_at, m.minDate)) FROM users u INNER JOIN ( SELECT user_id, MIN(created_at) minDate FROM events GROUP BY user_id ) m ON m.user_id = u.user_id WHERE u.created_at IS NOT NULL
{ "pile_set_name": "StackExchange" }
Q: Keras custom loss with one of the features used and a condition I'm trying to make a custom function for the deviance in Keras. Deviance is calculated as : 2 * (log(yTrue) - log(yPred)) The problem here is that my yTrue values are rare event count and therefore often equal to 0, resulting in a -inf error. The derivation of deviance for my specific case (poisson unscaled deviance) gives a solution to this : If yTrue = 0, then deviance is : 2 * D * yPred where D is a feature of my data. If yTrue !=0, then deviance is : 2 * D * (yTrue * ln(yTrue) - yTrue * ln(yPred) - yTrue + yPred There is two problems here i encounter : I need to choose the function according to the value of yPred I also need to pass D as argument to the loss function I made a first iteration of a loss function before derivating deviance, adding small values to yTrue when it is equal to 0 to prevent the -Inf. problems, but it gives wrong results for deviance so i have to change it. def DevianceBis(y_true, y_pred): y_pred = KB.maximum(y_pred, 0.0 + KB.epsilon()) #make sure ypred is positive or ln(-x) = NAN return (KB.sqrt(KB.square( 2 * KB.log(y_true + KB.epsilon()) - KB.log(y_pred)))) I'd like to know how to pass the D values into the loss function and how to use an if statement in order to choose the correct expression to use. Thanks in advance EDIT : Tried this one but returns NaN def custom_loss(data, y_pred): y_true = data[:, 0] d = data[:, 1:] # condition mask = keras.backend.equal(y_true, 0) #i.e. y_true != 0 mask = KB.cast(mask, KB.floatx()) # returns 0 when y_true =0, 1 otherwise #calculate loss using d... loss_value = mask * (2 * d * y_pred) + (1-mask) * 2 * d * (y_true * KB.log(y_true) - y_true * KB.log(y_pred) - y_true + y_pred) return loss_value def baseline_model(): # create model #building model model = keras.Sequential() model.add(Dense(5, input_dim = 26, activation = "relu")) #model.add(Dense(10, activation = "relu")) model.add(Dense(1, activation = "exponential")) model.compile(loss=custom_loss, optimizer='RMSProp') return model model = baseline_model() model.fit(data2, np.append(y2, d, axis = 1), epochs=1, shuffle=True, verbose=1) EDIT 2 : def custom_loss(data, y_pred): y_true = data[:, 0] d = data[:, 1:] # condition mask2 = keras.backend.not_equal(y_true, 0) #i.e. y_true != 0 mask2 = KB.cast(mask2, KB.floatx()) # returns 0 when y_true =0, 1 otherwise #calculate loss using d... loss_value = 2 * d * y_pred + mask2 * (2 * d * y_true * KB.log(y_true) + 2 * d * y_true * KB.log(y_pred) - 2 * d * y_true) return loss_value EDIT 3 seems to be working without the logs (altough it isn't the result i am looking for) : def custom_loss(data, y_pred): y_true = data[:, 0] d = data[:, 1] # condition mask2 = keras.backend.not_equal(y_true, 0) #i.e. y_true != 0 mask2 = KB.cast(mask2, KB.floatx()) # returns 0 when y_true =0, 1 otherwise #calculate loss using d... loss_value = 2 * d * y_pred #+ mask2 * (2 * d * y_true * KB.log(y_true) + 2 * d * y_true * KB.log(y_pred) - 2 * d * y_true) return loss_value def baseline_model(): # create model #building model model = keras.Sequential() model.add(Dense(5, input_dim = 26, activation = "relu")) #model.add(Dense(10, activation = "relu")) model.add(Dense(1, activation = "exponential")) model.compile(loss=custom_loss, optimizer='RMSProp') return model model = baseline_model() model.fit(data2, np.append(y2, d, axis = 1), epochs=1, shuffle=True, verbose=1) EDIT again : def custom_loss3(data, y_pred): y_true = data[:, 0] d = data[:, 1] # condition loss_value = KB.switch(KB.greater(y_true, 0), 2 * d * y_pred, 2 * d * (y_true * KB.log(y_true + KB.epsilon()) - y_true * KB.log(y_pred + KB.epsilon()) - y_true + y_pred)) return loss_value A: So here's the final answer ... after days i finally found how to do it. def custom_loss3(data, y_pred): y_true = data[:, 0] d = data[:, 1] lnYTrue = KB.switch(KB.equal(y_true, 0), KB.zeros_like(y_true), KB.log(y_true)) lnYPred = KB.switch(KB.equal(y_pred, 0), KB.zeros_like(y_pred), KB.log(y_pred)) loss_value = 2 * d * (y_true * lnYTrue - y_true * lnYPred[:, 0] - y_true + y_pred[:, 0]) return loss_value Calculate the logs before the actual loss and give K.zeros_like instead of it if the value of y_true is 0. Also need to only take the first vector of y_pred since it will return a vector NxN and y_true will return Nx1. Also had to delete values of d=0 in the data (they wern't of much use anyway).
{ "pile_set_name": "StackExchange" }
Q: How can use the cascade in Postgresql query while deleting record from parent table How can we use the cascade in PostgreSQL while deleting the one record from the parent table that is being referred in other child tables. Currently it is giving the syntax error. ERROR: syntax error at or near "cascade" LINE 1: DELETE FROM fs_item where itemid = 700001803 cascade; A: You have to add ON DELETE CASCADE constraint in following way: ALTER TABLE table1 ADD CONSTRAINT "tbl1_tbl2_fkey" FOREIGN KEY(reference_key) REFERENCES table2 ON DELETE CASCADE; Then, you can simply execute the DELETE query DELETE FROM fs_item where itemid = 700001803
{ "pile_set_name": "StackExchange" }
Q: ASP.NET 2.0 TreeView - OnSelectedNodeChanged does not fire in an User Control I have a small User Control defined as: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CompanyTree.ascx.cs" Inherits="RivWorks.Web.UserControls.CompanyTree" %> <div class="PrettyTree"> <asp:TreeView runat="server" ID="companyTree" OnSelectedNodeChanged="SelectedNodeChanged" OnAdaptedSelectedNodeChanged="SelectedNodeChanged" > </asp:TreeView> <asp:Label runat="server" ID="currentParentID" Text="" Visible="false" /> <asp:Label runat="server" ID="currentCompanyID" Text="" Visible="false" /> <asp:Label runat="server" ID="currentExpandDepth" Text="" Visible="false" /> <asp:Label runat="server" ID="currentValuePath" Text="" Visible="false" /> <asp:Label runat="server" ID="currentParentValuePath" Text="" Visible="false" /> <asp:Label runat="server" ID="currentCompanyUser" Text="" Visible="false" /> </div> For some reason, the OnSelectedNodeChanged and OnAdaptedSelectedNodeChanged events do not fire when I click on a node in the tree. I’ve been googling for the last hour and have not found anything amiss. Here are my event handlers in the code behind. #region Event Handlers protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadCompanyTree(); TreeNode currentNode = companyTree.SelectedNode; CompanyID = currentNode.Value; ValuePath = currentNode.ValuePath; if (currentNode.Parent != null) { ParentCompanyID = currentNode.Parent.Value; ParentValuePath = currentNode.Parent.ValuePath; } else { ParentCompanyID = ""; ParentValuePath = ""; } ExpandDepth = currentNode.Depth.ToString(); LoadCompany(); } } protected void SelectedNodeChanged(object sender, EventArgs e) { TreeNode currentNode = companyTree.SelectedNode; CompanyID = currentNode.Value; ValuePath = currentNode.ValuePath; if (currentNode.Parent != null) { ParentCompanyID = currentNode.Parent.Value; ParentValuePath = currentNode.Parent.ValuePath; } else { ParentCompanyID = ""; ParentValuePath = ""; } ExpandDepth = currentNode.Depth.ToString(); LoadCompany(); } #endregion I am also including the code for building the tree. My data structure is based off of http://articles.sitepoint.com/article/hierarchical-data-database. private void LoadCompanyTree() { DataTable dtTree = RivWorks.Data.Companies.GetTree(); companyTree.Nodes.Clear(); companyTree.Nodes.Add(RivWorks.Web.Tree.BuildTree(dtTree, Page)); companyTree.ExpandDepth = 1; companyTree.Nodes[0].Selected = true; companyTree.Nodes[0].Select(); companyTree.ShowLines = true; companyTree.RootNodeStyle.ImageUrl = Page.ResolveUrl(@"~/images/tree/root.png"); companyTree.ParentNodeStyle.ImageUrl = Page.ResolveUrl(@"~/images/tree/parent.png"); companyTree.LeafNodeStyle.ImageUrl = Page.ResolveUrl(@"~/images/tree/leaf.png"); companyTree.SelectedNodeStyle.Font.Bold = true; companyTree.SelectedNodeStyle.Font.Italic = true; if (CompanyID.Length > 0) { for (int i = 0; i < companyTree.Nodes.Count; i++) { if (companyTree.Nodes[i].Value.Equals(CompanyID, StringComparison.CurrentCultureIgnoreCase)) { companyTree.ExpandDepth = companyTree.Nodes[i].Depth; ValuePath = companyTree.Nodes[i].ValuePath; companyTree.Nodes[i].Selected = true; companyTree.Nodes[i].Select(); } } } } internal static TreeNode BuildTree(DataTable dtTree, System.Web.UI.Page myPage) { int left = 0; int right = 0; int index = 0; Stack<int> rightStack = new Stack<int>(); Stack<TreeNode> treeStack = new Stack<TreeNode>(); TreeNode rootNode = new TreeNode(dtTree.Rows[index]["CompanyName"].ToString(), dtTree.Rows[index]["CompanyID"].ToString()); while (index < dtTree.Rows.Count) { left = Convert.ToInt32(dtTree.Rows[index]["left"]); right = Convert.ToInt32(dtTree.Rows[index]["right"]); if (rightStack.Count > 0) { while (rightStack.Peek() < right) { rightStack.Pop(); treeStack.Pop(); } } if (treeStack.Count == 0) { treeStack.Push(rootNode); } else { TreeNode treeNode = new TreeNode(dtTree.Rows[index]["CompanyName"].ToString(), dtTree.Rows[index]["CompanyID"].ToString()); treeStack.Peek().ChildNodes.Add(treeNode); treeStack.Push(treeNode); } rightStack.Push(right); index++; } return rootNode; } When I put this in an ASPX page it works fine. When I moved it to an ASCX User Control the event no longer fires! Any tips/suggestions to get the event to fire? TIA NOTE: I am using the CSS Friendly Control Adapters found on CodePlex. http://cssfriendly.codeplex.com/workitem/5519?PendingVoteId=5519 is a bug report of the event not raising in User Control (.ascx). I've added the suggested code plus more and it still does not fire. <MasterPage> <Page> <ContentHolder> <User Control> <-- this should handle the event! <TreeView with CSSFriendly Adapter> Code in the adapter: public void RaiseAdaptedEvent(string eventName, EventArgs e) { string attr = "OnAdapted" + eventName; if ((AdaptedControl != null) && (!String.IsNullOrEmpty(AdaptedControl.Attributes[attr]))) { string delegateName = AdaptedControl.Attributes[attr]; Control methodOwner = AdaptedControl.Parent; MethodInfo method = methodOwner.GetType().GetMethod(delegateName); if (method == null) { methodOwner = AdaptedControl.Page; method = methodOwner.GetType().GetMethod(delegateName); } // 2010.06.21 - keith.barrows - added to (hopefully) handle User Control (ASCX) coding... // http://forums.asp.net/t/1249501.aspx if (method == null) { Control parentUserControl = FindParentUserControl(AdaptedControl.Parent); if (parentUserControl != null) { methodOwner = parentUserControl; method = methodOwner.GetType().GetMethod(delegateName); } } // 2010.06.21 - keith.barrows - added to (hopefully) handle User Control (ASCX) coding... // http://cssfriendly.codeplex.com/workitem/5519?ProjectName=cssfriendly if (method == null) { methodOwner = AdaptedControl.NamingContainer; method = methodOwner.GetType().GetMethod(delegateName); } if (method == null) { methodOwner = AdaptedControl.Parent; method = methodOwner.GetType().GetMethod(delegateName); } if (method != null) { object[] args = new object[2]; args[0] = AdaptedControl; args[1] = e; method.Invoke(methodOwner, args); } } } private Control FindParentUserControl(Control control) { if (control.Parent == null) return null; if (control.Parent is UserControl) return control.Parent; return FindParentUserControl(control.Parent); } Am I missing a delegate or event definition? The Adapted Control is JUST NOT FINDING the method to call! A: Quite by accident I found a solution that does work. Don't ask me why but I am dying to find out! In my ASPX page code-beside I added this method signature: protected void SelectedNodeChanged(object sender, EventArgs e) { } And now the RaiseAdaptedEvent event finds the event handler in the ASCX file!! Before I mark this as the answer - does anyone have any clue why this would work this way?
{ "pile_set_name": "StackExchange" }
Q: Notepad++ regular expression help I'm a total newb with expressions and looking for a quick way to do this. Trying to delete everything in between the && to TAG URL GOTO=http://www.URLHERE.com/&&TXT:Just<SP>Because<SP>I'm<SP>Skinny<SP>Does<SP>NOT<SP>Mean<SP>I<SP>Have<SP>an<SP>Eating<SP>Disorder TAG POS=1 TYPE=INPUT:SUBMIT FORM=ID:aspnetForm ATTR=VALUE:Submit A: Replace this: &&.*?\bTAG\b with an empty string. That will do it. It also makes sure that "TAG" is a separate word. You should also turn on multiline mode if the line break in your example is not only for formatting, or use: &&[\s\S]*?\bTAG\b
{ "pile_set_name": "StackExchange" }
Q: Snow from Fire: Could graupel, or even snow, fall from pyrocumulus clouds? Pyrocumulus clouds often form in areas that experience prolonged fire conditions, particularly forest fires, but are also associated with volcanic eruptions and even nuclear explosions. This question focuses on forest fire origins. An example of what one looks from above, is below: Caption: Pyrocumulus cloud, above the Oregon Gulch fire in Oregon & California, 2014. Aircraft is a F-15C Eagle. Image source The general idea of how pyrocumulus clouds are formed is quite well known, and its relationship with a 'firestorm' is, in a simplistic way, is shown below: Caption: Firestorm: fire (1), updraft (2), strong gusty winds (3) (A) pyrocumulonimbus cloud.Image source Pyrocumulus and related pyroconvective clouds have been known to have caused severe hail to fall. An example reported in the Earth Observatory: Russian Firestorm: Finding a Fire Cloud from Space, from the Canberra, Australia fires: Called pyrocumulonimbus clouds, the clouds are capable of dangerous lightning, hail, and strong winds. One such firestorm in 2003 pelted Canberra, Australia, with large, soot-darkened hail, produced a damaging tornado (Point of reference: Canberra is Australia's capital city, I was there at the time). Could graupel, or even snow, fall from pyrocumulus clouds? (It would be good if examples from real life or models could be provided, if possible) A: It is likely snowing somewhere in these clouds and graupel exist transiently on their way to becoming hail, but its not likely that you will see either at the surface. You can make a first order approximation of a pyrocumulus cloud by putting a very strong heat source at the surface in an environment otherwise favorable for severe convection. What you'll observe is that parcels will easily reach the LFC and you will have tons of CAPE owing to the high surface temperature. The maximum theoretical updraft velocity is a function of CAPE and so we can expect exceptionally strong updrafts. This can be confirmed by the observation of severe hail falling from these clouds -- the weight the hailstones can attain increases with updraft velocity. Because we can observe hail we know that normal moist processes we expect in cumulonimbus clouds are working. In any mid-latitude cumulonimbus cloud the precipitation starts out as snow. What we experience on the ground is dependent on the temperature profile and this snow either makes it to the surface, melts to be become rain, melts then becomes supercooled (freezing rain) or melts and refreezes (sleet). Another option is that the precipitation sublimates or evaporates and never reaches the ground. The fire driving the storm is likely producing a warm, dry environment at low levels and promoting evaporation of any precipitation. Graupel will exist as riming and accretion processes are at work, but because of the strong updraft you will end up with hail production and hail at the surface. To take this approximation into reality you also need to take into account how the fire is modifying the low and mid levels and what kind of aerosols are being emitted by the fire. The aerosol content could play heavily into the microphysics and precipitation production, but this is not my area of expertise so I won't speculate on the possibilities.
{ "pile_set_name": "StackExchange" }
Q: Do I have to create a new instance of fileinputstream if the file is changed constantly? I have a xml log that is modified constantly by another application; however my Java code runs concurrently and checks for a couple of strings. I am using a SAX Parser. Now my question is will I have to have a new instance of a FileInputStream every time I loop through the file? How about the parser? So let's say: while(notfound) { FileInputStream fis = new FileInputStream(new File("c:/tmp/123.xml")); SaxParser.parse(fis, sampleHandler); notFound = sampleHandler.checkIfFound(); } Thanks :D A: In the example you provided, you will need a new FileInputStream each time you want to start reading from the beginning of the file. Stream classes don't often allow for manual positioning/resetting of the 'location', as since the name ('Stream') implies, it's just a pipe with bits spewing out of it. Since you're using the SaxParser.parse() class method to initiate the parsing, it doesn't seem as though you actually have a parser object to re-create. So you should be fine with just re-creating the FileInputStream. But! It seems like current versions of the SaxParser class support passing in a File instance as the first parameter, so you can just repeatedly use: while(notfound) { SaxParser.parse(new File("c:/tmp/123.xml"), sampleHandler); notFound = sampleHandler.checkIfFound(); } Avoiding the re-creation of the FileInputStream altogether, and allowing the parser to handle that.
{ "pile_set_name": "StackExchange" }
Q: How to add one array into 2 sections UITableView Here is my code: - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger numberOfRowsPerSection = 0; if (section == 0) { for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) { BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i]; if ([item valueInDollars] > 50) { numberOfRowsPerSection ++; } } }else{ for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) { BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i]; if ([item valueInDollars] == 73) { numberOfRowsPerSection ++; } } } return numberOfRowsPerSection; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; if (!cell) { cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"]; } BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]]; if ([p valueInDollars] > 50 && indexPath.section == 0) { [[cell textLabel] setText:[p description]]; }else if(indexPath.section == 1){ [[cell textLabel] setText:[p description]]; } return cell; } -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } I want to display in one section results > 50 and the other section the rest of the result but I don't know how to do it. I am getting duplicate results in each section. Thanks A: Your code doesn't reflect what you're describing ( > 50 and == 73 are kind of intersecting): if (section == 0) { for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) { ... if ([item valueInDollars] > 50) { ... } } }else{ for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) { ... if ([item valueInDollars] == 73) { ... } } } And this line is incorrect too: BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]]; because the indexPath.row will go with an indexPath.section (it means the row is relative to the section, not to the whole table). This is main cause of your problem having the same results for both sections. Anyway, my suggestion for you is to perform a preprocessing step (maybe in viewDidLoad or somewhere else) to split your array into 2 arrays (one for each section) instead of using only one array for both sections.
{ "pile_set_name": "StackExchange" }
Q: iPhone does not recognize PhoneGap's navigator.app I have a button to exit from the application. The function looks like this: //Close application function close_window() { navigator.app.exitApp(); } It did not work, so I tried the following line: navigator.device.exitApp(); It did not work either. Then I discovered by alert that the iPhone does not recognize PhoneGap's navigator.app and navigator.device. I use PhoneGap version 2.2.0. Why is this happening? P.S.: It works for me on Android. A: navigator.app.exitApp() does not work on IOS, only Android. On iOS, Apple does not allow apps to programmatically exit. It can be done through iOS objective c side but there's a good chance this app will be rejected in Apple app store. Here you will find a good explanation: https://groups.google.com/forum/?fromgroups=#!topic/phonegap/XjTm0ua4uOY.
{ "pile_set_name": "StackExchange" }
Q: jquery v1.7.1 select() function don't work in IE9 my code is: <!DOCTYPE html> <html> <head> <title>Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(function(){ var textarea = document.createElement('textarea'); $(textarea).val("abc").select(); $(textarea).select(); $("body").append($(textarea)); }); </script> </head> <body> </body> </html> this code can work in chrome and firefox,but don't work in IE9,who can help me,thanks! UPDATE: error on : $(textarea).val("abc").select(); A: You may have more luck if you move the .select() line to AFTER the append() line. Also, try $(textarea).focus().select(); instead. This works for me in IE8 at least - don't have IE9 handy. edit: My approach would be something like $(function(){ var textarea = document.createElement('textarea'); $(textarea).val("abc"); $("body").append($(textarea)); $(textarea).focus().select(); });
{ "pile_set_name": "StackExchange" }
Q: Knockoutjs foreach n rows check if dropdown has value I have this html markup: <!-- ko foreach: Orders --> <div class="row"> <div> <select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }"> </select> </div> <div> <a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right"> <span class="glyphicon glyphicon-cloud-download"></span> Download </a> </div> </div> <!-- /ko --> There will be n number of items in the foreach loop, that will not be known in the moment of development. What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message. So in the RequestImage that action should happen, this is the RequestImage function currently: self.RequestImage = function () { }; How can I achieve this? Update OrdersVM: var self = this; self.Orders = ko.observableArray([]); $.ajax({ type: "POST", url: "/webservices/InfoWS.asmx/GetOrders", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if (data.d != null) { var orderIds = []; ko.utils.arrayForEach(data.d, function (item) { item._teacherOrders = ko.observable(); $.ajax({ type: "POST", url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount", contentType: "application/json; charset=utf-8", data: "{'orderId': " + JSON.stringify(item.OrderId) + "}", dataType: "json", success: function (data) { if (data) { return item._teacherOrders(data.d); } }, error: function (n) { alert('Error retrieving teachers for orders, please try again.'); } }); item.TeacherNames = ko.computed(function () { return item._teacherOrders(); }); self.Orders.push(item); orderIds.push(item.OrderId); }); } }, error: function (data) { var response = JSON.parse(data.responseText); console.log("error retrieving orders:" + response.Message); } }); A: I would do it this way: add an observable selectedTeacher to every order object add value: selectedTeacher to your selects: <select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select> check that observable in your RequestImage event if ( !data.selectedTeacher() ) { alert('Error: select teacher') } else { alert('Success') } A working demo - Fiddle
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get similar feature to Warmage Edge without becoming a Warmage? I am levelling up an sorcerer npc, that accompanies PCs. He focuses on the use of fire magic. I really enjoyed Warmage Edge class feature and I wonder, if there is some similar feature, that may be obtained by a feat or magic item, but would be charisma based and would affect more than "only warmage spells". I was hoping I could find something in Complete Arcane or Divine, but sadly there was nothing. Warmage Edge (Ex): A warmage is specialized in dealing damage with his spells. Whenever a warmage casts a spell that deals hit point damage, he adds his Intelligence bonus (if any) to the amount of damage dealt. For instance, if a 1st-level warmage with 17 Intelligence casts magic missile, he deals 1d4+1 points of damage normally, plus an extra 3 points of damage due to his Intelligence bonus. The bonus from the warmage edge special ability applies only to spells that he casts as a warmage, not to those he might have by virtue of levels in another class. A single spell can never gain this extra damage more than once per casting. For instance, a fireball deals the extra damage to all creatures in the area it affects. However, if a 3rd-level warmage casts magic missile and produces two missiles, only one of them (of the warmage's choice) gains the extra damage, even if both missiles are directed at the same target. If a spell deals damage for more than 1 round, it deals this extra damage in each round. 3.0, 3.5, Dugeon Adventures and Dragon Magazines allowed. A: No, there is no existing pre-made effect that will accomplish both the granting of that class feature and switch the keyed stat. However, there are rules for creating new content built into the game. As such, you can work with your DM and create exactly such an item. For example, there are items, feats, spells, and powers which DO grant access to a class feature (just not the one you want), and there are also methods of switching the keyed stats (usually via a feat). Therefore, find an in-game example of each: a warmage, an effect which grants a class feature (such as a Monk's belt), and an effect which switches the key stat (preferably an effect which specifically switches the key stat from the warmage primary stat to your desired stat) in the game world, and use the item creation rules and or spell/power research rules in conjunction with the example(s) as a template to craft/develop what you want. Might be pricey, but then you also have the advantage of DM approval built into the process. Also, some people have issues with the Monk's Belt, considering it to be an unbalancing effect as it can be used to grant, among other things, a boost to AC beneficial for any WIS focused character. This also gives you a great excuse to go on a quest in your game to collect all the things (people in some cases) you'll need.
{ "pile_set_name": "StackExchange" }
Q: Issues putting a hard drive in the optical bay of my early 2011 MacBook Pro I'm asking for help for my brother! I recently switched over to a dual hard-drive setup, and it worked perfectly. However, my brother is having issues. First off, here is the hard drive we are trying to put in. He has an early 2011 15" MacBook Pro. We read up online, and people said that the optical bay for his model only has SATA II, while the main bay has SATA III, which means he should put his HDD in the optical bay, and the SSD in the main bay. He wants to put the HDD in the optical drive area, and then transfer everything over to the new HDD, before putting the SSD into the main bay. The issue is that when we put the HDD in the optical bay, the computer can basically not recognize or use it. If plug the HDD in via a usb cord, he can initialize it and erase it to Mac OSX Extended (Journaled) perfectly fine. It only takes a few seconds, and as far as I can tell, it works. However, when he actually puts the hard drive in the optical bay, it either doesn't show up in disk utility, or it shows up, but can't be accessed or changed. We left it in, and it showed up after 30 minutes or so. When he tried to initialize it, however, the computer said it'd take 5 hours to do. The progress bar ended up getting half way done, and then stopping, so that didn't even work. We thought that maybe it could be a firmware issue after searching on the internet some, but we looked and definitely have the newest firmware version (2.7, I believe). Also, I don't think that issue applies to us, since I think it's only relevant to getting the proper speeds out of a SSD. We also tried just initializing it before putting it into the computer, but the computer doesn't seem to recognize it correctly. The name is changed from "New HDD" to "disk1s1", and we can't actually access it. That's when we tried initializing it again, just for the progress bar to get stuck. Looking online, this setup should work. Tons of people have done it, even using the hard drive we are using. We aren't even trying to put a SSD in yet, which is where most people have problems with the 2011 model. This is just a regular hard drive! I don't understand what could be wrong, and could use some help! If there's anywhere else you think I should post this, just let me know! Thank you! A: I believe the issue to be that the controller is still SATA III for the optical bay, yet the connector is a SATA II type, as is the cable. So if you try and place a SATA III enabled drive in the optical bay, it will try and negotiate at SATA III speed (6G). This creates an issue as the cable is not setup for this and the crosstalk, and very low SNR at that speed causes many errors. I got my Seagate Momentus SSHD disk drive working somewhat in the optical bay by wrapping it and the short cable in tin foil, making it a good ground to the chassis, but it still had loads of errors on it. I ended up putting a SATA II disk in which works. My Macbook is a 2012 13in with an 2.9GHz i7 in it. This shows both connectors as 7 series Intel Chipset, both of them are supported for 6G, yet the optical drive is negotiated as 3G (SATA II). My Samsung SSD in the HDD bay, is negotiated as the full 6G. Have a check in system profiler to see what supported speeds and negotiated speeds you are seeing for your controllers. There seems to be a lot of conflicting information about what model supports what, but it makes sense that the controllers are the same type on the main board for the particular chipset being used. The connectors are different though. I was hoping there would be a hard disk that you can force SATA II on, or some way of enforcing the controller to only ever negotiate up to 3G, but thus far haven't had any luck :-( Hope that helps demystify the core issue at stake here somewhat.
{ "pile_set_name": "StackExchange" }
Q: Can you represent the same example using Procedural, Functional, Logic and OO programming Languages? Can anyone please provide me with an example that can help me to understand Procedural, functional, Logic and Object Oriented programming models side by side by using nearly same example-problem. Please give me example code-snippets of the somewhat same problem using Procedural, Functional, Logic and OO programming languages. A: http://99-bottles-of-beer.net/ (It features my own horribly contrived 99 language.) A: Let's try simpler example - just calculating n-th Fibonacci number. First, procedural (in Pascal): program Fibonacci; function fib(n: Integer): Integer; var a: Integer = 1; b: Integer = 1; f: Integer; i: Integer; begin if (n = 1) or (n = 2) then fib := 1 else begin for i := 3 to n do begin f := a + b; b := a; a := f; end; fib := f; end; end; begin WriteLn(fib(6)); end. This example shows features of procedural languages: There are some subroutines (function in this case) Variables are assigned value probably multiple times ( := operator) There are cycles (for operator in this case) Language is imperative, i.e. we are telling computer what to do in what order Second, object oriented (in Python): class Fibonacci: def __init__(self): self.cache = {} def fib(self, n): if self.cache.has_key(n): return self.cache[n] if n == 1 or n == 2: return 1 else: a = 1 b = 1 for i in range(2, n): f = a + b; b = a; a = f; self.cache[n] = f; return f; fibonaccyCounter = Fibonacci() print fibonaccyCounter.fib(6) Actually the problem is not worth creating a class, so I added caching of already calculated results. This example shows: class and its instantiation (creating instance) class has own section of memory, own state (self and its members) Language is imperative, i.e. we are telling computer what to do in what order Not shown but we can e.g. descend this class from abstract class returning n-th member of some sequence. By subslassing we get class defining Fibonacci sequence, sequence 1,2,3..., sequence 1,4,9,16,... etc. Third, in functional style (Haskell): import Text.Printf fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) main = printf "%d\n" (fib 6) Following features of a functional programming paradigm are demonstrated: there is no state, no variables - just functions defined there are no cycles - only recursion pattern matching: we separately defined "fib 0", "fib 1" and "fib n" for rest of numbers, no constructs like if were needed declarative style - we don't define the order of steps to calculate main function value: the compiler/interpreter/runtime figures this out by itself, given the function definitions. We tell the computer what we want to get, not what to do. Lazy evaluation. If main was calling only "fib 2" then "fib n" was not called because functions are evaluated only when their result is needed to be passed as parameter to other functions. But the main feature of functional languages is that functions are first class objects. This can be demonstrated by other implementation of fib: fib n = fibs!!n fibs = 0 : 1 : zipWith (+) fibs (tail fibs) Here we are passing fibs function as parameter to zipWith function. This example also demonstrates lazy evaluation: "infinite" list is computed only to extent it is needed for other functions. By the way, functional does not necessary mean not object oriented. An example of programming language that is both functional and object oriented is Scala. Prolog: fib(1, 1). fib(2, 1). fib(X, Y):- X > 1, X1 is X - 1, X2 is X - 2, fib(X1, Z), fib(X2, W), Y is W + Z. main :- fib(6,X), write(X), nl. Following features of logic programming style can be seen: Language is declarative. As in functional style, we define things and not telling in what order to do them. But the difference with functional style is that we define predicates, not functions. In this case, predicate fib(X, Y) means "X-th Fibonacci number is Y". Given some known predicates (fib(1, 1) and fib(2, 1) - i.e. first Fibonacci number is 1 and second Fibonacci number is 1) and rules to infer other predicates (Y is X-th Fibonacci number is Y is a sum of X-1th Fibonacci number and X-2th Fibonacci number), Prolog infers predicates in question. Actually there could be more than 1 answer! There is no input values and return value - instead of this we define a relation between "input" and "output". This program could also be used to find out that Fibonacci number 8 is at 6th position in the sequence: ?- between(0,inf,X), fib(X,8). X = 6 . A: Project Euler Problem number 2: http://projecteuler.net/problem=2 Haskell (functional/logic): p2 = sum [x | x <- fibs, (x `mod` 2) == 0] where fibs = unfoldr acc (0,1) where acc (prev, cur) | (prev+cur) > 4000000 = Nothing | otherwise = Just (prev+cur, (cur, prev+cur)) Python (OO): class FibSum(object): def __init__(self, end): self.end = end self.next_two = (1,0) self.sum = 0 def __iter__(self): return self def next(self): current, previous = self.next_two self.next_two = (previous+current, current) new = current+previous if current >= self.end: raise StopIteration elif (new % 2) == 0: self.sum += new else: pass fibcount = FibSum(4000000) [i for i in fibcount] print fibcount.sum C (procedural/imperative): #include <stdio.h> int main(void) { long int sum, newnum, previous = 0; long int current = 1; while(current <= 4000000) { newnum = previous+current; if ((newnum % 2) == 0) { sum = sum + newnum; } previous = current; current = newnum; } printf("%d\n", sum); } And here is a very inefficient version written in MIT Scheme (define (unfold func seed) (let* ((result (func seed))) (cond ((null? result) ()) (else (cons (car result) (unfold func (second result))))))) (define (test x) (cond ((> (sum x) 4000000) ()) (else (list (sum x) (list (second x) (sum x)))))) (define (sum xs) (cond ((null? (cdr xs)) (first xs)) (else (+ (car xs) (sum (cdr xs)))))) (sum (filter (lambda (x) (eq? (modulo x 2) 0)) (unfold test (list 0 1)))) Prolog: Take from this here, posted by 13tazer31 fibonacci(_,Current,End,0) :- Current > End. fibonacci(Previous, Current, End, Total) :- divisible(Current, 2), Next is Current + Previous, fibonacci(Current, Next, End, Sum), Total is Sum + Current, !. fibonacci(Previous, Current, End, Total) :- Next is Current + Previous, fibonacci(Current, Next, End, Total). divisible(Number, 0) :- write(‘Error: division by 0′). divisible(Number, Divisor) :- Number mod Divisor =:= 0.
{ "pile_set_name": "StackExchange" }
Q: AngularJS html5Mode refresh fails So this is my router: var app = angular.module('tradePlace', ['ngRoute', 'tradeCntrls']); app.config(['$routeProvider', '$locationProvider', function($route, $location) { $route. when('/', { redirectTo: '/index' }). when('/index', { templateUrl: './includes/templates/index.php', controller: 'indexCntrl' }). when('/register', { templateUrl: './includes/templates/register.php', controller: 'indexCntrl' }). otherwise({ redirectTo: '/index' }); $location.html5Mode(true); }]) I have html5 mode true, so now the URL have not a # in it. If I go to mysite.com/ it redirect`s me to /index but when I reload the page (f5) or go to mysite.com/index I get a 404 error. Is there a way to fix this? Or just don`t use html5 mode? A: For Apache use in your .htaccess: RewriteEngine On RewriteBase / RewriteRule ^index.php - [L] #your static data in the folder app RewriteRule ^app - [L] #everything else RewriteRule ^(.*)$ index.php?para=$1 [QSA,L] EDIT: The whole requested url is passed as para to the php file. You can further process this in the php skript with $_GET['para'] if needed. Apache rewrites your request and delivers the file which match the rules. i.e. request: http://somehost.com/blabla -> index.php?para=blabla http://somehost.com/app/mainapp.js -> app/mainapp.js
{ "pile_set_name": "StackExchange" }
Q: angular promise queue and showing loading data I am using angular's $q promise like this: $scope.loadingData = true; // show loading spinner in view var thingsToProcess = [....]; for(int i = 0; i < thingsToProcess.length; i++) { var itemToProcess = thingsToProcess[i]; makeServiceCallThatReturnsPromise(itemToProcess) .then(function(response) { processAndDisplayResponse(response); }); } $loadingData = false; // hide loading spinner Since the service call promises get queued, the loading indicator goes away before all the data is returned from the service. How can I keep the loading flag set till all the promises are served? A: you can use $q.all() here, var promises=[]; for(int i=0; i<thingsToProcess.length; i++) { var itemToProcess = thingsToProcess[i]; promises.push( makeServiceCallThatReturnsPromise(itemToProcess) .then(function(response) { //do some work here ? })); } $q.all(promises).then(function(){ processAndDisplayResponse(response); })
{ "pile_set_name": "StackExchange" }
Q: jQuery ScrollTO with data attributes I really need help with this issue, my knowledge with JS is not that good. So, basically I want to scroll to the section when the link is clicked, but not through (href="#target"), I want to do it with attributes. Also, I want to add attribute offset from top as well if it is possible. Please take a look at the code, you will get a clearer picture. HTML Example: <nav> <a href="#" data-attr-scroll="#section1" class="scrollto">Section 1</a> <a href="#" data-attr-scroll="#section2" class="scrollto">Section 2</a> <a href="#" data-attr-scroll="#section3" class="scrollto">Section 3</a> <a href="#" data-attr-scroll="#section4" class="scrollto">Section 4</a> <a href="#" data-attr-scroll="#section5" class="scrollto">Section 5</a> </nav> <div class="test" id="section1"> #1 Section </div> <div class="test" id="section2" data-scroll-offset="100"> #2 Section </div> <div class="test" id="section3"> #3 Section </div> <div class="test" id="section4" data-scroll-offset="200"> #4 Section </div> <div class="test" id="section5" data-scroll-offset="300"> #5 Section </div> JS example: jQuery(document).ready(function($) { $(".scrollto").click(function(event) { event.preventDefault(); var defaultAnchorOffset = 0; var $anchor = $(this).attr('data-attr-scroll'); var anchorOffset = $anchor.attr('data-scroll-offset'); if (!anchorOffset) anchorOffset = defaultAnchorOffset; $('html,body').animate({ scrollTop: $anchor.offset().top - anchorOffset }, 500); }); }); CSS example: nav { position: fixed; top: 20px; right: 20px; } .test { height: 500px; } I know that JS code is bad. If anyone can help me, I would be very grateful. Thank you in advance. Regards, Danny Fiddle Demo A: here you go, i´d rather take a string representation of the id and concatinate the selector, it works fine ! jQuery(document).ready(function($) { $(".scrollto").click(function(event) { event.preventDefault(); var defaultAnchorOffset = 0; var anchor = $(this).attr('data-attr-scroll'); var anchorOffset = $('#'+anchor).attr('data-scroll-offset'); if (!anchorOffset) anchorOffset = defaultAnchorOffset; $('html,body').animate({ scrollTop: $('#'+anchor).offset().top - anchorOffset }, 500); }); }); i think it didnt work cause you tryed to cast an object from a string heres a fiddle, have fun ! http://jsfiddle.net/JcEb3/1/
{ "pile_set_name": "StackExchange" }
Q: When are C++ operators really inlined? From http://cs.brown.edu/~jak/proglang/cpp/stltut/tut.html and http://www.geeksforgeeks.org/c-qsort-vs-c-sort/, we find that using the STL's sorting mechanism is faster than C's qsort(). This is because the comparison function is "inlined". However, when using the compiler explorer at https://godbolt.org/ to inspect the output of the gcc compiler, I can't get any operators to actually become inlined. See here for an example, code given below: #include <string> #include <algorithm> #include <vector> #include <cstdlib> #include <iostream> using namespace std; class myClass { public: int key; int data; myClass(int k, int d) : key(k), data(d) {} inline bool operator<(myClass& other) { return key < other.key; } }; main () { myClass c1(1,100), c2(2, 100); if (c1 < c2) cout << "True" << endl; else cout << "False" << endl; } The generated assembly code clearly makes a call to the operator< routine. The C++ compiler completely disregarded the inline keyword! So when exactly are the operators inlined? This is the key to having faster sorting performance for example, but it would be nice to know how to take advantage of it whenever possible. A: Most compilers will not inline anything at all by default, because this can get in the way of debugging. You need to enable optimizations. gcc has a handful of levels of optimizations and many individually tweakable optimization settings, but even the simplest "-O1" flag is enough to cause your example to inline the operator< function. (In fact, gcc actually realized it could determine the result of operator< at compile time, and was able to discard the else branch entirely!)
{ "pile_set_name": "StackExchange" }
Q: Can a Kantian bluff in poker? Kantians aren't allowed to lie---if it were a universal law of nature that everyone lied all the time, no communication would be possible at all, no words would have meaning, and lying itself would become impossible. Poker is a game that involves a lot of lying. Or if not lying, something very much like lying: systematic attempts to mislead people, aka bluffing. (Actually I don't think this is supposed to be much of the game for pros. When you get really good it's just about statistics.) But since everyone knows we are going to lie in poker the situation seems to be somewhat different than in normal communication. Does this make a difference? Can a Kantian bluff in poker? A: Bluff - lying - in poker is a case of what Onora O'Neill terms selective falsehood. Let her explain this idea before I go further : Another alluring, but on reflection impossible, maxim of communication to which Kant turned his attention (in a form few of his admirers find adequate) is that of falsehood. ... [I]t appears that a maxim of falsehood in communication could not serve as a universal principle of communications among a plurality of rational beings, or beings who are becoming rational. For if falsehood became the maxim of "communications" among such beings, comprehension itself would cease, and so also the possibility of communication. This is not to say that a maxim of selective falsehood would be an impossible one for regulating the communicating of a plurality of partially free and rational beings. Plenty of actual communities get on well with a universally shared convention of falsehood in response to intimate inquiries or about punctuality or in relations with strangers. But the very possibility of recognizing what is said in such contexts as falsehood presupposes comprehensibility, and thus also that standards of truth-telling obtain more generally in such communities.' (O. O'Neill, Constructions of Reason : Explorations of Kant's Practical Philosophy, Cambridge : CUP, 1989, 45.) The main point is that what is up for universalisation in your question is not lying simpliciter but a mutually voluntary activity (the game of poker) in which people agree for purposes of gain or entertainment to engage in a competition with specific other persons in which they and the others know that lying (within limits) is allowed. This is selective lying. There is no reason why the maxim, 'agree for purposes of gain or entertainment to engage in a competition with specific other persons in which they and the others know that lying (within limits) is allowed', cannot be universalised - that it involves a contradiction in conception or a contradiction in the will. But the reply may come : Kant rules out lying and you cannot get around this by contextualising lying. Why not ? Two points : first in the Groundwork the prohibition on lying precisely is contextualised : it is contextualised to making a lying promise to repay a debt (§§ 18-19). While the maxim behind this cannot be universalised, the maxim behind my poker case can be. And in 'On a Supposed Right to Lie from Philanthropy' Kant says : Truthfulness in statements that one cannot avoid is a human being's duty to everyone, however great the disadvantage to him or to another that may result from it ... (SRL 8:426). (McGregor Cambridge tr.) The immediate context is the supposed right to lie to the murderer at the door. But lying in poker is hardly a violation of 'Truthfulness in statements that one cannot avoid'. It is, and is recognized as, selective lying. The second point is that we need to draw a distinction between what Kant thought the universalisation constraint implies in particular cases or types of case, and what it actually does imply. Even if Kant had pronounced against bluff in poker, it would not follow that the universalisation constraint cannot, as I have argued above, consistently allow it. A: Can a Kantian bluff in poker? What an interesting question. I do not believe that bluffing in poker is the same as lying in daily life for the same reason that acting in theater is not lying. The players and actors agree to follow a specialized set of rules that apply to a single activity which is outside the collection of transactions that people encounter every day. Other writers have arrived at a similar conclusion. Perverse Egalitarianism, "Running The Red Light, Being Late For A Poker Game", April 5, 2009. The article is here; https://pervegalit.wordpress.com/2009/04/05/running-the-read-light-being-late-for-a-poker-game/
{ "pile_set_name": "StackExchange" }
Q: How to create a kotlin live template for newInstance Fragments using Android studio I'm searching for a way to create a new Kotlin live code template so that whenever I type newIns.... it and hit tab it will be able to print the following as a live template choice: companion object { fun newInstance(b: Bundle): DetailsFragment { val frag = DetailsFragment() frag.arguments = b return frag } } In Java, it was done the same way and there is already a "newInstance" abbreviation and a live template exists in Android Studio. I want the same thing for Kotlin. Let me show you a photo : Notice that, Java Android already has newInstance template. I want this for Kotlin. Here is what I have so far: and the template code I have so far looks like this: companion object { fun newInstance($args$:Bundle):$fragment$ { $nullChecks$ android.os.Bundle args = Bundle(); $addArgs$ $fragment$ fragment = $fragment$(); fragment.setArguments(args); return fragment; } } but when I exit the settings and in Kotlin type the first few words of the abbreviation and hit tab or ctrl + spacebar on mac nothing happens. I guess I have the syntax wrong, I'm not sure. Anyone of suggestions? A: Step 1: Go to Live Templates section in Android Studio. For Windows: File > Settings > Editor > Live Templates For Mac: Android Studio > Preferences > Editor > Live Templates Step 2: Select Kotlin template group. Then tap on + present at the top-right corner of the popup. Select Live Template. Step 3: Now you can add your live template. Check at the bottom of the popup. Add abbreviation: newInstance Add description: Creates an instance of the fragment with arguments Add template text: companion object { fun newInstance(args: Bundle): $fragment$ { val fragment = $fragment$() fragment.arguments = args return fragment } } Add applicable context. Tap on Define. Select Kotlin from the list. Select Reformat according to style Step 4: Tap on Edit Variables below the description. Now tap on Expression for the variable name fragment. Tap on down arrow. You can see a list of expressions. From there select kotlinClassName(). Tap on OK of the Edit Templates Variable Now tap on Apply and OK of the Live Templates. To check type newInstance in a Fragment written in Kotlin.
{ "pile_set_name": "StackExchange" }
Q: c# でのデバッグの時のみ走るロジックの書き方 c#において、if def相当のデバッグ用ロジックはどう書けば良いですか? A: C言語と同様に#if #else #endifのプリプロセッサ ディレクティブが使えます。またデバッグビルドを行う際、DEBUGが定義されるよう構成されているため#if DEBUGと記述することができます。 ただし、これは厳密には「デバッグの時のみ走る」でなく、デバッグビルドの場合は常に走ります。 一般にデバッグ時/非デバッグ時で処理を分けるべきではありません。しかし、適切に動作しているかのチェックコードを埋め込むことはよくあり、C#言語においても、Debug.Assertメソッドが用意されています。こちらもデバッグビルドの場合は常に走るチェックコードとなります。 厳密な意味で「デバッグの時のみ走る」ですとDebugger.IsAttachedプロパティが用意されています。デバッグ中=デバッガーに接続されている場合にのみこのプロパティはtrueを返しますので、if文で判定して必要なロジックを書くことができます。
{ "pile_set_name": "StackExchange" }
Q: Where can I find some amusing cartoons about software testing? I came across this Dilbert cartoon this week that I thought was pretty funny. What other good software testing related cartoons are out there? A: Here's one that has a short list (the site hasn't been around long). http://www.softwarequalityconnection.com/cartoon-archive/ You can also find a pretty good list here: http://www.softwaretestpro.com/List/Cartoons And that actually has several links to http://cartoontester.blogspot.com/ I've made this a community wiki so that others can add to the list.
{ "pile_set_name": "StackExchange" }
Q: ExportToJPEG - can't change resolution, always resets to default In ArcGIS Pro (latest version), using the ExportToJPEG (or even ExportToPNG) arcpy function, I can't seem to export an image with my desired resolution. It always defaults to 96 dpi even when I specify 500. What am I doing wrong? Is this a bug? This is the script I paste into the python console within ArcGIS Pro: p = arcpy.mp.ArcGISProject("CURRENT") print ("project loaded") l = p.listLayouts("MyLayout")[0] print ("layouts listed") if not l.mapSeries is None: ms = l.mapSeries if ms.enabled: for pageNum in range(1, ms.pageCount + 1): ms.currentPageNumber = pageNum print("Exporting page {0} of {1}".format(str(ms.currentPageNumber), str(ms.pageCount))) l.exportToJPEG(r"C:\\Users\\Theo\\Dropbox\\site_plans\\Current_GR_site_plans\\GR2-GroundMovement-SP-_{0}".format(str(ms.currentPageNumber) + ".jpg", 500)) You can see at the end I specify 500 as the resolution. Even when I write- resolution = 500, it's the same. My images aren't coming out in my desired quality. If I export a single page using the share ribbon, setting the dpi to 500, it works. But I'm automating this, so that's not a viable option for me. Guides I've used: https://community.esri.com/external-link.jspa?url=http%3A%2F%2Fpro.arcgis.com%2Fen%2Fpro-app%2Farcpy%2Fmapping%2Fmapframe-class.htm https://community.esri.com/external-link.jspa?url=http%3A%2F%2Fpro.arcgis.com%2Fen%2Fpro-app%2Farcpy%2Fmapping%2Flayout-class.htm similar issue to: https://community.esri.com/thread/201455-exporttojpeg-resolution-problem ExportToJPEG() arcpy script failure (ArcMap) neither helped me. A: Syntax error, found on official ESRI website (they have been informed). Essentially, the last line has a closing bracket out of place. The line SHOULD read: l.exportToJPEG(r"C:\\Users\\Theo\\Dropbox\\site_plans\\Current_GR_site_plans\\GR2-GroundMovement-SP-_{0}".format(str(ms.currentPageNumber)) + ".jpg", 500)
{ "pile_set_name": "StackExchange" }
Q: What is the correct usage of arriviste/parvenu? In one of the episodes of the TV show Rosemary & Thyme the word arriviste/parvenu was used. Context how it was used: Person A considers person B as an arriviste/parvenu. Person A is rich and has been growing orchids all his life. Person B recently starts growing orchids. My question is, can the words arriviste/parvenu be used for making political accusations? In the following context, Politician A considers Politician B as an arriviste/parvenu. Politician A: very senior Politician B: new to politics A: I think you're guessing well at the origin of the words, because how you seem to be interpreting them is close to their original French meanings. However, often loan-words are borrowed to serve a particular purpose only and so have a narrower meaning in English than the original form. (The inverse can sometimes happen too). Arriviste and Parvenu both describe someone who is "new money"; wealthy but without the social knowledge that allows one to fit into the social class of those who've enjoyed a similar level of wealth all their lives. Both terms are used from a class-conscious position where the terms are negative because such people "don't know their place", or at the very least are so lacking in "class" that they cause embarrassment. Arriviste is perhaps a bit more aggressive in this than parvenu, but neither are nice things to call someone. Can the words arriviste/parvenu be used while making political accusations? Yes, extending the word to figuratively cover the political sphere, but you would have to do so from a distance, and even then it would be fraught. The terms are associated with a snobbish attitude, and so while a pundit might get away with it they might also just seem prejudiced and anti-democratic. A rival politician would be much less likely to get away with it, because opponents would be sure to seize on it much as when the British Government Chief Whip was forced to resign after allegations that he called police officers "plebs". You couldn't get away with it in public, but you might in private among some like-minded friends, but really you'd only be likely to do so if you actually were a bit of a snob anyway.
{ "pile_set_name": "StackExchange" }
Q: How to handle orientation change using fragment? I now have 2 fragment, one fragment handle portrait mode then another handle landscape mode. But the problem is that when rotate from portrait to landscape then back to portrait. It will not show the same thing that show on the first portrait mode. Is there any code that can solve this problem? This code is inside the fragment holder: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.frag_holder); FragmentManager fm = getSupportFragmentManager(); final Fragment fragment = Frag.newInstance(); //Portrait layout final Fragment fragment2 = Frag2.newInstance(); //Landscape layout int orientation = getResources().getConfiguration().orientation; //check whether is it portrait or landscape if(orientation == Configuration.ORIENTATION_PORTRAIT){ Fragment fragTAG = fm.findFragmentByTag(TAG_P); if(fragTAG == null){ Log.i("test","test"); fm.beginTransaction() .replace(R.id.fragPlaceHolder, fragment, TAG_P) .commit(); //Portrait } else{ fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit(); } } if(orientation == Configuration.ORIENTATION_LANDSCAPE){ Fragment fragTAG = fm.findFragmentByTag(TAG_L); if(fragTAG == null){ fm.beginTransaction() .replace(R.id.fragPlaceHolder, fragment2, TAG_L) .commit(); //Landscape } else{ fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit(); } } } } A: Step 1: Add Config changes in your activity <activity android:name=".ui.createtasks.CreateTaskActivity" android:configChanges="orientation|screenSize|keyboardHidden" > </activity> Step 2: Add your edit text values to onSaveInstanceState @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putCharSequence(KEY_TITLE, et_text.getText().toString()); } Step 3: Get your Saved edit text values through onViewStateRestored @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); String savedTitle = null; if (savedInstanceState != null) { savedTitle = savedInstanceState.getString(KEY_TITLE); et_text.setText(savedTitle); } }
{ "pile_set_name": "StackExchange" }