text
stringlengths
64
89.7k
meta
dict
Q: Get int from char[] of bytes I have a file that I read into a char array. The char array now holds a certain number of bytes, now if I know the file stored a 32bit integer in little endian at position say 0x8, how do I retrieve it from the char array? FILE * file = fopen("file"); char buffer[size]; fread(buffer,1,size,file); int = buffer[0x8]; // What should I do here? // I imagine it involves some strange pointer // arithmetic but I can't see what I should do, // casting to int just takes the first byte, // casting to (int *) doesn't compile A: you need to cast it like so: int foo = *((int *) &buffer[0x8]); Which will first cast the spot to a int pointer and the dereference it to the int itself. [watch out for byte-ordering across different machine types though; some do high bytes first some do low] And just to make sure the example is well understood, here's some code showing the results: #include <stdio.h> main() { char buffer[14] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13 }; int foo = *((int *) &buffer[0x8]); int bar = (int) buffer[0x8]; printf("raw: %d\n", buffer[8]); printf("foo: %d\n", foo); printf("bar: %d\n", bar); } And the results from running it: raw: 8 foo: 185207048 bar: 8 A: The "easy" way, assuming the array contains a byte of the same endianness as your machine, and that there aren't any special alignment requirements, is: int x = *(int *)&buffer[8]; If you do have an endianness difference, you'll need to handle that. If there's an alignment problem (or even potentially an alignment problem), you should extract the bytes one by one: int x = buffer[8] + (buffer[9] << 8) + (buffer[10] << 16) + (buffer[11] << 24); Or possibly the other direction if the endianness is the other way.
{ "pile_set_name": "StackExchange" }
Q: Python SimpleXMLRPCServer : Socket Error , Connection Refused I am trying to list the contents of a directory on a server. If the client and server code is executed on the same machine, it works perfectly. However, running the client code from another machine using the IP of the server gives me a Errno 111:Socket Error. Connection Refused Server Code : from SimpleXMLRPCServer import SimpleXMLRPCServer import logging import os # Set up logging logging.basicConfig(level=logging.DEBUG) server = SimpleXMLRPCServer(('localhost', 9000), logRequests=True) # Expose a function def list_contents(dir_name): logging.debug('list_contents(%s)', dir_name) return os.listdir(dir_name) server.register_function(list_contents) try: print 'Use Control-C to exit' server.serve_forever() except KeyboardInterrupt: print 'Exiting' Client code : import xmlrpclib proxy = xmlrpclib.ServerProxy('http://192.168.239.148:9000') print proxy.list_contents('/home/thejdeep/rpc_test/fd/') A: Try binding the server to 0.0.0.0 rather than localhost... server = SimpleXMLRPCServer(('0.0.0.0', 9000), logRequests=True)
{ "pile_set_name": "StackExchange" }
Q: Flash WebSocket class/library Where can I find Flash WebSocket class/library for Flash (not Flash builder, no mx classes)? Please provide an example if possible. A: websocket-as is probably the closest you'll find. However, it implements an older version of the WebSockets protocol, Hixei-75. Most browsers that have WebSockets (either on by default such as Chrome, or off by default like Firefox 4 and Opera 11) implement Hixie-76. The HyBi version of the protocol are coming soon. You might be able to adapt websocket-as to support the new protocol by looking at the implementation in web-socket-js which implements Hixie-76. web-socket-js is a shim/polyfill for WebSockets support in Javascript. web-socket-js uses mx.* classes however. There is a development branch of web-socket-js which implements HyBi-07. Update: Another project that tracks the current HyBi protocol pretty well is AS3WebSocket. AS3WebSocket uses some mx.* classes however.
{ "pile_set_name": "StackExchange" }
Q: How to get a "Glow" shader effect in OpenGL ES 2.0? I'm writing a 3D app for iOS. I'm new to OpenGL ES 2.0, so I'm still getting myself around writing basic shaders. I really need to implement a "Glow" effect on some of my models, based on the texturing. Here's a sample: . I'm looking for code examples for OpenGL ES 2.0. Most code I find on the internet is either for desktop OpenGL or D3D. Any ideas? A: First of all there are tons of algorithms and techniques to generate a glow effect. I just want to present one possibility. Create a Material that is luminescent. For this I use a modified Blinn-Phong light model, where the direction to the light source is always the inverse direction of the normal vector of the fragment. varying vec3 vertPos; varying vec3 vertNV; varying vec3 vertCol; uniform float u_glow; void main() { vec3 color = vertCol; float shininess = 10.0; vec3 normalV = normalize( vertNV ); vec3 eyeV = normalize( -vertPos ); vec3 halfV = normalize( eyeV + normalV ); float NdotH = max( 0.0, dot( normalV, halfV ) ); float glowFac = ( shininess + 2.0 ) * pow( NdotH, shininess ) / ( 2.0 * 3.14159265 ); fragColor = vec4( u_glow * (0.1 + color.rgb * glowFac * 0.5), 1.0 ); } In a second step a gaussian blur algorithm is performed on the output. The scene is written to frame buffer with a texture bound to the color plane. A screen space pass uses the texture as the input to blur the output. For performance reasons, the blur algorithm is first performed along the X-axis of the viewport and in a further step along the Y-axis of the viewport. varying vec2 vertPos; uniform sampler2D u_textureCol; uniform vec2 u_textureSize; uniform float u_sigma; uniform int u_width; float CalcGauss( float x, float sigma ) { float coeff = 1.0 / (2.0 * 3.14157 * sigma); float expon = -(x*x) / (2.0 * sigma); return (coeff*exp(expon)); } void main() { vec2 texC = vertPos.st * 0.5 + 0.5; vec4 texCol = texture( u_textureCol, texC ); vec4 gaussCol = vec4( texCol.rgb, 1.0 ); vec2 step = 1.0 / u_textureSize; for ( int i = 1; i <= u_width; ++ i ) { vec2 actStep = vec2( float(i) * step.x, 0.0 ); // this is for the X-axis // vec2 actStep = vec2( 0.0, float(i) * step.y ); this would be for the Y-axis float weight = CalcGauss( float(i) / float(u_width), u_sigma ); texCol = texture2D( u_textureCol, texC + actStep ); gaussCol += vec4( texCol.rgb * weight, weight ); texCol = texture2D( u_textureCol, texC - actStep ); gaussCol += vec4( texCol.rgb * weight, weight ); } gaussCol.rgb /= gaussCol.w; gl_FragColor = vec4( gaussCol.rgb, 1.0 ); } For the implementation of a blur algorithm see also the answer to the questions: OpenGL es 2.0 Gaussian blur on triangle What kind of blurs can be implemented in pixel shaders? See the following similar WebGL example which puts all together: var readInput = true; function changeEventHandler(event){ readInput = true; } (function loadscene() { var resize, gl, progDraw, progBlurX, progPost, vp_size, blurFB; var bufCube = {}; var bufQuad = {}; var shininess = 10.0; var glow = 10.0; var sigma = 0.8; function render(delteMS){ //if ( readInput ) { readInput = false; var sliderScale = 100; shininess = document.getElementById( "shine" ).value; glow = document.getElementById( "glow" ).value / sliderScale; sigma = document.getElementById( "sigma" ).value / sliderScale; //} Camera.create(); Camera.vp = vp_size; gl.enable( gl.DEPTH_TEST ); gl.clearColor( 0.0, 0.0, 0.0, 1.0 ); gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT ); // set up framebuffer gl.bindFramebuffer( gl.FRAMEBUFFER, blurFB[0] ); gl.viewport( 0, 0, blurFB[0].width, blurFB[0].height ); gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT ); // set up draw shader ShaderProgram.Use( progDraw.prog ); ShaderProgram.SetUniformM44( progDraw.prog, "u_projectionMat44", Camera.Perspective() ); ShaderProgram.SetUniformM44( progDraw.prog, "u_viewMat44", Camera.LookAt() ); var modelMat = IdentityMat44() modelMat = RotateAxis( modelMat, CalcAng( delteMS, 13.0 ), 0 ); modelMat = RotateAxis( modelMat, CalcAng( delteMS, 17.0 ), 1 ); ShaderProgram.SetUniformM44( progDraw.prog, "u_modelMat44", modelMat ); ShaderProgram.SetUniformF1( progDraw.prog, "u_shininess", shininess ); ShaderProgram.SetUniformF1( progDraw.prog, "u_glow", glow ); // draw scene VertexBuffer.Draw( bufCube ); // set blur-X framebuffer and bind frambuffer texture gl.bindFramebuffer( gl.FRAMEBUFFER, blurFB[1] ); gl.viewport( 0, 0, blurFB[1].width, blurFB[1].height ); gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT ); var texUnit = 1; gl.activeTexture( gl.TEXTURE0 + texUnit ); gl.bindTexture( gl.TEXTURE_2D, blurFB[0].color0_texture ); // set up blur-X shader ShaderProgram.Use( progBlurX.prog ); ShaderProgram.SetUniformI1( progBlurX.prog , "u_texture", texUnit ) ShaderProgram.SetUniformF2( progBlurX.prog , "u_textureSize", vp_size ); ShaderProgram.SetUniformF1( progBlurX.prog , "u_sigma", sigma ) // draw full screen space gl.enableVertexAttribArray( progBlurX.inPos ); gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos ); gl.vertexAttribPointer( progBlurX.inPos, 2, gl.FLOAT, false, 0, 0 ); gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx ); gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); gl.disableVertexAttribArray( progBlurX.inPos ); // reset framebuffer and bind frambuffer texture gl.bindFramebuffer( gl.FRAMEBUFFER, null ); gl.viewport( 0, 0, vp_size[0], vp_size[1] ); gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT ); texUnit = 2; gl.activeTexture( gl.TEXTURE0 + texUnit ); gl.bindTexture( gl.TEXTURE_2D, blurFB[1].color0_texture ); // set up pst process shader ShaderProgram.Use( progPost.prog ); ShaderProgram.SetUniformI1( progPost.prog, "u_texture", texUnit ) ShaderProgram.SetUniformF2( progPost.prog, "u_textureSize", vp_size ); ShaderProgram.SetUniformF1( progPost.prog, "u_sigma", sigma ); // draw full screen space gl.enableVertexAttribArray( progPost.inPos ); gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos ); gl.vertexAttribPointer( progPost.inPos, 2, gl.FLOAT, false, 0, 0 ); gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx ); gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); gl.disableVertexAttribArray( progPost.inPos ); requestAnimationFrame(render); } function resize() { //vp_size = [gl.drawingBufferWidth, gl.drawingBufferHeight]; vp_size = [window.innerWidth, window.innerHeight] canvas.width = vp_size[0]; canvas.height = vp_size[1]; var fbsize = Math.max(vp_size[0], vp_size[1])-1; fbsize = 1 << 31 - Math.clz32(fbsize); // nearest power of 2 fbsize = fbsize * 2 blurFB = []; for ( var i = 0; i < 2; ++ i ) { fb = gl.createFramebuffer(); fb.width = fbsize; fb.height = fbsize; gl.bindFramebuffer( gl.FRAMEBUFFER, fb ); fb.color0_texture = gl.createTexture(); gl.bindTexture( gl.TEXTURE_2D, fb.color0_texture ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, fb.width, fb.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); fb.renderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer( gl.RENDERBUFFER, fb.renderbuffer ); gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fb.width, fb.height ); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, fb.color0_texture, 0 ); gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, fb.renderbuffer ); gl.bindTexture( gl.TEXTURE_2D, null ); gl.bindRenderbuffer( gl.RENDERBUFFER, null ); gl.bindFramebuffer( gl.FRAMEBUFFER, null ); blurFB.push( fb ); } } function initScene() { canvas = document.getElementById( "canvas"); gl = canvas.getContext( "experimental-webgl" ); if ( !gl ) return null; progDraw = {} progDraw.prog = ShaderProgram.Create( [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER }, { source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER } ] ); if ( !progDraw.prog ) return null; progDraw.inPos = gl.getAttribLocation( progDraw.prog, "inPos" ); progDraw.inNV = gl.getAttribLocation( progDraw.prog, "inNV" ); progDraw.inCol = gl.getAttribLocation( progDraw.prog, "inCol" ); progBlurX = {} progBlurX.prog = ShaderProgram.Create( [ { source : "post-shader-vs", stage : gl.VERTEX_SHADER }, { source : "blurX-shader-fs", stage : gl.FRAGMENT_SHADER } ] ); progBlurX.inPos = gl.getAttribLocation( progBlurX.prog, "inPos" ); if ( !progBlurX.prog ) return; progPost = {} progPost.prog = ShaderProgram.Create( [ { source : "post-shader-vs", stage : gl.VERTEX_SHADER }, { source : "blurY-shader-fs", stage : gl.FRAGMENT_SHADER } ] ); progPost.inPos = gl.getAttribLocation( progPost.prog, "inPos" ); if ( !progPost.prog ) return; // create cube var cubePos = [ -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0 ]; var cubeCol = [ 1.0, 0.0, 0.0, 1.0, 0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ]; var cubeHlpInx = [ 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 1, 0, 4, 5 ]; var cubePosData = []; for ( var i = 0; i < cubeHlpInx.length; ++ i ) { cubePosData.push( cubePos[cubeHlpInx[i]*3], cubePos[cubeHlpInx[i]*3+1], cubePos[cubeHlpInx[i]*3+2] ); } var cubeNVData = []; for ( var i1 = 0; i1 < cubeHlpInx.length; i1 += 4 ) { var nv = [0, 0, 0]; for ( i2 = 0; i2 < 4; ++ i2 ) { var i = i1 + i2; nv[0] += cubePosData[i*3]; nv[1] += cubePosData[i*3+1]; nv[2] += cubePosData[i*3+2]; } for ( i2 = 0; i2 < 4; ++ i2 ) cubeNVData.push( nv[0], nv[1], nv[2] ); } var cubeColData = []; for ( var is = 0; is < 6; ++ is ) { for ( var ip = 0; ip < 4; ++ ip ) { cubeColData.push( cubeCol[is*3], cubeCol[is*3+1], cubeCol[is*3+2] ); } } var cubeInxData = []; for ( var i = 0; i < cubeHlpInx.length; i += 4 ) { cubeInxData.push( i, i+1, i+2, i, i+2, i+3 ); } bufCube = VertexBuffer.Create( [ { data : cubePosData, attrSize : 3, attrLoc : progDraw.inPos }, { data : cubeNVData, attrSize : 3, attrLoc : progDraw.inNV }, { data : cubeColData, attrSize : 3, attrLoc : progDraw.inCol } ], cubeInxData ); bufQuad.pos = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos ); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( [ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ] ), gl.STATIC_DRAW ); bufQuad.inx = gl.createBuffer(); gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx ); gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] ), gl.STATIC_DRAW ); window.onresize = resize; resize(); requestAnimationFrame(render); } function Fract( val ) { return val - Math.trunc( val ); } function CalcAng( deltaTime, intervall ) { return Fract( deltaTime / (1000*intervall) ) * 2.0 * Math.PI; } function CalcMove( deltaTime, intervall, range ) { var pos = self.Fract( deltaTime / (1000*intervall) ) * 2.0 var pos = pos < 1.0 ? pos : (2.0-pos) return range[0] + (range[1] - range[0]) * pos; } function EllipticalPosition( a, b, angRag ) { var a_b = a * a - b * b var ea = (a_b <= 0) ? 0 : Math.sqrt( a_b ); var eb = (a_b >= 0) ? 0 : Math.sqrt( -a_b ); return [ a * Math.sin( angRag ) - ea, b * Math.cos( angRag ) - eb, 0 ]; } glArrayType = typeof Float32Array !="undefined" ? Float32Array : ( typeof WebGLFloatArray != "undefined" ? WebGLFloatArray : Array ); function IdentityMat44() { var m = new glArrayType(16); m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return m; }; function RotateAxis(matA, angRad, axis) { var aMap = [ [1, 2], [2, 0], [0, 1] ]; var a0 = aMap[axis][0], a1 = aMap[axis][1]; var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad); var matB = new glArrayType(16); for ( var i = 0; i < 16; ++ i ) matB[i] = matA[i]; for ( var i = 0; i < 3; ++ i ) { matB[a0*4+i] = matA[a0*4+i] * cosAng + matA[a1*4+i] * sinAng; matB[a1*4+i] = matA[a0*4+i] * -sinAng + matA[a1*4+i] * cosAng; } return matB; } function Cross( a, b ) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], 0.0 ]; } function Dot( a, b ) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } function Normalize( v ) { var len = Math.sqrt( v[0] * v[0] + v[1] * v[1] + v[2] * v[2] ); return [ v[0] / len, v[1] / len, v[2] / len ]; } var Camera = {}; Camera.create = function() { this.pos = [0, 3, 0.0]; this.target = [0, 0, 0]; this.up = [0, 0, 1]; this.fov_y = 90; this.vp = [800, 600]; this.near = 0.5; this.far = 100.0; } Camera.Perspective = function() { var fn = this.far + this.near; var f_n = this.far - this.near; var r = this.vp[0] / this.vp[1]; var t = 1 / Math.tan( Math.PI * this.fov_y / 360 ); var m = IdentityMat44(); m[0] = t/r; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = t; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = -fn / f_n; m[11] = -1; m[12] = 0; m[13] = 0; m[14] = -2 * this.far * this.near / f_n; m[15] = 0; return m; } Camera.LookAt = function() { var mz = Normalize( [ this.pos[0]-this.target[0], this.pos[1]-this.target[1], this.pos[2]-this.target[2] ] ); var mx = Normalize( Cross( this.up, mz ) ); var my = Normalize( Cross( mz, mx ) ); var tx = Dot( mx, this.pos ); var ty = Dot( my, this.pos ); var tz = Dot( [-mz[0], -mz[1], -mz[2]], this.pos ); var m = IdentityMat44(); m[0] = mx[0]; m[1] = my[0]; m[2] = mz[0]; m[3] = 0; m[4] = mx[1]; m[5] = my[1]; m[6] = mz[1]; m[7] = 0; m[8] = mx[2]; m[9] = my[2]; m[10] = mz[2]; m[11] = 0; m[12] = tx; m[13] = ty; m[14] = tz; m[15] = 1; return m; } var ShaderProgram = {}; ShaderProgram.Create = function( shaderList ) { var shaderObjs = []; for ( var i_sh = 0; i_sh < shaderList.length; ++ i_sh ) { var shderObj = this.CompileShader( shaderList[i_sh].source, shaderList[i_sh].stage ); if ( shderObj == 0 ) return 0; shaderObjs.push( shderObj ); } var progObj = this.LinkProgram( shaderObjs ) if ( progObj != 0 ) { progObj.attribIndex = {}; var noOfAttributes = gl.getProgramParameter( progObj, gl.ACTIVE_ATTRIBUTES ); for ( var i_n = 0; i_n < noOfAttributes; ++ i_n ) { var name = gl.getActiveAttrib( progObj, i_n ).name; progObj.attribIndex[name] = gl.getAttribLocation( progObj, name ); } progObj.unifomLocation = {}; var noOfUniforms = gl.getProgramParameter( progObj, gl.ACTIVE_UNIFORMS ); for ( var i_n = 0; i_n < noOfUniforms; ++ i_n ) { var name = gl.getActiveUniform( progObj, i_n ).name; progObj.unifomLocation[name] = gl.getUniformLocation( progObj, name ); } } return progObj; } ShaderProgram.AttributeIndex = function( progObj, name ) { return progObj.attribIndex[name]; } ShaderProgram.UniformLocation = function( progObj, name ) { return progObj.unifomLocation[name]; } ShaderProgram.Use = function( progObj ) { gl.useProgram( progObj ); } ShaderProgram.SetUniformI1 = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1i( progObj.unifomLocation[name], val ); } ShaderProgram.SetUniformF1 = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1f( progObj.unifomLocation[name], val ); } ShaderProgram.SetUniformF2 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform2fv( progObj.unifomLocation[name], arr ); } ShaderProgram.SetUniformF3 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform3fv( progObj.unifomLocation[name], arr ); } ShaderProgram.SetUniformF4 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform4fv( progObj.unifomLocation[name], arr ); } ShaderProgram.SetUniformM33 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix3fv( progObj.unifomLocation[name], false, mat ); } ShaderProgram.SetUniformM44 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix4fv( progObj.unifomLocation[name], false, mat ); } ShaderProgram.CompileShader = function( source, shaderStage ) { var shaderScript = document.getElementById(source); if (shaderScript) source = shaderScript.text; var shaderObj = gl.createShader( shaderStage ); gl.shaderSource( shaderObj, source ); gl.compileShader( shaderObj ); var status = gl.getShaderParameter( shaderObj, gl.COMPILE_STATUS ); if ( !status ) alert(gl.getShaderInfoLog(shaderObj)); return status ? shaderObj : null; } ShaderProgram.LinkProgram = function( shaderObjs ) { var prog = gl.createProgram(); for ( var i_sh = 0; i_sh < shaderObjs.length; ++ i_sh ) gl.attachShader( prog, shaderObjs[i_sh] ); gl.linkProgram( prog ); status = gl.getProgramParameter( prog, gl.LINK_STATUS ); if ( !status ) alert("Could not initialise shaders"); gl.useProgram( null ); return status ? prog : null; } var VertexBuffer = {}; VertexBuffer.Create = function( attributes, indices ) { var buffer = {}; buffer.buf = []; buffer.attr = [] for ( var i = 0; i < attributes.length; ++ i ) { buffer.buf.push( gl.createBuffer() ); buffer.attr.push( { size : attributes[i].attrSize, loc : attributes[i].attrLoc } ); gl.bindBuffer( gl.ARRAY_BUFFER, buffer.buf[i] ); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( attributes[i].data ), gl.STATIC_DRAW ); } buffer.inx = gl.createBuffer(); gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, buffer.inx ); gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( indices ), gl.STATIC_DRAW ); buffer.inxLen = indices.length; gl.bindBuffer( gl.ARRAY_BUFFER, null ); gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null ); return buffer; } VertexBuffer.Draw = function( bufObj ) { for ( var i = 0; i < bufObj.buf.length; ++ i ) { gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.buf[i] ); gl.vertexAttribPointer( bufObj.attr[i].loc, bufObj.attr[i].size, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( bufObj.attr[i].loc ); } gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx ); gl.drawElements( gl.TRIANGLES, bufObj.inxLen, gl.UNSIGNED_SHORT, 0 ); for ( var i = 0; i < bufObj.buf.length; ++ i ) gl.disableVertexAttribArray( bufObj.attr[i].loc ); gl.bindBuffer( gl.ARRAY_BUFFER, null ); gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null ); } initScene(); })(); html,body { height: 100%; width: 100%; margin: 0; overflow: hidden; } #gui { position : absolute; top : 0; left : 0; } <script id="draw-shader-vs" type="x-shader/x-vertex"> precision highp float; attribute vec3 inPos; attribute vec3 inNV; attribute vec3 inCol; varying vec3 vertPos; varying vec3 vertNV; varying vec3 vertCol; uniform mat4 u_projectionMat44; uniform mat4 u_viewMat44; uniform mat4 u_modelMat44; void main() { mat4 mv = u_viewMat44 * u_modelMat44; vertCol = inCol; vertNV = normalize(mat3(mv) * inNV); vec4 viewPos = mv * vec4( inPos, 1.0 ); vertPos = viewPos.xyz; gl_Position = u_projectionMat44 * viewPos; } </script> <script id="draw-shader-fs" type="x-shader/x-fragment"> precision mediump float; varying vec3 vertPos; varying vec3 vertNV; varying vec3 vertCol; uniform float u_shininess; uniform float u_glow; void main() { vec3 color = vertCol; vec3 normalV = normalize( vertNV ); vec3 eyeV = normalize( -vertPos ); vec3 halfV = normalize( eyeV + normalV ); float NdotH = max( 0.0, dot( normalV, halfV ) ); float shineFac = ( u_shininess + 2.0 ) * pow( NdotH, u_shininess ) / ( 2.0 * 3.14159265 ); gl_FragColor = vec4( u_glow*0.1 + color.rgb * u_glow * shineFac * 0.5, 1.0 ); } </script> <script id="post-shader-vs" type="x-shader/x-vertex"> precision mediump float; attribute vec2 inPos; varying vec2 pos; void main() { pos = inPos; gl_Position = vec4( inPos, 0.0, 1.0 ); } </script> <script id="blurX-shader-fs" type="x-shader/x-fragment"> precision mediump float; varying vec2 pos; uniform sampler2D u_texture; uniform vec2 u_textureSize; uniform float u_sigma; float CalcGauss( float x, float sigma ) { float coeff = 1.0 / (2.0 * 3.14157 * sigma); float expon = -(x*x) / (2.0 * sigma); return (coeff*exp(expon)); } void main() { vec2 texC = pos.st * 0.5 + 0.5; vec4 texCol = texture2D( u_texture, texC ); vec4 gaussCol = vec4( texCol.rgb, 1.0 ); float stepX = 1.0 / u_textureSize.x; for ( int i = 1; i <= 20; ++ i ) { float weight = CalcGauss( float(i) / 32.0, u_sigma * 0.5 ); texCol = texture2D( u_texture, texC + vec2( float(i) * stepX, 0.0 ) ); gaussCol += vec4( texCol.rgb * weight, weight ); texCol = texture2D( u_texture, texC - vec2( float(i) * stepX, 0.0 ) ); gaussCol += vec4( texCol.rgb * weight, weight ); } gaussCol.rgb /= gaussCol.w; gl_FragColor = vec4( gaussCol.rgb, 1.0 ); } </script> <script id="blurY-shader-fs" type="x-shader/x-fragment"> precision mediump float; varying vec2 pos; uniform sampler2D u_texture; uniform vec2 u_textureSize; uniform float u_sigma; float CalcGauss( float x, float sigma ) { float coeff = 1.0 / (2.0 * 3.14157 * sigma); float expon = -(x*x) / (2.0 * sigma); return (coeff*exp(expon)); } void main() { vec2 texC = pos.st * 0.5 + 0.5; vec4 texCol = texture2D( u_texture, texC ); vec4 gaussCol = vec4( texCol.rgb, 1.0 ); float stepY = 1.0 / u_textureSize.y; for ( int i = 1; i <= 20; ++ i ) { float weight = CalcGauss( float(i) / 32.0, u_sigma * 0.5 ); texCol = texture2D( u_texture, texC + vec2( 0.0, float(i) * stepY ) ); gaussCol += vec4( texCol.rgb * weight, weight ); texCol = texture2D( u_texture, texC - vec2( 0.0, float(i) * stepY ) ); gaussCol += vec4( texCol.rgb * weight, weight ); } vec3 hdrCol = 2.0 * gaussCol.xyz / gaussCol.w; vec3 mappedCol = vec3( 1.0 ) - exp( -hdrCol.rgb * 3.0 ); gl_FragColor = vec4( clamp( mappedCol.rgb, 0.0, 1.0 ), 1.0 ); } </script> <div> <form id="gui" name="inputs"> <table> <tr> <td> <font color= #CCF>shininess</font> </td> <td> <input type="range" id="shine" min="0" max="50" value="10" onchange="changeEventHandler(event);"/></td> </tr> <tr> <td> <font color= #CCF>glow</font> </td> <td> <input type="range" id="glow" min="100" max="400" value="250" onchange="changeEventHandler(event);"/></td> </tr> <tr> <td> <font color= #CCF>blur</font> </td> <td> <input type="range" id="sigma" min="1" max="100" value="60" onchange="changeEventHandler(event);"/></td> </tr> </table> </form> </div> <canvas id="canvas" style="border: none;" width="100%" height="100%"></canvas> A: The website GLSL Sandbox has a collection of shader examples. This one has the glow and appears to be able to compile for ES. You should be able to modify these to pull uv's from your texture. Here is some code directly from this site: #ifdef GL_ES precision mediump float; #endif #extension GL_OES_standard_derivatives : enable uniform float time; uniform vec2 mouse; uniform vec2 resolution; void main(void){ vec2 p = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); vec3 color1 = vec3(0.0, 0.3, 0.5); vec3 color2 = vec3(0.5, 0.0, 0.3); float f = 0.0; float g = 0.0; float h = 0.0; float PI = 3.14159265; for(float i = 0.0; i < 40.0; i++){ if (floor(mouse.x * 41.0) < i) break; float s = sin(time + i * PI / 20.0) * 0.8; float c = cos(time + i * PI / 20.0) * 0.8; float d = abs(p.x + c); float e = abs(p.y + s); f += 0.001 / d; g += 0.001 / e; h += 0.00003 / (d * e); } gl_FragColor = vec4(f * color1 + g * color2 + vec3(h), 1.0); }
{ "pile_set_name": "StackExchange" }
Q: Table with blank spaces after nth cell I am trying to create a table that has 1 row and 8 columns. However, I want a blank spaces after the 3rd and 6th table cell. The result should be: cell cell cell blank space cell cell cell blank space cell cell I have tried placing margins but they don't work. I have tried implementing this code, but it doesn't work. .brzl td:nth-child(3){ margin-right: 20px; } Edit: I am trying to implement this within an AngularJS project. In the index.html i have the following code: <div ng-switch-when="brzl"> <table class="brzl"> <tbody> <tr> <td ng-repeat="cell in mini.vrednost track by $index"> {{ cell }} </td> </tr> </tbody> </table> <label class="small-label"> {{ mini.label }} </label> </div> The mini.vrednost basically loops through some JSON data (e.g. "123456789"). Each digit has to be placed within separate cell in the table. Now, once the '1','2', and '3' have been placed in the cells, I need to put an empty field after them and then continue with '4', '5' etc. The empty field cannot be read from the JSON data, since the whole string is already read from somewhere (I suppose the database). I know I should have mentioned this earlier. That was my bad. A: Margin doesn't work on table cells. However, padding does. Of course, if you have added borders to your table, this means you get one cell with a lot of white space. Fiddle What you could do (through hard coding or by injecting with Javascript or jQuery) is add a blank cell where you want the white space, remove any styling of that cell through CSS and add a width. Working fiddle HTML <table> <tbody> <tr> <td>cell</td> <td>cell2</td> <td>cell3</td> <td></td> <!-- blank cell, no border --> <td>cell4</td> <td>cell5</td> <td>cell6</td> <td></td> <!-- blank cell, no border --> <td>cell7</td> </tr> </tbody> </table> CSS td { border: 1px solid #ccc; } td:nth-child(4n+4){ border: none; width: 30px; /*desired blank space*/ } As you can see, you'll have to target every 4th cell, starting with the 4th. If you have any questions, just ask and I'll see if I can adapt the answer accordingly. UPDATE AFTER OP'S EDIT However, since your table is filled with data by some script, you might want to run the following jQuery AFTER the loop is done filling up the table. I have no idea how it will react on huge tables with lots of content, but it works in the updated Fiddle below. $('tr > td:nth-child(3n+3)').after('<td></td>'); This piece of jQuery takes every 3rd child, starting with the 3rd, and adds an empty <td> to it, which is then styled by the CSS. Of course you could ad a <td> with a specific class which you then target with CSS, but as it is now, it seems to work fine. Fiddle Remember to add jQuery!
{ "pile_set_name": "StackExchange" }
Q: GL_REPEAT and GL_CLAMP giving same result I have a problem with GL_REPEAT and GL_CLAMP when generating a texture in OpenGL. In my following code I get same result(its always repeated) with GL_REPEAT and GL_CLAMP ... I dont see any difference in my code with the the ones in many of the tutorials. Please help me finding this mistake. I tried increasing the image size from 4 till 128 .. but still not difference between GL_CLAMP and GL_REPEAT #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <cmath> #include <stdlib.h> #include <stdio.h> /* Create checkerboard texture */ #define checkImageWidth 64 #define checkImageHeight 64 static float checkImage[checkImageHeight][checkImageWidth][4]; static GLuint texName; void makeCheckImage(void) { int i, j; float c; for (i = 0; i < checkImageHeight; i++) { for (j = 0; j < checkImageWidth; j++) { // c = ((((i&0x8)==0)^((j&0x8))==0))*255; c = 10*sin(i*j); // checkImage[i][j][0] = (GLubyte) c*0; checkImage[i][j][0] = c*0.1; checkImage[i][j][1] = c*0.25; checkImage[i][j][2] = c*0.0; checkImage[i][j][3] = 250; } } } void init(void) { glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel(GL_FLAT); glEnable(GL_DEPTH_TEST); makeCheckImage(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_FLOAT, checkImage); } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gluLookAt(1, -1, 1, 0, 1, 0, 0, 0, 1); glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glBindTexture(GL_TEXTURE_2D, texName); glMatrixMode(GL_MODELVIEW); //glLoadIdentity(); // glLoadIdentity(); glPushMatrix(); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0); glTexCoord2f(0.0, 1.0); glVertex3f(-2.0, 1.0, 0.0); glTexCoord2f(1.0, 1.0); glVertex3f(0.0, 1.0, 0.0); glTexCoord2f(1.0, 0.0); glVertex3f(0.0, -1.0, 0.0); glTexCoord2f(0.0, 0.0); glVertex3f(1.0, -1.0, 0.0); glTexCoord2f(0.0, 1.0); glVertex3f(1.0, 1.0, 0.0); glTexCoord2f(1.0, 1.0); glVertex3f(2.41421, 1.0, -1.41421); glTexCoord2f(1.0, 0.0); glVertex3f(2.41421, -2.0, -1.41421); glPopMatrix(); glPushMatrix(); /* glTranslated(-6, -2, 1); glScaled(0.5,0.5,0.5) ; //GLint mysphereID; GLUquadricObj *sphere=NULL; sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_LINE); gluQuadricTexture(sphere, GL_TRUE); gluQuadricNormals(sphere, GLU_SMOOTH); gluSphere(sphere, 01.0, 100, 100); */ glPopMatrix(); glPushMatrix(); glColor3f(0.7f, 0.0f, 0.4f); glTranslated(-1, -3, -1); glScaled(0.5,0.5,0.5) ; GLUquadricObj *quadObj = gluNewQuadric(); gluQuadricDrawStyle(quadObj, GLU_LINE); gluQuadricNormals(quadObj, GLU_SMOOTH); gluQuadricTexture(quadObj, GL_TRUE); gluCylinder(quadObj, 0.8, 0.8, 1.4, 100, 100); glPopMatrix(); glDisable(GL_TEXTURE_2D); //gluDeleteQuadric(sphere); gluDeleteQuadric(quadObj); glEnd(); glFlush(); } void reshape(int w, int h) { glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(100.0, (GLfloat) w/(GLfloat) h, 1.0, 30.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -3.6); } void keyboard (unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; default: break; } } int main(int argc, char** argv) { glutInit(&argc, argv); //glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(550, 550); glutInitWindowPosition(100, 100); glutCreateWindow(argv[0]); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMainLoop(); return 0; } A: You will not see a difference unless your texture coordinates are outside of the range 0 to 1. Otherwise there is nothing to clamp or repeat.
{ "pile_set_name": "StackExchange" }
Q: I want my loop to run until the result of the equation equals the previous result I am writing a code in FORTRAN to calculate the position of the planets. I need to solve Kepler's equation using newtons numerical method and I am having trouble with my loop. The code is shown below. I can compile it with no error messages, but it wont run. It just gets stuck in a forever loop. I want the loop to run until E(i) and the following result are equal. Any help would be greatly appreciated. do while (E(i)/=E(i+1)) E(1)=M E(i+1)=E(i)-((M-E(i)+(p*sin(E(i))))/((p*cos(E(i)))-1)) end do Also, how do i define the variable 'E' at the beginning of my program. I currently have this but the '11' is only because I originally had my loop run 10 times. If I don't specify the number of times I want the loop to run, how do i define the variable? double precision :: E(11) A: I did not check if your convergence implementation is correct, but you definitely do not want to check for exact equality. You must allow for some inexactness, because floating point calculations are inexact (abs(E(i)-E(i+1))<eps) where eps is some small number. As @agentp suggests you don't change i, so you always work with 2 values E(i) and E(i+1) (i being whatever you set it before the loop). You do not use any other elements of your array. For the array which can have any length, depending on your need, you could theoretically use double precision, allocatable :: E(:) but you probably do not want to use an array at all and you just want two scalar values double precision :: E1, E2 E1 = M do E2 = E1 - ((M-E1+(p*sin(E1))) / ((p*cos(E1))-1)) if (abs(E1-E2) < eps) exit E1 = E2 end do Note that the kind notation (real(....)) is preferable in new code instead of the old double precision.
{ "pile_set_name": "StackExchange" }
Q: How to write $\aleph$ by hand So far, I've only seen the symbol $\aleph$ in its printed form and am wondering how this symbol could be written by hand on paper or on a board (in mathematical contexts, of course). Whenever I try to write it, I seem to have two options: Paper: Unwrap my nib and attempt a nice piece of calligraphy. (However, this is a bit too time-consuming.) Board: Rotate the chalk to produce a broader line. (However, this only works with chalk of appropriate length.) Approximate the printed form $\aleph$ as good as I can holding the pen/chalk ordinarily. (However, this leads to a letter that can hardly be distinguished from an $N$ or $\chi$ or $X$.) So, how can I produce a neat, distinguishable $\aleph$ by hand (in a reasonable amount of time)? And in what order should the strokes and wiggles be written? A: This is the letter א as commonly taught to schoolchildren in Israel: If I remember correctly, we used to draw the main diagonal first, starting at the top left, then the upper arm starting from the top and angling towards the main line, then the lower leg starting from the main diagonal and curving downwards. There's no need to use a particularly thick stroke; the letters are written with the same stroke style as letters in Latin and other alphabets. A: I have always written it as three disconnected strokes: and as far as I know, nobody has ever had trouble recognizing it.
{ "pile_set_name": "StackExchange" }
Q: How to do conditional update of Azure Table Storage Entity with ETag How do I use the ETag of Azure Table Storage Entity to update the entity if the ETag has not changed? Example: var query = (from ent in cloudservicetable.CreateQuery<CloudServiceTableEntity>() where ent.PartitionKey == "test" && ent.Status == "creating" && ent.Counter> 0 select ent).AsTableQuery(); var candidates = query.OrderByDescending(s=>s.Counter).ToList(); bool found = false; while (!found && candidates.Any()) { //Find best candidate var candidate = candidates.First(); //If we can decrement the count with out the entity have been changed //it is a acceptable candidate. candidate.Counter--; var opr = TableOperation.Merge(candidate); // cloudservicetable.ExecuteAsync(opr) // How do I only do the merge if the etag have not changed? //TODO If changed remove/update the candidate list } // if found we have a candidate A: For conditional merges, you don't have to do anything. Your code will throw an error (PreCondition failed - Http Status Code 412) if during the merge operation ETag doesn't match. So your code above will work perfectly fine. For unconditional merges, you would need to manually set the ETag property of the entity to *.
{ "pile_set_name": "StackExchange" }
Q: How to match strings that start and end with the same character, but have an odd number of letters? I'm trying to formulate a regex that identifies strings that begin and end with 'B" but also have an odd number of letters overall. So far I have the following: Strings that start and end with B: ^B.*B$ I am not sure how to get it so that it only accepts an odd number of letter. For even numbers it's easy: ^B(..)*B$ But odd is throwing me a little A: It should be almost the same: ^B.(..)*B$
{ "pile_set_name": "StackExchange" }
Q: symfony2 route pattern This pattern: pattern: /Messages/.{_format} Not working when i go to url /Messages I want to redirect me to the /Messages/ like without the {_format} at the end of the pattern. HOW? A: It's not working because by /Messages you are calling not defined pattern. I suppose that problem is with /.. Instead that you should try something like that: messages_show: pattern: /Messages.{_format} defaults: { _controller: AcmeDemoBundle:Messages:show, _format: html } requirements: _format: html|rss Btw. current Symfony2 routing documentation: http://symfony.com/doc/current/book/routing.html
{ "pile_set_name": "StackExchange" }
Q: Use function to create a new column in a DataFrame based on DataFrame variables with pandas Have a function to assign a hex color variable based on a scale from 0-1. In one column I have pageviews that are being assigned a scale: df1['pvScale'] = df1['GA Page Views']/max(df1['GA Page Views']) But when I go to create another column and have that be based off a function for assigning hex values: df1['hex'] = colorscale("#00ff4c", df1['pvScale']) #(orginal hex, 0-1) Getting this return: "ValueError: The truth value of a Series is ambiguous." What's the correct syntax to perform this operation? A: Try using df.apply(): df1['hex'] = df['pvScale'].apply(lambda x: colorscale("#00ff4c", x)) It will apply the colorscale function on the values in one-by-one.
{ "pile_set_name": "StackExchange" }
Q: rm except last 5 files bash I found 5 last core files. I need to delete all core files except these 5 files. ls -t /u01/1/bin/core.siebprocmw.* |head -n 5 command to find 5 last files by time. ls -t /u01/1/bin/core.siebprocmw.* |head -n 5 |xargs rm -r command remove found last 5 files. I need to delete all files except these last 5 files. Any ideas? A: You could use sed to exclude the first five newest files, then delete the rest: ls -t /u01/1/bin/core.siebprocmw.* | sed '1,5d' | xargs rm -r
{ "pile_set_name": "StackExchange" }
Q: Dynamically setting the PackageName in an Execute Package Task How can you dynamically set the PackageName in an Execute Package Task? I've select the list of packages into a user variable, and got a ForEach loop with a script task showing the value I'm after in there in ... Dts.Variables["User::TgtPackage"].Value.ToString() But I've tried using ... User::TgtPackage Dts.Variables["User::TgtPackage"].Value.ToString() in the PackageName, but neither work A: Since you're on 2008, the way in which you're referencing a package in the Execute Package Task is either on the File System or in SQL Server. The Execute Package task is then using your Connection Manager In the case of File based connection managers, you need to set an Expression on the file Connection Manager's ConnectionString property. Right click on the Connection Manager, in the Properties pane find your Expressions section, click the ellipses and map ConnectionString to @[User::TgtPackage] (assuming the value of TgtPackage is a fully qualified path) In the case of SQL Server based packages, you will need to set an Expression on the Execute Package Task's PackagePath property. Double click on your Execute Package Task, on the Expressions tab, map the PackagePath property to @[User::TgtPackage] value (assuming the value of TgtPackage is just the package name, e.g. so_26718490Target) Biml Biml is the business intelligence markup language. If you have the free addon Bids Helper, you can add a Biml file and use the following code to generate a package that uses a For Each Item Enumerator. Inside that, an Execute Package Task which uses a file based source. For an example of Biml to configure the package name, see https://stackoverflow.com/a/21170368/181965 <Biml xmlns="http://schemas.varigence.com/biml.xsd"> <Connections> <FileConnection Name="FCChild" FilePath="c:\Sandbox\SO\SO\so_26718490Target.dtsx"></FileConnection> </Connections> <Packages> <Package ConstraintMode="Linear" Name="so_26718490Target"></Package> <Package ConstraintMode="Linear" Name="so_26718490"> <Variables> <Variable DataType="String" Name="TgtPackage">c:\Sandbox\SO\SO\so_26718490Target.dtsx</Variable> </Variables> <Tasks> <ForEachItemLoop ConstraintMode="Linear" Name="FILC Run packages"> <Rows> <Row> <Columns> <Column DataType="String" Value="c:\Sandbox\SO\SO\so_26718490Target.dtsx"></Column> </Columns> </Row> </Rows> <VariableMappings> <VariableMapping VariableName="User.TgtPackage" Name="0"></VariableMapping> </VariableMappings> <Tasks> <!-- Execute package task --> <ExecutePackage Name="EPT File Child"> <File ConnectionName="FCChild"></File> </ExecutePackage> </Tasks> </ForEachItemLoop> </Tasks> <Connections> <Connection ConnectionName="FCChild"> <Expressions> <Expression ExternalProperty="ConnectionString">@[User::TgtPackage]</Expression> </Expressions> </Connection> </Connections> </Package> </Packages> </Biml>
{ "pile_set_name": "StackExchange" }
Q: Implementing Facebook Connect for iPhone using xcode 4 I'm having trouble getting Facebook Connect working. I (attempt) to follow the instructions located at http://www.mobisoftinfotech.com/blog/iphone/iphone-fbconnect-facebook-connect-tutorial/ but it seems to be for earlier versions of xcode. Here are the steps I'm taking. Create a new View Based App Download the SDK from their link Copy the FBxxxx.h files from the FBConnect folder inside of the src folder into my projects directory Create a new group named FBConnect under my project in xcode right click add new files and select the files that are already within my project go through the rest of the steps on the page creating an application and writing the example code It seems that I've set everything up correct then I get the follow error when I build my project. Undefined symbols for architecture i386: "_OBJC_CLASS_$_FBSession", referenced from: objc-class-ref in JetPackViewController.o "_OBJC_CLASS_$_FBLoginButton", referenced from: objc-class-ref in JetPackViewController.o "_OBJC_CLASS_$_FBRequest", referenced from: objc-class-ref in JetPackViewController.o ld: symbol(s) not found for architecture i386 collect2: ld returned 1 exit status I'm assuming this has something to do with how I am importing the files into my project. So how do I fix this or what am I doing wrong? A: The Facebook Connect SDK has been deprecated. Pull down the Facebook iOS SDK from Github. It comes with a working example and all you need to do is replace your appId in two places. If you run into issues upgrading it to Xcode 4, see this guide on upgrading.
{ "pile_set_name": "StackExchange" }
Q: MS Outlook 2013 deletes custom categories added into MasterCategoryList via Exchange Web Services API Hello Exchange developers, I successfully added several custom categories into MasterCategoryList via Exchange Web Services API. I used a sample: var list = MasterCategoryList.Bind(service); list.Categories.Add( new Category { Name = "Vacation", Color = CategoryColor.DarkMaroon, KeyboardShortcut = CategoryKeyboardShortcut.CtrlF10, Id = Guid.NewGuid() }); But after some time I noticed my custom categories went away from MasterCategoryList for some reason. I found out despite I assigned "Guid.NewGuid()" to the "Id" property after some time MS Exchange nullify it ("0000-0000-..."). Does anybody solve such a problem? Thanks for your attention. A: Thanks for your answer. It seems I resolved this problem. It appeared contents of the "Id" property (Category class) should be wrapped inside curly brackets. In my case I used "Guid" type for "Id" property. Serializer applied "ToString" method and "Id" property looked like "e6de9b1b-a81c-46f6-81b3-c23edfab4478" but valid value is "{e6de9b1b-a81c-46f6-81b3-c23edfab4478}". So I changed type of "Id" property to "string". And valid version looks like: var list = MasterCategoryList.Bind(service); list.Categories.Add( new Category { Name = "Vacation", Color = CategoryColor.DarkMaroon, KeyboardShortcut = CategoryKeyboardShortcut.CtrlF10, Id = "{" + Guid.NewGuid() + "}"; }); Please be aware.
{ "pile_set_name": "StackExchange" }
Q: What are the parameters in this C qsort function call? qsort(bt->rw[t], bt->num[t], sizeof(TRELLIS_ATOM *), (int (*)(const void *,const void *))compare_wid); bt->rw[t] is a pointer to struct pointer, bt->[num] is an int, I don't understand what that fourth parameter is, except that compare_wid is a function defined somewhere as follows: static int compare_wid( TRELLIS_ATOM* a, TRELLIS_ATOM* b ) { ... return x; } A: I will get to the meaning of the line in a bit, but before I do that, let's get some of the basics of why qsort() needs its final parameter of the type it needs. qsort() is a function that can sort any type of data. You provide it with: a base pointer, which points to the start of a contiguous block of data, the number of elements in the block, the size of one data member, and a function that compares two data values. Since a sorting algorithm in general doesn't depend upon the type of the data being sorted, qsort() can be written without the knowledge of what data types it is sorting. But to be able to do that, qsort() takes void * parameters, which means "generic pointer" in C. Let's say you have an array of unsorted int values: #define N 1024 int data[N] = { 10, 2, 3, -1, ... } /* 1024 values */ Then you can sort them by calling qsort(): qsort(data, N, sizeof data[0], compare_int); data is of type int * when passed to qsort(), and the first parameter of qsort() is of type void *. Since any object pointer can be converted to void * in C, this is OK. The next two arguments are okay too. The final argument, compare_int, should be a function that takes two const void * parameters and returns an int. The function will be called by qsort() with pairs of pointers from &data[0] to &data[N-1] as many times as it needs. To declare a function f() that "takes two const void * parameters and returns int": int f(const void *, const void *); If one wants to declare a function pointer that we can set to f, the pointer is declared as: int (*pf)(const void *, const void *); pf = f; The parentheses are required, because otherwise pf would be a function returning an int *. Now, pf is a pointer to a function returning int. Getting back to our int sorting algorithm, and from the above, we could define compare_int() as: int compare_int(const void *a, const void *b) { const int *the_a = a; const int *the_b = b; if (*the_a > *the_b) return 1; else if (*the_a < *the_b) return -1; else return 0; } While writing compare_int(), we know that the pointers passed are int * disguised as void *, so we convert them back to int *, which is OK, and then we compare the numbers. Now, we turn our attention to the code in question: static int compare_wid( TRELLIS_ATOM* a, TRELLIS_ATOM* b ) means that compare_wid is a function that takes two TRELLIS_ATOM * parameters, and returns an int. As we just saw, the last argument to qsort() should be a function that is of type: int (*)(const void *, const void *) I.e., a function taking two const void * parameters and returning int. Since the types don't match, the programmer cast compare_wid() to the type required by qsort(). However, this has problems. A function of type: int (*)(TRELLIS_ATOM *, TRELLIS_ATOM *) is not equivalent to a function of type: int (*)(const void *, const void *) so it's not guaranteed if the cast will work. It is much more easier, correct, and standard to declare compare_wid() as: static int compare_wid(const void *a, const void *b); And the definition of compare_wid() should look like: static int compare_wid(const void *a, const void *b) { const TRELLIS_ATOM *the_a = a; const TRELLIS_ATOM *the_b = b; ... /* Now do what you have to do to compare the_a and the_b */ return x; } If you do that, you won't need the cast in the call to qsort(), and your program will not only be easier to read, but also correct. If you can't change compare_wid(), then write another function: static int compare_stub(const void *a, const void *b) { return compare_wid(a, b); } and call qsort() with compare_stub() (without the cast) instead of compare_wid(). Edit: Based upon many of the wrong answers, here is a test program: $ cat qs.c #include <stdio.h> #include <stdlib.h> struct one_int { int num; }; #ifdef WRONG static int compare(const struct one_int *a, const struct one_int *b) { #else static int compare(const void *a_, const void *b_) { const struct one_int *a = a_; const struct one_int *b = b_; #endif if (a->num > b->num) return 1; else if (a->num < b->num) return -1; else return 0; } int main(void) { struct one_int data[] = { { 42 }, { 1 }, { 100 } }; size_t n = sizeof data / sizeof data[0]; qsort(data, n, sizeof data[0], compare); return 0; } Compiling with compare() defined as taking two const struct one_int * values: $ gcc -DWRONG -ansi -pedantic -W -Wall qs.c qs.c: In function `main': qs.c:32: warning: passing argument 4 of `qsort' from incompatible pointer type Compiling with the correct definition: $ gcc -ansi -pedantic -W -Wall qs.c $ Edit 2: There seems to be some confusion about the legality of using compare_wid as-it-is for the final argument to qsort(). The comp.lang.c FAQ, question 13.9 has a good explanation (emphasis mine): To understand why the curious pointer conversions in a qsort comparison function are necessary (and why a cast of the function pointer when calling qsort can't help), it's useful to think about how qsort works. qsort doesn't know anything about the type or representation of the data being sorted: it just shuffles around little chunks of memory. (All it knows about the chunks is their size, which you specify in qsort's third argument.) To determine whether two chunks need swapping, qsort calls your comparison function. (To swap them, it uses the equivalent of memcpy.) Since qsort deals in a generic way with chunks of memory of unknown type, it uses generic pointers (void *) to refer to them. When qsort calls your comparison function, it passes as arguments two generic pointers to the chunks to be compared. Since it passes generic pointers, your comparison function must accept generic pointers, and convert the pointers back to their appropriate type before manipulating them (i.e. before performing the comparison). A void pointer is not the same type as a structure pointer, and on some machines it may have a different size or representation (which is why these casts are required for correctness). As mentioned in the FAQ, also see this. A: (int (*)(const void *,const void *)) means "treat what follows as a pointer to a function that takes two parameters of type const void* and returns an int". compare_wid is indeed a function that can be treated this way. qsort will call this function to perform comparisons between items when sorting: if the integer it returns is zero, the items are assumed to be equal, otherwise the sign of the integer is used to order them. A: qsort void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) ); comparator: Function that compares two elements. The function shall follow this prototype: int comparator ( const void * elem1, const void * elem2 ); The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared. The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
{ "pile_set_name": "StackExchange" }
Q: When should tf.losses.add_loss() be used in TensorFlow? I cannot find an answer to this question in the TensorFlow documentation. I once read that one should add losses from tf.nn functions but it isn't necessary for functions from tf.losses. Therefore: When should I use tf.losses.add_loss()? Example: loss = tf.reduce_mean(tf.nn.sparse_softmax_corss_entropy_with_logits (labels=ground_truth, logits=predictions)) tf.losses.add_loss(loss) <-- when is this required? Thank yoou. A: One would use this method to register the loss defined by user. Namely, if you have created a tensor that defines your loss, for example as my_loss = tf.mean(output) you can use this method to add it to loss collection. You might want to do that if you are not tracking all your losses manually. For example if you are using a method like tf.losses.get_total_loss(). Inside tf.losses.add_loss is very much straightforward: def add_loss(loss, loss_collection=ops.GraphKeys.LOSSES): if loss_collection and not context.executing_eagerly(): ops.add_to_collection(loss_collection, loss)
{ "pile_set_name": "StackExchange" }
Q: Intellij plugin to filter logs? Some time ago when android development was done on eclipse i remember that ADB viewer (or whatever its called) allowed you to filter and see only say DEBUG logs then you could just change it from drop down menu and you'd have all logs of specified level (also all logs were colored). Now on Intellij i found a good plugin called grep console which allows to color your log output using regex, however i couldn't find anything that could actually filter the output in the console window to the level you want to... Is there any solution for this? A: The plugin offers "filter out" option which hides matching lines. You can setup expressions for various log levels and control which ones to filter out. Or you can try to specify expression which matches any input but with needed level and filter it out. As a last resort, the plugin is open source, so you can add any needed feature. But I believe it's not necessary. BTW, nice plugin, thank you.
{ "pile_set_name": "StackExchange" }
Q: JQuery Colorbox and Forms I have a form which I want to submit and show in Colorbox. The form is Mals Ecommerce View Cart. See: https://www.mals-e.com/tpv.php?tp=4 I want it to Show the Cart contents in a colorbox iframe. Is this possible to do using the FORM method rather than the Link method? A: here the best answer.. add this to your submitbutton : id="SearchButton" then use this: $(document).ready(function() { $("input#SearchButton").colorbox({href: function(){ var url = $(this).parents('form').attr('action'); var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser); return url+'?'+ser; }, innerWidth:920, innerHeight:"86%", iframe:true}); }); test at: http://wwww.xaluan.com or http://wwww.xaluan.com/raovat/ A: I recently faced this problem, spent some time searching the solution and found this: $("#submit_button").click(function () { // ATTACH CLICK EVENT TO MYBUTTON $.post("/postback.php", // PERFORM AJAX POST $("#info_form").serialize(), // WITH SERIALIZED DATA OF MYFORM function(data){ // DATA NEXT SENT TO COLORBOX $.colorbox({ html: data, open: true, iframe: false // NO FRAME, JUST DIV CONTAINER? }); }, "html"); }); I.e. Colorbox uses submitting the form via standard jQuery methods. Hope this helps someone.
{ "pile_set_name": "StackExchange" }
Q: When is a mechitza required at a meal? According to the opinions which require Mechitzos by weddings. Why isn't there a requirement to have Mechitzos by any other Seudas Mitzvah? For example, why isn't there a requirement that one have a Mechitza by a Shabbos Table, a Seder, etc. A: There is a difference between a a private Shabbos Seuda and a wedding. By a private Seuda there usually is only family, however at a wedding you also invite others. Incidentally the Chasidim when they have a Mitzva Tantz and only the family remains, they take away the Mechitza. And when they make a Shabbos Sheva Brachos where there are others present back comes the Mechitza.
{ "pile_set_name": "StackExchange" }
Q: How to Listen For an Application Launch Event in Mac OS X? I wrote an AppleScript to mount a SparseBundle image and I want it to be executed exactly when Time Machine launches. Right now, I periodically check if Time Machine is running with AppleScript using on idle statement: on idle .... return <interval> end idle which isn't a robust way. In my opinion adding an event trigger for Application Launch event would be a better approach. Could you please help? An Objective-C or Python sample code (I'd prefer Python) is more than welcome. A: What you are looking for is, NSDistributedNotificationCenter or NSWorkspace , these cocoa classes post notifications of application events, For workspace, things like application launches, mounting of drives etc. To do this in python, you need PyObjC, which is basically python bindings for apple's cocoa classes. The documentation is sparse on their website, and there's a reason, as the documentation would be basically be the same as the Apple docs, so they only include the differences between the pyobjc api, and the cocoa API. If you understand how the objective c api is converted to python you are good to go. Check here: http://pyobjc.sourceforge.net/documentation/pyobjc-core/intro.html I have included an example below which listens for Distributed notifications using python. The code below basically adds an observer and listens for itunes notifications. You could follow a similar structure, but instead add an observer for NSWorkspace. To figure out what you should be listening to, there is an application that will display all notifications going through your system. It's called notification watcher . Use this to figure out what you should be listening to. You could also convert the objective c code to python. What the code below is doing Defines a new class which inherits from NSObject, as defined by PyObjC Defines a method, which gets passed the actual notification and prints it out Creates an instance of Foundation.NSDistributedNotificationCenter.defaultCenter Creates an instance of GetSongs Registers an observer, passing it the class, the method that gets called when a notification is received and which application & event to monitor i.e "com.apple.iTunes.playerInfo" Runs the event loop, One thing that will trip you up, accessing attributes (objective c attributes) do not work the same as accessing python attributes. i.e in python you do class_name.att for objective c in python you have to call it like a function i.e from my example below: song.userInfo() import Foundation from AppKit import * from PyObjCTools import AppHelper class GetSongs(NSObject): def getMySongs_(self, song): print "song:", song song_details = {} ui = song.userInfo() print 'ui:', ui for x in ui: song_details[x] = ui.objectForKey_(x) print song_details nc = Foundation.NSDistributedNotificationCenter.defaultCenter() GetSongs = GetSongs.new() nc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None) NSLog("Listening for new tunes....") AppHelper.runConsoleEventLoop() Here's an example of the actual output... (YES BRITNEY ROCKS!, NOT! ;) song NSConcreteNotification 0x104c0a3b0 {name = com.apple.iTunes.playerInfo; object = com.apple.iTunes.player; userInfo = { Album = Circus; "Album Rating" = 0; "Album Rating Computed" = 1; Artist = "Britney Spears"; "Artwork Count" = 1; Genre = Pop; "Library PersistentID" = 8361352612761174229; Location = "file://localhost/Users/izze/Music/iTunes/iTunes%20Music/Britney%20Spears/Circus/02%20Circus.mp3"; Name = Circus; PersistentID = 4028778662306031905; "Play Count" = 0; "Play Date" = "2010-06-26 08:20:57 +0200"; "Player State" = Playing; "Playlist PersistentID" = 7784218291109903761; "Rating Computed" = 1; "Skip Count" = 1; "Skip Date" = "2010-06-26 12:20:57 +0200"; "Store URL" = "itms://itunes.com/link?n=Circus&an=Britney%20Spears&pn=Circus"; "Total Time" = 192444; "Track Count" = 16; "Track Number" = 2; }} ui { Album = Circus; "Album Rating" = 0; "Album Rating Computed" = 1; Artist = "Britney Spears"; "Artwork Count" = 1; Genre = Pop; "Library PersistentID" = 8361352612761174229; Location = "file://localhost/Users/izze/Music/iTunes/iTunes%20Music/Britney%20Spears/Circus/02%20Circus.mp3"; Name = Circus; PersistentID = 4028778662306031905; "Play Count" = 0; "Play Date" = "2010-06-26 08:20:57 +0200"; "Player State" = Playing; "Playlist PersistentID" = 7784218291109903761; "Rating Computed" = 1; "Skip Count" = 1; "Skip Date" = "2010-06-26 12:20:57 +0200"; "Store URL" = "itms://itunes.com/link?n=Circus&an=Britney%20Spears&pn=Circus"; "Total Time" = 192444; "Track Count" = 16; "Track Number" = 2; } {u'Album Rating Computed': 1, u'Album': u'Circus', u'Rating Computed': True, u'Name': u'Circus', u'Artist': u'Britney Spears', u'Track Number': 2, u'Skip Date': 2010-06-26 12:20:57 +0200, u'Library PersistentID': 8361352612761174229L, u'Player State': u'Playing', u'Total Time': 192444L, u'Genre': u'Pop', u'Playlist PersistentID': 7784218291109903761L, u'Album Rating': 0, u'Location': u'file://localhost/Users/izze/Music/iTunes/iTunes%20Music/Britney%20Spears/Circus/02%20Circus.mp3', u'Skip Count': 1, u'Track Count': 16L, u'Artwork Count': 1, u'Play Date': 2010-06-26 08:20:57 +0200, u'PersistentID': 4028778662306031905L, u'Play Count': 0, u'Store URL': u'itms://itunes.com/link?n=Circus&an=Britney%20Spears&pn=Circus'} A: This isn't too tough to do in Objc-C. You can access notifications for all applications through NSWorkspace and NSNotificationCenter. Create an object and register one of it's methods for notifications of type NSWorkspaceDidTerminateApplicationNotification. Something like: @interface NotificationObserver : NSObject { } - (void) applicationDidLaunch:(NSNotification*)notification; @end @implementation NotificationObserver : NSObject - (void) applicationDidLaunch:(NSNotification*)notification { // Check the notification to see if Time Machine is being launched. } @end void watch(void) { NSNotificationCenter* notificationCenter = [[NSWorkspace sharedWorkspace] sharednotificationCenter]; NotificationObserver* observer = [[NotificationObserver alloc] init]; [notificationCenter addObserver:observer selector:@selector(applicationDidTerminate:) name:@"NSWorkspaceDidTerminateApplicationNotification" object:nil]; }
{ "pile_set_name": "StackExchange" }
Q: Assignment inside two for loops I am trying to build a specific matrix but using simply R can take a lot of time considering the size of the entries that I have to use. I write a function in Rcpp with the Armadillo functionality because I need the linear algebra part to work with matrices. My code is the next: library('Rcpp') library('inline') library('RcppArmadillo') cppFunction("arma::mat GramMat(arma::mat A, double parametro, int n) { arma::mat resultado=A; double temp; for (int i=0; i<n; i++){ for (int j=i; j<n; j++){ resultado(j,i)= exp(-1*parametro*((A.col(i)-A.col(j)).t() * (A.col(i)-A.col(j)))); } } for (int i=0; i<n; i++){ for (int j=0; j<i; j++){ resultado(i,j)=resultado(j,i); } } return resultado;}",depends="RcppArmadillo") and I am getting the next error: temp= exp(-1*parametro*((A.col(i)-A.col(j)).t() * (A.col(i)-A.col(j)))); ^ make: *** [file548914af6578.o] Error 1 The problem is with the assignation, because I tried assigning just a 1 and the assignation is working well. And I tought that maybe the problem was with the right hand side but I print it with Rcout and is delivering well number. A: When I tried compiling your code, I saw a more informative error message: file2f78133e7bc2.cpp: In function ‘arma::mat GramMat(arma::mat, double, int)’: file2f78133e7bc2.cpp:14:99: error: cannot convert ‘arma::enable_if2, arma::subview_col, arma::eglue_minus>, arma::op_htrans>, arma::eGlue, arma::subview_col, arma::eglue_minus>, arma::glue_times>, arma::eop_scalar_times>, arma::eop_exp> >::result {aka const arma::eOp, arma::subview_col, arma::eglue_minus>, arma::op_htrans>, arma::eGlue, arma::subview_col, arma::eglue_minus>, arma::glue_times>, arma::eop_scalar_times>, arma::eop_exp>}’ to ‘double’ in assignment resultado(j,i)= exp(-1*parametro*((A.col(i)-A.col(j)).t() * (A.col(i)-A.col(j)))); ^ make: *** [file2f78133e7bc2.o] Error 1 This leads us directly to the problem; the operation (A.col(i)-A.col(j)).t() * (A.col(i)-A.col(j)) returns a type that cannot be directly converted to a double. However, we can just use arma::as_scalar() to fix this (see here in the Armadillo documentation); the following compiled fine for me: cppFunction("arma::mat GramMat(arma::mat A, double parametro, int n) { arma::mat resultado=A; double temp; for (int i=0; i<n; i++){ for (int j=i; j<n; j++){ resultado(j,i)= arma::as_scalar(exp(-1*parametro*((A.col(i)-A.col(j)).t() * (A.col(i)-A.col(j))))); } } for (int i=0; i<n; i++){ for (int j=0; j<i; j++){ resultado(i,j)=resultado(j,i); } } return resultado;}",depends="RcppArmadillo") There are quite a few other things that could be improved in this code, of course. For example, as Dirk Eddelbuettel points out, you actually never use temp in your code. You might also want to use arma::dot() to get the dot product of (A.col(i)-A.col(j)) with itself (see here in the Armadillo documentation -- as arma::dot() returns a double, it would also eliminate the need to use arma::as_scalar()), etc.
{ "pile_set_name": "StackExchange" }
Q: Poker equity calculation algorithm I writing some specific poker equity calculator. Basically, equity calculator tells how much one hand is more profitable than other. I have written such calculator and it works, works fast, but there is a one not optimal place where a lot of time is spent and it definitely can be optimized. I am asking you about the advice how to optimize it. Below is the simplified structure of poker equity calculator. For sample purpose, I have made it for the game when both Players hands contain one from 52 cards, 4 cards are on board(turn), one(river) board card left. Let say that player who's sum of the board and hand card is higher - wins. #include "stdafx.h" #include <vector> #include <iostream> #include <ctime> #include <string> using namespace std; static const int card_count = 52; // Checks that board contains the card. A lot of time spent here. Need to be optimized. bool Contains(const std::vector<int>& board, int card) { for (int boardCard : board) { if (boardCard == card) { return true; } } return false; } // Fake function that evaluates hand strength. This is just for example real evaluator is different. So no need to optimize this. size_t GetHandStrength(const std::vector<int>& board, int card, int b) { size_t stren = 0; for (int boardCard : board) { stren += boardCard; } return stren + card + b; } // Returns equity for the board float GetEquity(const std::vector<int>& board) { float equity = 0; for (int c1 = 0; c1 < card_count; c1++) // Player1 card { if (Contains(board, c1)) { continue; } for (int c2 = 0; c2 < card_count; c2++) // Player2 card { if (c1 == c2 || Contains(board, c2)) { continue; } size_t usedBoards = 0; // number of boards are possible for this players and board cards float currentEquity = 0; for (int b = 0; b < card_count; b++) // Iterating river board cards { if (Contains(board, b)) { continue; } if (b == c1 || b == c2) // Check that there are no conflict with players cards { continue; } size_t p1stren = GetHandStrength(board, c1, b); size_t p2stren = GetHandStrength(board, c2, b); if (p1stren > p2stren) { currentEquity += 1.0; } else if (p1stren < p2stren) { currentEquity -= 1.0; } usedBoards++; } currentEquity /= usedBoards; equity += currentEquity; } } return equity; } int main() { clock_t begin = clock(); std::vector<int> board = { 0, 1, 2, 21 }; // Some turn random board (4 cards) float equity = GetEquity(board);; cout << "equity: " << equity << endl; return 0; } When iterating over the hand and board cards I need to check that board doesn't already contains the card, so I need to iterate over the board cards again and again. This is done by the bool Contains(const std::vector<int>& board, int card) also checks like if (b == c1 || b == c2) What can you suggest to optimize this part? A: Since you're doing an O(N³) operation, with a linear search, a big performance boost will happen if we can eliminate that search. There are two similar ways to go about it; both replace the search with an indexed lookup. Change the type of board from a vector that holds the cards to a vector (or array) of card_count slots that holds a count of how many of that card is in the board (using a count for future expansion to multiple decks). In GetEquity, fill a vector or array of card_count elements with counts for the cards in board, then just check that container for a nonzero to see if the card is contained in the board. This has the additional advantage of being able to add c1 and c2, so the inner loop checks only need to check one condition (rather than 2 or 3) to see if a card is available. Here's an updated GetEquity using ideas from option 2: float GetEquity(const std::vector<int>& board) { std::vector<int> counts(card_count); for (auto b: board) ++counts[b]; float equity = 0; for (int c1 = 0; c1 < card_count; c1++) // Player1 card { if (counts[c1]) { continue; } ++counts[c1]; for (int c2 = 0; c2 < card_count; c2++) // Player2 card { if (counts[c2]) { continue; } ++counts[c2]; size_t usedBoards = 0; // number of boards are possible for this players and board cards float currentEquity = 0; for (int b = 0; b < card_count; b++) // Iterating river board cards { if (counts[b]) { continue; } size_t p1stren = GetHandStrength(board, c1, b); size_t p2stren = GetHandStrength(board, c2, b); if (p1stren > p2stren) { currentEquity += 1.0; } else if (p1stren < p2stren) { currentEquity -= 1.0; } usedBoards++; } currentEquity /= usedBoards; equity += currentEquity; --counts[c2]; } --counts[c1]; } return equity; }
{ "pile_set_name": "StackExchange" }
Q: How to create a new document in Alfresco via REST API? How to create a certain type of document in Alfresco with using the Rest API. I would like to receive the URL to which to send the request and the list of required parameters. Tried to use http://wiki.alfresco.com/wiki/Repository_RESTful_API_Reference#Create_folder_or_document_.28createDocument.2C_createFolder.29 but it did not work out, because it could not determine which parameters to send to this API A: Here are some links to get started with Alfresco + CMIS - These should help to solve your question in general: https://forums.alfresco.com/forum/developer-discussions/alfresco-api/cmis-resources-tutorials-and-examples-03212012-1456
{ "pile_set_name": "StackExchange" }
Q: Why should I use Docker when I control my dev, staging and prod environment? I know the whole fact that it's better to have exactly what the production environment is on a development workstation: it erases the "it works on my computer". Docker for me it's like Bruce Lee on steroids fighting Abdul Jabbar: if you need to use a VM, use Docker instead. If, on development, I use nuget to control my dependencies, on my build server, it restores the packages before deployment: then I have exactly what the app needs to run. Furthermore, it the same app I am deploying over and over again on the same boxes. Why would I need a restart policy when I must know what went wrong ? If the app dies, the other boxes will take the load and I need to investigate/fix and not get into the habits of "no big deal, the container will restart in a minute". In a cloud environment, I see the point : AWS, Azure are those who can benefit the most of those features. Like being able to move webapps from server to server fast when customers ask for more power. Furthermore, if those webapps are different then I need to isolate them from each other: great use case of Docker! But, on premise / colocation, if I have a powershell script to get me a bare metal server on foot with IIS ready: why would I introduce another layer of abstraction? A: First two answers I thought of (there are more, but I think these are the most important): Resource utilization - if you're bare metal, your unit of scale is likely an entire VM. As you run more than one instance of an application or service, you can only do so by running more VMs. The canonical example of this in my world is IIS websites, where I can only get one instance per machine. If I run three instances, I have three VMs that are grossly underutilized. Docker allows you to replicate apps within a single VM. You can use up more resources on a single VM before scaling them horizontally. App-specific dependencies - you manage the VM image and OS dependencies, but there might be cases where you want to tune that more specifically for your app. Versions of IIS, for example. Instead of needing to run one version of a dependency for all of your applications globally, you can build container images that are app-specific, which makes your runtime more predictable. Deployment independence - if you're depending on global dependencies, you're locking yourself into updating all apps at once instead of being able to independently deploy each. Your deployments are larger and riskier. Containers would allow you to update each at your own pace and deliver value more incrementally.
{ "pile_set_name": "StackExchange" }
Q: Export Map to GeoPDF I am using GeoServer/OpenLayers to build a map website. One of things I want to do is to export a map to GeoPDF. It's not an export from desktop software. More specifically, map tiles are added as images and GML features are added as vector data. The only thing I have found that could allow me to do that is TerraGo SDK. Has anybody tried to do the same thing? Could anybody shed some lights? Thanks, A: GeoServer can produce PDFs, but not geospatial ones. If someone wants to give a crack at an implementation here there are some hints: https://stackoverflow.com/questions/4184127/java-itext-geospatial-pdf-exporter A: Starting with version 2 GDAL can create Geospatial PDF's. It is also able to request images directly from WMS servers to retrieve the information from Geoserver.
{ "pile_set_name": "StackExchange" }
Q: Android bulk insert or ignore JSONArray I am receiving a JSONArray of data from an ajax call in my application. What would be the best way to do an insert/on conflict skip on a SQLite table in my app? I have the following code: try { JSONArray data = response.getJSONArray("data"); ContentValues contentValues = new ContentValues(); // I don't know what to do here. // Do I do a for loop and convert the entire JSONArray into ContentValues // with the column name and value for each item in the array? db.insertWithOnConflict("Data", null, data, SQLiteDatabase.CONFLICT_IGNORE); } catch (JSONException e) { e.printStackTrace(); } A: Yes, you have to write a loop for converting the data from your JSONArray to be inserted into your database. If you are using a library which can do that automatically, it does not actually reduce the time of the data processing right? However, you can minimize your insert operations into your database table by one single database transaction like the following. SQLiteDatabase db = ... db.beginTransaction(); try { // do ALL your inserts here db.setTransactionSuccessful() } finally { db.endTransaction(); } You might also consider using an AsyncTask to do all these operations in a background thread. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: References for existence of solutions to overdetermined system of partial differential inequalities I want to show the existence of solutions to an overdetermined system of second-order partial differential inequalities in a given region $\Omega\subset\mathbb{R}^2$, \begin{equation*} \begin{cases} P_1(u)\geq 0,&\\ P_2(u)\geq 0,&\\ P_3(u)\geq 0.& \end{cases} \end{equation*} Updated: $P_i$ are linear/quasilinear/nonlinear second-order differential operators, \begin{equation*} \begin{cases} P_1(u)=&\hspace{-0.3cm}xu_{xx}+yu_{xy}+x^2u_{yy}+4u_x.\\ P_2(u)=&\hspace{-0.3cm}u_{xx}u_{yy}-u_{xy}^2+(xu_x-yu_y)u_{xx}+(yu_x-x^2u_y)u_{xy}+x(xu_x-yu_y)u_{yy}.\\ P_3(u)=&\hspace{-0.3cm}(u_{xx}u_{yy}-u_{xy}^2)u_x+(xu_x^2-yu_xu_y-x^2u_y^2)u_{xx}+(yu_x^2-x^2u_xu_y-xyu_y^2)u_{xy}+(x^2u_x^2-xyu_xu_y-y^2u_y^2)u_{yy}. \end{cases} \end{equation*} To do this, I am trying to solve for $(u,f_1,f_2,f_3)$ of the following system of PDEs, \begin{equation*} \begin{cases} P_1(u)=f_1^2,&\\ P_2(u)=f_2^2,&\\ P_3(u)=f_3^2.& \end{cases} \end{equation*} Could anyone suggest any references to deal with either system? Any suggestion is appreciated. Updated: Is it true that if I find all compatible conditions for $f_1,f_2,f_3$ and they are satisfied, then this system has a solution? A: Existence theorems for real analytic pde systems were developed by Riquier and Janet in the first quarter of the twentieth century (see, for example, Riquier's 1910 book Les systèmes d'équations aux dérivées partielles). An up to date treatment of their work, its modernisation by Pommaret, and its subsequent extensions is given in Seiler's book Involution The formal theory of differential equations and its applications in computer algebra. A lot of progress in 100 years. Edit: an application of these ideas to overdetermined systems in particular can be found in Kunio Kakié "On Regularity of Solutions to Overdetermined Non Linear Partial Differential Equations", Commetarii Mathematici Universitatis Sancti Pauli Vol. 52, No. 2 2003, pp. 125-138. Note that as per the comments added below, this paper discusses local properties only. Edit(2): regarding your question about compatibility conditions for the $f$ functions, the answer is "highly likely, but not guaranteed". You need your system to be involutive. If it isn't, then the system has to prolonged (differentiated to produce a higher order system); the Cartan-Kuranishi theorem states that a finite number of prolongations will produce either an involutive system, or an inconsistency. This is explained in Seiler's book mentioned previously, which also includes worked examples.
{ "pile_set_name": "StackExchange" }
Q: Guitar Tablature: "bis" meaning I've looked, but Google keeps interpreting "bis" as German(?) Example: |----------------|-------|-----------------------|-------| |-------7-----7--|-------|--------------7-----7--|-------| |-------8-----8--|--bis--|--------------7-----7--|--bis--| |----7-----7-----|-------|-----------6-----6-----|-------| |----------------|-------|-----------------------|-------| |--7-------------|-------|---------0-------------|-------| A: "bis" is just Latin for "twice", it's a pretty common expression in romance language countries, not so much in other ones, I guess. I had never seen it in tablatures before, but I suppose the meaning should be to repeat the previous segment.
{ "pile_set_name": "StackExchange" }
Q: Versions of all firebase dependencies are the same, app still crashes right after start I noticed that this is quite common question around here so I did some research and tried to resolve this on my own, but without any positive results. So if anyone would have any ideas how to solve this problem I would really appreciate it. I have been stuck on this for hours now. I look up into these threads: Firebase database dependecny crashes app - there I found out that I should have all my dependency versions same. Android app crashes - in this thread they suggested that I should use the latest versions depending on google official website. And also here I found the same suggestions - versions should be the same, clean and rebuild your project etc. What I understand is the issue: The dependencies are incompatible. NOTE: My app worked fine just with the firebase-realtime database. After adding the firebase-auth it crashes instantly (testing on Huawei P9 lite NOT on emulator). What I have tried: 1) Making all the dependencies the newest versions. It didn’t work – still the app crashes right after start. implementation 'com.google.firebase:firebase-core:16.0.8' implementation 'com.google.firebase:firebase-database:16.1.0' implementation 'com.google.firebase:firebase-auth:16.2.0' 2) Downgrading the dependencies to the closest version that they have all in common based on this link (which is 16.0.5). implementation 'com.google.firebase:firebase-core:16.0.5' implementation 'com.google.firebase:firebase-database:16.0.5' implementation 'com.google.firebase:firebase-auth:16.0.5' 3) When I tried to add the firebase-auth through tools manager it inserted 'com.google.firebase:firebase-auth:16.0.3' which lead up to this error: ERROR: In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[15.0. 1]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown. Dependency failing: com.google.android.gms:play-services-flags:15.0.1 -> com.google.android.gms:play-services-basement@[ 15.0.1], but play-services-basement version was 16.0.1. The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art ifact with the issue. -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.firebase:[email protected] -- Project 'app' depends onto com.google.android.gms:[email protected] This is how my app level gradle file looks like: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.test123" minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.android.support:animated-vector-drawable:28.0.0' implementation 'com.android.support:support-media-compat:28.0.0' implementation 'com.android.support:support-v4:28.0.0' implementation 'com.google.firebase:firebase-core:16.0.5' implementation 'com.google.firebase:firebase-database:16.0.5' implementation 'com.google.firebase:firebase-auth:16.0.5' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } apply plugin: 'com.google.gms.google-services' This is my gradle file: // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { // Android Gradle Plugin classpath 'com.android.tools.build:gradle:3.3.2' // Google Services Plugin classpath "com.google.gms:google-services:4.2.0" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } And finally my logcat: 04-05 14:04:36.000 906-906/? I/art: Late-enabling -Xcheck:jni 04-05 14:04:36.192 906-906/com.example.test123 W/System: ClassLoader referenced unknown path: /data/app/com.example.test123-1/lib/arm64 04-05 14:04:36.439 906-922/com.example.test123 I/art: Background partial concurrent mark sweep GC freed 11193(638KB) AllocSpace objects, 4(80KB) LOS objects, 21% free, 15MB/19MB, paused 343us total 105.488ms at HeapTaskDaemon thread CareAboutPauseTimes 1 04-05 14:04:36.658 906-957/com.example.test123 W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. 04-05 14:04:36.686 906-956/com.example.test123 I/FA: App measurement is starting up, version: 14700 04-05 14:04:36.686 906-956/com.example.test123 I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE 04-05 14:04:36.686 906-956/com.example.test123 I/FA: To enable faster debug mode event logging run: adb shell setprop debug.firebase.analytics.app com.example.test123 04-05 14:04:36.717 906-906/com.example.test123 I/FirebaseInitProvider: FirebaseApp initialization successful 04-05 14:04:36.723 906-961/com.example.test123 W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. 04-05 14:04:36.733 906-961/com.example.test123 I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions. 04-05 14:04:36.733 906-961/com.example.test123 I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation 04-05 14:04:37.017 906-976/com.example.test123 I/System: core_booster, getBoosterConfig = false 04-05 14:04:37.048 906-906/com.example.test123 I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl 04-05 14:04:37.254 906-906/com.example.test123 W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable 04-05 14:04:37.673 906-906/com.example.test123 I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper> 04-05 14:04:37.674 906-906/com.example.test123 I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper> 04-05 14:04:38.485 906-906/com.example.test123 I/Process: Sending signal. PID: 906 SIG: 9 A: The problem may be at your device, it might not have the google play services up to date to support the version that your app is requesting. Try updating your google play services in your device or change to another device and test it there.
{ "pile_set_name": "StackExchange" }
Q: In ASP.NET Core Razor Pages, how to get view engine path for a page outside that page's context? Say I have an Index page directly under Pages. In the context of that page, I can access PageContext.ActionDescriptor.ViewEnginePath that stores the page's path, and get /Index. How do I get view engine path for any particular page outside a page's context? Does ASP.NET Core maintain a collection with view engine paths for all available pages/views that I can access? This is an ASP.NET Core 2.2 application. A: I have the following razor page that I use for debugging all of the route info. You can use as is or grab the _actionDescriptorCollectionProvider.ActionDescriptors.Items and look for the specific value you are looking for. .cs code: using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.RazorPages; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; namespace RouteDebugging.Pages { public class RoutesModel : PageModel { private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; public RoutesModel(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) { this._actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } public List<RouteInfo> Routes { get; set; } public void OnGet() { Routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items .Select(x => new RouteInfo { Action = x.RouteValues["Action"], Controller = x.RouteValues["Controller"], Name = x.AttributeRouteInfo?.Name, Template = x.AttributeRouteInfo?.Template, Constraint = x.ActionConstraints == null ? "" : JsonConvert.SerializeObject(x.ActionConstraints) }) .OrderBy(r => r.Template) .ToList(); } public class RouteInfo { public string Template { get; set; } public string Name { get; set; } public string Controller { get; set; } public string Action { get; set; } public string Constraint { get; set; } } } } With a cshtml page to view it nicely in a table: @page @model RouteDebugging.Pages.RoutesModel @{ ViewData["Title"] = "Routes"; } <h2>@ViewData["Title"]</h2> <h3>Route Debug Info</h3> <table class="table table-striped table-bordered"> <thead> <tr> <th>Route Template</th> <th>Controller</th> <th>Action</th> <th>Constraints/Verbs</th> <th>Name</th> </tr> </thead> <tbody> @foreach (var route in Model.Routes) { @if (!String.IsNullOrEmpty(route.Template)) { <tr> <td>@route.Template</td> <td>@route.Controller</td> <td>@route.Action</td> <td>@route.Constraint</td> <td>@route.Name</td> </tr> } } </tbody> </table>
{ "pile_set_name": "StackExchange" }
Q: Injecting a class depending on args I need to construct a ApplicationContext instance using Guice. Most of my other classes depends on ApplicationContext. However, ApplicationContext depends on the args array available in public static void main. Currently, I have to create ApplicationContext and call the setters by hand, then inject it with injectMembers before asking Guice to create other objects. Is there a better way to get my object created by Guice when it depends on args? ApplicationContext appContext = new ApplicationContext(); // configure my appContext from command line args injector.injectMembers(appContext); MyAppFoo a = injector.getInstance(MyAppFoo.class); a.doThings(); A: You can use providers or provider methods to construct ApplicationContext and configure it before it participates in other injections: public static void main(String[] args) { Injector injector = Guice.createInjector(b -> { b.bind(ApplicationContext.class).toProvider(() -> { // construct and configure application context ApplicationContext ctx = new ApplicationContext(); ctx.setSomething(args[0]); ctx.setSomethingElse(args[1]); return ctx; }).in(Singleton.class); }); }
{ "pile_set_name": "StackExchange" }
Q: Duplicate key update with multiple inserts How can I properly manage on duplicate key update for the following SQL query where I've multiple inserts going on? INSERT into user(id, first, last) VALUES(1, 'f1', 'l1'), (2, 'f2', 'l2') ON DUPLICATE KEY UPDATE first = 'f1', last = 'l1'; // what about f2/l2? Question: how can I specify multiple key update values for the above query or help with a lateral thinking please. Overview: the project is for synchronizing purposes from a remote json feed. A: Use VALUES: INSERT into user(id, first, last) VALUES(1, 'f1', 'l1'), (2, 'f2', 'l2') ON DUPLICATE KEY UPDATE first = VALUES(first), last = VALUES(last); This is like a function (really syntactic sugar) that says to get the value passed in for the insert to the row.
{ "pile_set_name": "StackExchange" }
Q: Divide two difftime objects I have three time (POSIXct) objects t1, t2, t3 which specify the time duration to complete a task. I found t1, t2, t3 by doing the following: t1 <- as.POSIXct("2016-10-30 13:53:34") - as.POSIXct("2016-10-30 13:35:34") t2 <- as.POSIXct("2016-10-30 14:53:34") - as.POSIXct("2016-10-30 14:35:34") t3 <- as.POSIXct("2016-10-30 15:50:34") - as.POSIXct("2016-10-30 15:40:34") I want to find the ratios t1/t3 and t2/t3. However, I get the following error: t1/t3 # Error in `/.difftime`(t1, t3) : # second argument of / cannot be a "difftime" object I understood that two difftime objects cannot be divided. Is there any way that I could find the result of dividing two difftime objects? A: To divide by a difftime you must convert it to numeric. If, as you stated in a comment, you would like the answer to be expressed in seconds, you can specify the 'secs' units. For example: t1/as.double(t3, units='secs') As @JonathanLisic notes, as.double does not generally take a units parameter, and this won't work for generic time classes. It is the S3 method for difftime which takes the parameter. A: As of today's date (9/2018), you can use as.numeric() to turn your difftime values into numeric values. ie, if you were to take as.numeric(t3) R will return 10 as desired. A: @MatthewLundberg's answer is more correct, but I'll suggest an alternative just to help illustrate the underlying structures of time-based objects in R are always just numbers: unclass(t1)/unclass(t3) # [1] 1.8 # attr(,"units") # [1] "mins" Note that, in terms of units, the approach of t1/as.double(t3, units = 'secs') doesn't make much sense, since the units of the output are min/sec, whereas this answer is unit-free. Note further that this approach is a bit dangerous, since by default, -.POSIXt (which is ultimately called when you define t1, t2, and t3) automatically chooses the units of the output (at core, -.POSIXt here will call difftime with the default units = "auto"). In this case, we are (maybe) lucky that all 3 are given units, but consider t4: t4 = as.POSIXct('2017-10-21 12:00:35') - as.POSIXct('2017-10-21 12:00:00') t4 # Time difference of 35 secs Again, if we use t4 in a ratio, we'll probably get the wrong units. We can avoid this by explicitly calling difftime and declaring the units upfront: t1 = difftime("2016-10-30 13:53:34", "2016-10-30 13:35:34", units = 'mins') t2 = difftime("2016-10-30 14:53:34", "2016-10-30 14:35:34", units = 'mins') t3 = difftime("2016-10-30 15:50:34", "2016-10-30 15:40:34", units = 'mins') t4 = difftime('2017-10-21 12:00:35', '2017-10-21 12:00:00', units = 'mins') t4 # Time difference of 0.5833333 mins
{ "pile_set_name": "StackExchange" }
Q: A function bound to multiple buttons internal variables are being shared I am binding an ajax calls to multiple buttons that are unique based on attached data attributes. Now the internal variables of the function are shared. So, if I click on multiple buttons (i.e. before previous ajax requests have completed) the variables are over-writing each other.... $('.btn-merge').click(function(){ $this = $( this ); pid = $this.data('pid'); cid = $this.data('cid'); $this.removeClass('btn-primary').addClass('btn-warning').prop('disabled',true).closest('li.suggestions').addClass('waiting-merge'); putData = { catalogId : cid, productId : pid }; $.post("///url///",putData,function (returnData){ if (returnData === 'true'){ suggestion = $this.removeClass('btn-warning').addClass('btn-success').closest('li.suggestions').removeClass('waiting-merge').addClass('success-merge').appendTo('ul.catalog-products').slideDown(); suggestion.find('.btn-unmerge').data('cid',cid).show().prop('disabled',false).removeClass('btn-success').addClass('btn-danger'); suggestion.find('.suggestion-cid').text('Catalog ID:'+cid); } else $this.removeClass('btn-warning').addClass('btn-danger').removeAttr('disabled'); }); }); A: You are using global variables. Inside your callback function, prefix variables with var to make sure they don't leak the scope.
{ "pile_set_name": "StackExchange" }
Q: How can I edit the attributes in a JSON using JavaScript I have the following JSON: [{ ID: '0001591', name: 'EDUARDO DE BARROS THOMÉ', class: 'EM1A', 'phone Pai': '(11) 999822922', 'email Pai': '[email protected]', { ID: '0001592', name: 'JEAN LUC EUGENE VINSON', class: 'EM1A', 'phone Pai': '(11) 981730534', 'email Pai': '[email protected]', And I wish that looks like that: [{ ID: '0001591', name: 'EDUARDO DE BARROS THOMÉ', class: 'EM1A', Address[ type:Phone, tag:Pai, address:'(11) 999822922', ] Address[ type:Email, tag:Pai, address:'[email protected]', ] }, { ID: '0001592', name: 'JEAN LUC EUGENE VINSON', class: 'EM1A', Address[ type:Phone, tag:Pai, address:'(11) 981730534', ] Address[ type:email, tag:Pai, address:'[email protected]', ] } ] Do you have any suggestions, please? A: After fixing your JSON a bit, let's say you have this JS object (btw. it's still an invalid JSON, but a valid JS object): var json = [{ ID: '0001591', name: 'EDUARDO DE BARROS THOMÉ', class: 'EM1A', 'phone Pai': '(11) 999822922', 'email Pai': '[email protected]' }, { ID: '0001592', name: 'JEAN LUC EUGENE VINSON', class: 'EM1A', 'phone Pai': '(11) 981730534', 'email Pai': '[email protected]' }]; It's a two-element array, with each array element being an object, so to access each object, you need to use an index, for example: json[0]; json[1]; To access a specific property of an object, you need to use the key, for example: json[0].name; json[0]['name']; // equal to above, but you'll need it for your keys with spaces Finally to add an object property, we can do something like this: json[0].Address = []; // make it an empty array json[0].Address.push({ type: 'Phone', tag: 'Pai', address: '(11) 999822922'}); // push the phone number json[0].Address.push({ type: 'Email', tag: 'Pai', address: '[email protected]'}); // push the email That will give you the final object you asked for. If you wish to make it automatic (I see you're reading 'phone Pai' and 'email Pai' values to build those new objects), you'd need to loop the whole array, parse the object keys to figure out the types and tags, and finally add an object property to each object based on the parsed data.
{ "pile_set_name": "StackExchange" }
Q: How can repeated addition/multiplication be done in polynomial time? I can see how adding 2 unsigned $n$-bit values is $O(n)$. We just go from the rightmost digits to the leftmost digits and add the digits up sequentially. We can also perform multiplication in polynomial time ($O(n^2)$) via the algorithm we all learned in grade school. However, how can we add up or multiply say $i$ numbers together in polynomial time? After we add up 2 numbers together, we get a bigger number that will require more bits to represent. Same with multiplication. How can we ensure that these extra bits do not produce exponential blowup? A: From what you said, I suppose that you consider complexity in terms of number of bits of the input. Say you add up two numbers $a$ and $b$, with respectively $n_1$ and $n_2$ bits, then the result is at most $\max(n_1, n_2) + 1$ bits since $a + b \leq 2 \times \max(a, b)$. For the multiplication, the result is at most $2 \times \max(n_1, n_2)$ bits since $a \times b \leq \max(a, b)^2$. The important thing is that the number of bits necessary to represent the sum / product of two numbers is polynomial in the number of bits to represent those numbers. Hence, for $i$ numbers, the number of bits necessary to represent the answer is still polynomial in the number of bits of the input (since composition of polynomial functions yields polynomial functions). Edit: actually, the really important thing is that $i$ is not part of the input, it is fixed. Otherwise, if you take for instance $2 \times 2 \times \ldots \times 2 = 2^i$, the answer takes $2^{i-1}$ bits, while the input takes $i + \log i$ bits. But if $i$ is fixed, then $2^{i-1}$ is a constant. This kind of distinction happens quite often in computer science, especially in the field of fixed parameter tractability.
{ "pile_set_name": "StackExchange" }
Q: How can I increment every foreign key in my database? I have two large MySQL databases with identical schemas that I want to merge. To do that I want to increase every foreign key (and id, naturally) of one database by 10 million, and then insert all the records of the modified db into the other db. I have thought about editing the mysqldump with tools like grep and gawk, but that seems very hard to do. What would be the best approach? A: OK, so here is the solution that I implemented, using the information_schema and a bash script. First I get every key-column in the database and the table in which it occurs, and then I update each of those columns. echo Incrementing every primary and foreign key by $increment # Get the table name and column name for every key from the information_schema select_constraints_sql="select TABLE_NAME, COLUMN_NAME from KEY_COLUMN_USAGE where CONSTRAINT_SCHEMA = 'MyDB'" # Place the query results in an array data=( $(mysql -e "$select_constraints_sql" -sN --user=$username --password=$passwd information_schema) ) # Step through the tables and keys and update each, with foreign key checks disabled # Foreign key checks must be disabled at each step ignore_fks_sql="SET FOREIGN_KEY_CHECKS = 0" cnt=${#data[@]} for (( i=0 ; i < cnt ; i=i+2 )) do update_key_sql="$ignore_fks_sql; UPDATE ${data[$i]} SET ${data[$i+1]} = ${data[$i+1]} + $increment" mysql -v -e "$update_key_sql" --user=$username --password=$passwd MyDB done # This is just me being a bit pedantic check_fks_sql="SET FOREIGN_KEY_CHECKS = 1" mysql -v --user=$username --password=$passwd -e "$check_fks_sql" MyDB
{ "pile_set_name": "StackExchange" }
Q: Don't syntax highlight my non-code Quite simple actually. I saw an answer, that desperately screamed for a little formatting as codeblock (quoting JavaDoc), and decided: "Why not suggest an edit?" Imagine how flabberghasted I was when I realized I can't stop code-prettify: for the record: I also tried <!-- language: none --> but to no avail. Is it just the preview, or are we not getting class="nocode" anymore? A: You need a newline between the paragraph and the comment. You need to call close() method on your MessageProducer. As per the Java docs:- <!-- language: lang-none --> void close() renders as: You need to call close() method on your MessageProducer. As per the Java docs:- void close() For documentation quotes, I'd not use a code block; I'd use > block quotes instead, however. I've edited that answer now to read: You need to call [`close()` method](http://docs.oracle.com/javaee/6/api/javax/jms/MessageProducer.html#close()) on your `MessageProducer`. As per the Java docs:- > void close() > throws JMSException > > Closes the message producer. > > Since a provider may allocate some resources on behalf of a `MessageProducer` outside the Java virtual machine, clients should close them when they are not needed. Relying on garbage collection to eventually reclaim these resources may not be timely enough. which formats as: You need to call close() method on your MessageProducer. As per the Java docs:- void close() throws JMSException Closes the message producer. Since a provider may allocate some resources on behalf of a MessageProducer outside the Java virtual machine, clients should close them when they are not needed. Relying on garbage collection to eventually reclaim these resources may not be timely enough. I corrected the documentation quote (it was badly copied), added correct attribution by linking and formatted the throws line to match the documentation indentation. Now the method signature is even correctly highlighted.
{ "pile_set_name": "StackExchange" }
Q: Asmx WebService - WSDL differs on DEBUG and RELEASE configuration I have the ASMX WebService (let's call it "A"), which is connected to 2 more webServices ("B" and "C"). The problem is, when I start WebService "A" on my local machine (using VS Development Server) on DEBUG configuration, the resulting wsdl:definitions node in the WSDL is like that (simplified and ordered): <wsdl:definitions ... xmlns:s1="B" xmlns:s2="C" xmlns:s3="http://microsoft.com/wsdl/types/" .../> And when I start the same service on the same local machine (using the same VS Development Server) on RELEASE config, it becomes this: <wsdl:definitions ... xmlns:s1="C" xmlns:s2="http://microsoft.com/wsdl/types/" xmlns:s3="B" .../> It's not the big problem by itself, but it gets harder to analyze my WSDL when needed. A: It turned out that checking the "Optimize code" flag on Debug fixes that problem. Still don't know what is the root of the problem though
{ "pile_set_name": "StackExchange" }
Q: Combine two SQL queries or prevent exclusion of data rows in existing query I have a SQL query: SELECT AnalyticsHub_Requests.Id AS reqId, AnalyticsHub_Requests.*, AnalyticsHub_StatusCodes.ShortDescription AS StatusText, Users.FullName + ' (' + COALESCE(WorkPhone,'Phone empty') + ')' AS Value, Users.Id FROM AnalyticsHub_StatusCodes INNER JOIN (Users INNER JOIN AnalyticsHub_Requests ON Users.[Id] = AnalyticsHub_Requests.[AssigneeId]) ON AnalyticsHub_StatusCodes.[Id] = AnalyticsHub_Requests.[StatusId] WHERE AnalyticsHub_Requests.StatusId = 4 OR AnalyticsHub_Requests.StatusId = 6; This returns 3 rows of data when all issues have an assignee. If an issue doesn't have an assignee, however, it will omit from the results. I've tried several different approaches but to no avail. How can I include data rows without an assignee in my results? A: Using the RIGHT JOIN (as mentioned in comments) I was able to prevent my query from omitting results. SELECT AnalyticsHub_Requests.Id AS reqId, AnalyticsHub_Requests.*, AnalyticsHub_StatusCodes.ShortDescription AS StatusText, Users.FullName + ' (' + COALESCE(WorkPhone,'Phone empty') + ')' AS Value, Users.Id FROM AnalyticsHub_StatusCodes INNER JOIN (Users RIGHT JOIN AnalyticsHub_Requests ON Users.[Id] = AnalyticsHub_Requests.[AssigneeId]) ON AnalyticsHub_StatusCodes.[Id] = AnalyticsHub_Requests.[StatusId] WHERE AnalyticsHub_Requests.StatusId = 4 OR AnalyticsHub_Requests.StatusId = 6;
{ "pile_set_name": "StackExchange" }
Q: NGINX prevent direct access to directory but allow rewrites Using NGINX to proxy to a cluster of RIAK nodes*. I have a rewrite rule like rewrite ^/bucket-([a-z]+)/object-([a-zA-Z0-9]+)/(.+)$ /riak/$1/$2 break; and a location block location /riak/ { proxy_pass http://riak_servers/riak/; } Which will redirect to one of the RIAK servers. Problem is, users can directly access http://server/riak/ and get directly to the RIAK cluster and bucket information. I want to only allow access to users requesting resources via the rewritten URL. I'd rather avoid any ifs or multiple location blocks to catch everything. I'm probably missing something obvious. NGINX 1.0.11 *This is generally a bad idea since anyone with access to the NGINX server can put/post stuff into your RIAK cluster. You should prevent all request types except GET and HEAD, also it's probably a good idea to remove andy X-* headers put in by RIAK. I don't think exposing the VClock value is a security issue but best to be safe. A: Use the internal directive to mark it as an internal location which is not accessible directly.
{ "pile_set_name": "StackExchange" }
Q: how to drive a N channel Mosfet transistor Hi I'm using an atmega 16 chip to drive a BS170 N channel enhancement mosfet. I'm unsure how would I go about this. Having read the datasheet, I'm guessing I set the pin the fet is connected to as a output pin. I would then set the PORTxn to high for on and low for off. Yes? I would have eight of these connected to the same chip. Is that ok? A: Yes. Did you also read the datasheet for the BS170? Datasheets are documents you have to learn how to read. In case of the BS170 \$V_{GS}\$ (page 2) is important. It's the minimum gate voltage at which the MOSFET starts conducting. For the BS170 this \$V_{GS}\$ can be anything between 0.8V and 3V. This wide range is typical of MOSFETs. It means that in a worst-case scenario you only get 1mA of drain current when driven from a 3V microcontroller, which isn't enough to drive a LED! If you're using the ATmega16 (and not the ATmega16L) you won't have this problem. Most important graph for the BS170 is figure 1 on page 3. This shows that at \$V_{GS}\$ = 5V you can have 800mA of drain current. MOSFET's gates are extremely ESD sensitive; you can zap them just by looking at them, so to speak. Make sure you're properly grounded when handling them (antistatic wrist strap), this also goes for your soldering iron. I also make it a habit to have a resistor from the gate to the source, this ensures that the BS170 remains off when for one reason or another the gate should be floating. This can be a 1M resistor. A: Yes that would work. Connecting 8 to the 8 outputs should be fine. Just remember MOSFETs are ESD sensitive.
{ "pile_set_name": "StackExchange" }
Q: RxJava2 PublishSubject does not have observers when doOnSubscribe called I am using RxJava2. i have some observable, and few subscribers that can be subscribed for it. each time when new subscribers arrive, some job should be done and each of subscribers should be notified. for this i decide to use PublishSubject. but when doOnSubscribe received from firs subscriber, myPublishSubject.hasObservers() return false... any idea why it happens and how can i fix this? private val myPublishSubject = PublishSubject.create<Boolean>() fun getPublishObservable():Observable<Boolean> { return myPublishSubject.doOnSubscribe { //do some job when new subscriber arrived and notify all subscribers //via myPublishSubject.onNext(true) } } Do I understand it correct, that when doOnSubscribe called it mean that there is at least one subscribers already present? A: i did not find ready answer, so i create my own version of subject and call it RefreshSubject. it based on PublishSubject but with one difference: if you would like to return observable and be notified when new subscriber arrives and ready to receive some data you should use method getSubscriberReady. here a small example: private RefreshSubject<Boolean> refreshSubject = RefreshSubject.create(); //ordinary publish behavior public Observable<Boolean> getObservable(){ return refreshSubject; } //refreshSubject behaviour public Observable<Boolean> getRefreshObserver(){ return refreshSubject.getSubscriberReady(new Action() { @Override public void run() throws Exception { //new subscriber arrives and ready to receive some data //so you can make some data request and all your subscribers (with new one just arrived) //will receive new content } }); } and here is full class: public class RefreshSubject<T> extends Subject<T> { /** The terminated indicator for the subscribers array. */ @SuppressWarnings("rawtypes") private static final RefreshSubject.RefreshDisposable[] TERMINATED = new RefreshSubject.RefreshDisposable[0]; /** An empty subscribers array to avoid allocating it all the time. */ @SuppressWarnings("rawtypes") private static final RefreshSubject.RefreshDisposable[] EMPTY = new RefreshSubject.RefreshDisposable[0]; /** The array of currently subscribed subscribers. */ private final AtomicReference<RefreshDisposable<T>[]> subscribers; /** The error, write before terminating and read after checking subscribers. */ Throwable error; /** * Constructs a RefreshSubject. * @param <T> the value type * @return the new RefreshSubject */ @CheckReturnValue public static <T> RefreshSubject<T> create() { return new RefreshSubject<T>(); } /** * Constructs a RefreshSubject. * @since 2.0 */ @SuppressWarnings("unchecked") private RefreshSubject() { subscribers = new AtomicReference<RefreshSubject.RefreshDisposable<T>[]>(EMPTY); } @Override public void subscribeActual(Observer<? super T> t) { RefreshSubject.RefreshDisposable<T> ps = new RefreshSubject.RefreshDisposable<T>(t, RefreshSubject.this); t.onSubscribe(ps); if (add(ps)) { // if cancellation happened while a successful add, the remove() didn't work // so we need to do it again if (ps.isDisposed()) { remove(ps); } } else { Throwable ex = error; if (ex != null) { t.onError(ex); } else { t.onComplete(); } } } public Observable<T> getSubscriberReady(final Action onReady){ return Observable.create(new ObservableOnSubscribe<T>() { @Override public void subscribe(ObservableEmitter<T> e) throws Exception { add(new RefreshDisposable(e, RefreshSubject.this)); onReady.run(); } }); } /** * Tries to add the given subscriber to the subscribers array atomically * or returns false if the subject has terminated. * @param ps the subscriber to add * @return true if successful, false if the subject has terminated */ private boolean add(RefreshSubject.RefreshDisposable<T> ps) { for (;;) { RefreshSubject.RefreshDisposable<T>[] a = subscribers.get(); if (a == TERMINATED) { return false; } int n = a.length; @SuppressWarnings("unchecked") RefreshSubject.RefreshDisposable<T>[] b = new RefreshSubject.RefreshDisposable[n + 1]; System.arraycopy(a, 0, b, 0, n); b[n] = ps; if (subscribers.compareAndSet(a, b)) { return true; } } } /** * Atomically removes the given subscriber if it is subscribed to the subject. * @param ps the subject to remove */ @SuppressWarnings("unchecked") private void remove(RefreshSubject.RefreshDisposable<T> ps) { for (;;) { RefreshSubject.RefreshDisposable<T>[] a = subscribers.get(); if (a == TERMINATED || a == EMPTY) { return; } int n = a.length; int j = -1; for (int i = 0; i < n; i++) { if (a[i] == ps) { j = i; break; } } if (j < 0) { return; } RefreshSubject.RefreshDisposable<T>[] b; if (n == 1) { b = EMPTY; } else { b = new RefreshSubject.RefreshDisposable[n - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, n - j - 1); } if (subscribers.compareAndSet(a, b)) { return; } } } @Override public void onSubscribe(Disposable s) { if (subscribers.get() == TERMINATED) { s.dispose(); } } @Override public void onNext(T t) { if (subscribers.get() == TERMINATED) { return; } if (t == null) { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); return; } for (RefreshSubject.RefreshDisposable<T> s : subscribers.get()) { s.onNext(t); } } @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { if (subscribers.get() == TERMINATED) { RxJavaPlugins.onError(t); return; } if (t == null) { t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); } error = t; for (RefreshSubject.RefreshDisposable<T> s : subscribers.getAndSet(TERMINATED)) { s.onError(t); } } @SuppressWarnings("unchecked") @Override public void onComplete() { if (subscribers.get() == TERMINATED) { return; } for (RefreshSubject.RefreshDisposable<T> s : subscribers.getAndSet(TERMINATED)) { s.onComplete(); } } @Override public boolean hasObservers() { return subscribers.get().length != 0; } @Override public Throwable getThrowable() { if (subscribers.get() == TERMINATED) { return error; } return null; } @Override public boolean hasThrowable() { return subscribers.get() == TERMINATED && error != null; } @Override public boolean hasComplete() { return subscribers.get() == TERMINATED && error == null; } /** * Wraps the actualEmitter subscriber, tracks its requests and makes cancellation * to remove itself from the current subscribers array. * * @param <T> the value type */ private static final class RefreshDisposable<T> extends AtomicBoolean implements Disposable { private static final long serialVersionUID = 3562861878281475070L; /** The actualEmitter subscriber. */ final Emitter<? super T> actualEmitter; /** The actualEmitter subscriber. */ final Observer<? super T> actualObserver; /** The subject state. */ final RefreshSubject<T> parent; /** * Constructs a PublishSubscriber, wraps the actualEmitter subscriber and the state. * @param actualEmitter the actualEmitter subscriber * @param parent the parent RefreshProcessor */ RefreshDisposable(Emitter<? super T> actualEmitter, RefreshSubject<T> parent) { this.actualEmitter = actualEmitter; this.parent = parent; actualObserver = null; } /** * Constructs a PublishSubscriber, wraps the actualEmitter subscriber and the state. * @param actualObserver the actualObserver subscriber * @param parent the parent RefreshProcessor */ RefreshDisposable(Observer<? super T> actualObserver, RefreshSubject<T> parent) { this.actualObserver = actualObserver; this.parent = parent; actualEmitter = null; } public void onNext(T t) { if (!get()) { if (actualEmitter != null) actualEmitter.onNext(t); if (actualObserver != null) actualObserver.onNext(t); } } public void onError(Throwable t) { if (get()) { RxJavaPlugins.onError(t); } else { if (actualEmitter != null) actualEmitter.onError(t); if (actualObserver != null) actualObserver.onError(t); } } public void onComplete() { if (!get()) { if (actualEmitter != null) actualEmitter.onComplete(); if (actualObserver != null) actualObserver.onComplete(); } } @Override public void dispose() { if (compareAndSet(false, true)) { parent.remove(this); } } @Override public boolean isDisposed() { return get(); } } }
{ "pile_set_name": "StackExchange" }
Q: std::thread throwing "resource dead lock would occur" I have a list of objects, each object has member variables which are calculated by an "update" function. I want to update the objects in parallel, that is I want to create a thread for each object to execute it's update function. Is this a reasonable thing to do? Any reasons why this may not be a good idea? Below is a program which attempts to do what I described, this is a complete program so you should be able to run it (I'm using VS2015). The goal is to update each object in parallel. The problem is that once the update function completes, the thread throws an "resource dead lock would occur" exception and aborts. Where am I going wrong? #include <iostream> #include <thread> #include <vector> #include <algorithm> #include <thread> #include <mutex> #include <chrono> class Object { public: Object(int sleepTime, unsigned int id) : m_pSleepTime(sleepTime), m_pId(id), m_pValue(0) {} void update() { if (!isLocked()) // if an object is not locked { // create a thread to perform it's update m_pThread.reset(new std::thread(&Object::_update, this)); } } unsigned int getId() { return m_pId; } unsigned int getValue() { return m_pValue; } bool isLocked() { bool mutexStatus = m_pMutex.try_lock(); if (mutexStatus) // if mutex is locked successfully (meaning it was unlocked) { m_pMutex.unlock(); return false; } else // if mutex is locked { return true; } } private: // private update function which actually does work void _update() { m_pMutex.lock(); { std::cout << "thread " << m_pId << " sleeping for " << m_pSleepTime << std::endl; std::chrono::milliseconds duration(m_pSleepTime); std::this_thread::sleep_for(duration); m_pValue = m_pId * 10; } m_pMutex.unlock(); try { m_pThread->join(); } catch (const std::exception& e) { std::cout << e.what() << std::endl; // throws "resource dead lock would occur" } } unsigned int m_pSleepTime; unsigned int m_pId; unsigned int m_pValue; std::mutex m_pMutex; std::shared_ptr<std::thread> m_pThread; // store reference to thread so it doesn't go out of scope when update() returns }; typedef std::shared_ptr<Object> ObjectPtr; class ObjectManager { public: ObjectManager() : m_pNumObjects(0){} void updateObjects() { for (int i = 0; i < m_pNumObjects; ++i) { m_pObjects[i]->update(); } } void removeObjectByIndex(int index) { m_pObjects.erase(m_pObjects.begin() + index); } void addObject(ObjectPtr objPtr) { m_pObjects.push_back(objPtr); m_pNumObjects++; } ObjectPtr getObjectByIndex(unsigned int index) { return m_pObjects[index]; } private: std::vector<ObjectPtr> m_pObjects; int m_pNumObjects; }; void main() { int numObjects = 2; // Generate sleep time for each object std::vector<int> objectSleepTimes; objectSleepTimes.reserve(numObjects); for (int i = 0; i < numObjects; ++i) objectSleepTimes.push_back(rand()); ObjectManager mgr; // Create some objects for (int i = 0; i < numObjects; ++i) mgr.addObject(std::make_shared<Object>(objectSleepTimes[i], i)); // Print expected object completion order // Sort from smallest to largest std::sort(objectSleepTimes.begin(), objectSleepTimes.end()); for (int i = 0; i < numObjects; ++i) std::cout << objectSleepTimes[i] << ", "; std::cout << std::endl; // Update objects mgr.updateObjects(); int numCompleted = 0; // number of objects which finished updating while (numCompleted != numObjects) { for (int i = 0; i < numObjects; ++i) { auto objectRef = mgr.getObjectByIndex(i); if (!objectRef->isLocked()) // if object is not locked, it is finished updating { std::cout << "Object " << objectRef->getId() << " completed. Value = " << objectRef->getValue() << std::endl; mgr.removeObjectByIndex(i); numCompleted++; } } } system("pause"); } A: Looks like you've got a thread that is trying to join itself.
{ "pile_set_name": "StackExchange" }
Q: Block header format Does anyone understand what each element of a block header represents? I have an example block header represented here: [ cd7bd64fba4cc782fe5474d3640882afece5887180591e72f80ce6916cf73526, 1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, f927a40c8b7f6e07c5af7fa2155b4864a4112b13, 30430d24554454b251003be3d027dea94397bf45cd34c6a06abcfec662242046, 56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421, 56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421, 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 3b32b8463f, 1780, 1388, "", 55ba9f2d, "Geth/v1.0.0/linux/go1.4.2", 437fa41b15c73334a947241ec885423a487d4401a0c3ec7c30550c1e039bccd7, c5317acb884dfc49, ] What do each of these elements represent? Is there an official source that also definitively says what each of these values mean? A: You can find the block header's structure in the Yellow paper, 4.4 (page 5). I don't have time to go through eveyrthing, but if I do not make any mistake, for example, you could bind the following: cd7bd64fba4cc782fe5474d3640882afece5887180591e72f80ce6916cf73526 --> Parent hash 1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 --> ommersHash f927a40c8b7f6e07c5af7fa2155b4864a4112b13 --> beneficiary 30430d24554454b251003be3d027dea94397bf45cd34c6a06abcfec662242046 --> stateRoot 56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421 --> transactionsRoot 56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421 --> receiptsRoot 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 --> logsBloom 3b32b8463f --> difficulty 1780 --> Number of ancestor blocks 1388 --> gasLimit "" --> gasUsed 55ba9f2d --> timestamp "Geth/v1.0.0/linux/go1.4.2" --> ExtraData 437fa41b15c73334a947241ec885423a487d4401a0c3ec7c30550c1e039bccd7 --> mixHash c5317acb884dfc49 --> nonce From what I read of your example, this matches pretty well.
{ "pile_set_name": "StackExchange" }
Q: Types of Equipment related Questions We are beginning to get closer to a usable definition of the types of sports we want to cover on the site (AFAIKS). But what about questions on equipment? From What should our FAQ contain? questions on equipment in general seems to be on topic. What about question on the various pro et con for equipment for a particular use? E.g. the different types of water-belts for long distance running? add-on spikes when running in the winter? running apps for mobile devices versus dedicated watches? Yet we don't want the obvious shopping questions - e.g. "which ... should I buy". How do we distinguish general equipment questions from shopping questions - that seems a little fuzzy to me. A: I think this can easily and safely be copied from other sites FAQ: F&N for instance: What kind of questions can I ask here? gear and gadgets used during exercise and it's not on... a purchase recommendation I think that in time it will be clear to us (and the rest). A: As far as equipment goes we walk a fine line between good expert Q&A on equipment and "shopping questions." Here are the guidelines I would enforce A question asking "What brand should I buy of X" is off topic. These kinds of things will age rapidly and will be rather useless long term. A question asking "Differentiate equipment X from Equipment Y" where X and Y are two distinct types of equipment (putter vs driver, barbell vs dumbbell etc) should be constructive. A question asking for the uses of different types of equipment and what circumstances they are good for is constructive. A question asking "What is the right type of X for me" is usually not constructive unless there is enough detail and then it may still be too localized. A question asking "how do I use equipment of type X" is constructive. These are my opinions on how equipment questions should be asked.
{ "pile_set_name": "StackExchange" }
Q: How to use Weierstrass test? How can I use Weierstrass test to determine a set $I$ on which the series $\displaystyle \sum_{n=1}^{\infty} nx^n(1-x)^n$ converges uniformly? Weierstrass test: Let $f_n : I \to \mathbb{R}$ be a sequence of functions with $|f_n(x)| \le M_n$ for all $x \in I$ and $k=1,2, \dots$. If $\sum_n M_n$ converges then $\sum_n f_n$ converges uniformly on $I$. A: The Weierstrass test is quite intuitive: it tells you that if you can bound each function in the series by a constant, and that this new series of constants converges, then so does your sum. (And what's more, it converges uniformly.) First note that if $\sum_n M_n$ is to converge then the sequence $(M_n)$ must be bounded. And since each $M_n$ is a bound for $f_n$, this means that the sequence $(f_n)$ must be uniformly bounded on $I$, the domain of the functions in the sequence. So there are two steps that you need to follow. First you need to find a subset $I \subseteq \mathbb{R}$ on which you can uniformly bound the $f_n$. Then you need to find whether the bounds you can attain satisfy the convergence condition of the Weierstrass test. Now, for any compact $I \subseteq \mathbb{R}$, your $f_n$ will be bounded in $x \in I$ because they are continuous. So you need to look instead at $n$: for which subset $I \subseteq \mathbb{R}$ is the sequence $(f_n(x))$ bounded for each fixed $x \in I$? Once you have worked this out, you can test to see if this subset gives way to the constants $M_n$ for which $|f_n(x)| \le M_n$ for each $x \in I$ and for which $\sum_n M_n$ converges.
{ "pile_set_name": "StackExchange" }
Q: Module development: hook_form(), hook_menu() and how to get $_POST I want to improve my knowledge in module development (which is far away from basic), so I try to develop a perimeter search module. What I've achieved for now is a block containing a form: function perimeter_search_block_view($delta = '') { // Define an empty array for the block output. $block = array(); switch($delta) { case 'perimeter_search_box': $block['subject'] = t('Perimeter search box'); $block['content'] = drupal_get_form('perimeter_search_form');; break; } return $block; } /** * Implementation of the perimeter search form * @return array with form data */ function perimeter_search_form($form, &$form_state) { $form = array( '#action' => 'perimeter-search-results', 'keyword' => array( '#type' => 'textfield' ), 'location' => array( '#type' => 'textfield' ), 'perimeter' => array( '#type' => 'select', '#title' => t('Perimeter'), '#options' => array('15 km', '30 km', '60 km', '120 km') ), 'submit' => array( '#type' => 'submit', '#value' => t('Start search') ) ); return $form; } I also have a function to output the search results: /** * Implementation of hook_menu() * @return defined menu/page items */ function perimeter_search_menu() { $items = array(); // Search results page $items['perimeter-search-results'] = array( 'title' => t('Perimeter search results'), 'page callback' => 'perimeter_search_results', 'access arguments' => array('view perimeter search'), 'type' => MENU_NORMAL_ITEM ); return $items; } /** * Processing job search queries */ function perimeter_search_results() { $page_content = t('Search results'); return $page_content; } My (simple?) question is: how to get the post data (keyword, location, perimeter) in my perimeter_search_results() function? A: Easy, you have to create the _submit function for your form, here an example: function perimeter_search_form_submit($form, &$form_state) { /* * Your data handling goes here on the $form_state['values']['myfieldname'] * variable. */ drupal_set_message(t('Awesome, you managed to fill the form!')); } And if you need to validate.. function perimeter_search_form_validate($form, &$form_state) { if($form_state['values'['myfieldname'] == '') { form_set_error('', t('Hey, it doesn't work like that!')); } } Just remember that if you add the attribute '#required' => TRUE to a form field, the field will be automatically validated to always require that field, so you don't need to use the validator for that field if you just need that it get compiled.
{ "pile_set_name": "StackExchange" }
Q: Is it OK to use H2 file mode for multiple computers I have to use the H2 database for only 2 PCs connected over LAN. I find it quite difficult to implement connection for server mode for 2 PCs over LAN. The LAN connection is such that the database is stored in 1 PC and is accessed from the other. So, I decided that I would run the database in server mode in 1 PC and file-mode from the other PC. Would it show the error that the database is "LOCKED BY ANOTHER PROCESS" (in the PC from which I am accessing the database in file-mode) or would it run perfectly fine? A: Yes, this works, if the database server is started within the same process as the embedded connection(s) to the database. The reason is, you can open multiple connection to the same database within the same process, so the server needs to run within the same process.
{ "pile_set_name": "StackExchange" }
Q: How to compile and run code and make gnuplot instruction in a single command line Hi I am bit ignorant about shell comand of Ubuntu. I would like to know if there is a way to construct a command that automatically compile ta c++ code and run it and for example the consequentely open gnuplot and plot the data produced by the code. I tryed to search on internet but I could not find anything which helped me with the gnuplot part!! If you have the solution or an idea or when I can learn it because it will save all of time instead of calling the 4 line command each time . Thank you. A: This works: g++ name.cpp && ./a.out && gnuplot -e "plot 'dati.dat' - pause -1"
{ "pile_set_name": "StackExchange" }
Q: How to find the optimum solution of Weighted set cover in O(2^n) A weighted set cover problem is: Given a universe $U=\{1,2,...,n\}$ and a collection of subsets of $U$, $\mathcal S=\{S_1,S_2,...,S_m\}$, and a cost function $c:\mathcal S\to Q^+$ , find a minimum cost subcollection of $\mathcal S$ that covers all elements of $U$. How to design a deterministic algorithm to solve weighted set cover in $O(2^n)$ (just find the optimum solution)? If I simply use exhaust searching to look through all possible cover (which is actually equals to $2^m$) and find the one with minimum weight, it will cost $O(2^m)$ but not $O(2^n)$. A: Use dynamic programming. For every $i \in [m]$ and every $V \subseteq U$, compute the minimal weight of sets among $S_1,\ldots,S_i$ needed to cover $V$. Here is pseudocode, which uses $w_i$ for the weight of $S_i$: Set $T[V][0] \gets \infty$ for all $\emptyset \neq V \subseteq U$, and $T[\emptyset][0] = 0$. For $i = 1,\ldots,m$: Set $T[V][i] \gets T[V][i-1]$ for all $V \subseteq U$. Set $T[V \cup S_i][i] \gets \min(T[V \cup S_i][i], T[V][i-1] + w_i)$ for all $V \subseteq U$. Return $T[U][m]$.
{ "pile_set_name": "StackExchange" }
Q: Java regex dies on stack overflow: need a better version I'm working on a JMD (Java MarkDown) (a Java port of MarkDownSharp) but I'm having an issue with one regex in particular. For the file Markdown_Documentation_Syntax.text this regular expression dies: private static final String BLOCK_TAGS_1 = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"; private static final String BLOCKS_NESTED_PATTERN = String.format("" + "(" + // save in $1 "^" + // start of line (with MULTILINE) "<(%s)" + // start tag = $2 "\\b" + // word break "(.*\\n)*?" + // any number of lines, minimally matching "</\\2>" + // the matching end tag "[ \\t]*" + // trailing spaces/tags "(?=\\n+|\\Z)" + // followed by a newline or end of ")", BLOCK_TAGS_1); which translates to: (^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b(.*\n)*?</\2>[ \t]*(?=\n+|\Z)) This pattern is looking for accepted block tags that are anchored to the start of a line, followed by any number of lines and then are terminated by a matching tag followed by a newline or a string terminator. This generates: java.lang.StackOverflowError at java.util.regex.Pattern$Curly.match(Pattern.java:3744) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168) at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4357) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227) at java.util.regex.Pattern$BmpCharProperty.match(Pattern.java:3366) at java.util.regex.Pattern$Curly.match0(Pattern.java:3782) at java.util.regex.Pattern$Curly.match(Pattern.java:3744) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168) at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4357) ... This can be dealt with by increasing the stack space for Java (defaults to 128k/400k for oss/ss IIRC) but the above expression is slow anyway. So I'm looking for a regex guru who can do better (or at least explain the performance problem with this pattern). The C# version is a little slow but works fine. PHP seems to have no issues with this either. Edit: This is on JDK6u17 running on Windows 7 64 Ultimate. A: This part: (.*\n)*? will involve A LOT of unnecessary backtracking because of the nested * and since there are chars that have to match afterwards. I just ran a quick benchmark in perl on some arbitrary strings and got a 13-15% improvement just by switching that piece to (?>.*\n)*? which does non-capturing, independent subgrouping. That gives you two benefits, it no longer wastes time capturing the matching string, and more importantly, it no longer backtracks on the innermost .* which is a waste of time anyway. There's no way that only a portion of that .* will ever result in a valid match so explicitly making it all or nothing should help. Don't know if that's a sufficient improvement in this case, however.
{ "pile_set_name": "StackExchange" }
Q: How to get sync status on headless dropbox install I have Dropbox running on a Debian server. I'd like to be able to find out the sync status - like you get when you right-click the dropbox icon in Windows, e.g. "Downloading 123 files" or "All up-to-date". I'm sure there's a way but Google is apparently not my friend on this one. Pls. note that I'm talking about the headless server install of dropbox, not the more common dropbox + dropbox-nautilus set up used for a typical linux desktop. A: It looks like you need to download the dropbox script for managing the daemon. Instructions on the dropbox website wget -O ~/dropbox.py https://www.dropbox.com/download?dl=packages/dropbox.py chmod a+x ~/dropbox.py ~/dropbox.py status You can also create a symlink to your dropbox script, so you don't have to type ~/dropbox.py to run it every time. sudo ln -s ~/dropbox.py /usr/local/bin/dropbox dropbox status
{ "pile_set_name": "StackExchange" }
Q: Jquery.switchclass is not loading properly 2 part question. So I want to be able to click the square at the middle which should slide the top left box to the right horizontally, and the top right box will slide to the bottom vertically, etc. Duration being 2 seconds for the slide. $(document).ready(function(){ $("#container").click(function(){ $("#box1, #box3").switchClass("horizontal", "newVertical", 1000); $("#box2, #box4").switchClass("vertical", "newHorizontal", 1000); }); }); in Fiddle animation is running. Does NOT run in chrome or firefox. Am I using the correct cdn? HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Cie Studios | Solution</title> <!--Stylesheet--> <link rel="stylesheet" href="ciestyle.css"> </head> <body> <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> <label>Fig 1.2</label> </section> <!--Google JQuery Lib --> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <!--Javascript --> <script src="ciescript.js"></script> </body> </html CSS * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; text-align:center; } #container { display:block; border:1px solid #000; background-color:#333333; height:151px; width:151px; } .horizontal { width:100px; height:50px; } .vertical { width:50px; height:100px; } .newHorizontal { width:100px!important; height:50px!important; float:left!important; border:0px!important; } .newVertical { width:50px!important; height:100px!important; float:right!important; border:0px!important; } #box1, #box3 { float:left; } #box2, #box4 { float:right; } #box1 { background-color:#ffffff; border-bottom:1px solid #000; } #box2 { background-color:#cccccc; border-left:1px solid #000000; } #box3 { background-color:#999999; border-right:1px solid #000000; } #box4 { background-color:#666666; border-top:1px solid #000000; } JQUERY $(document).ready(function(){ $("#container").click(function(){ $("#box1, #box3").switchClass("horizontal", "newVertical", 1000); $("#box2, #box4").switchClass("vertical", "newHorizontal", 1000); }); }); http://jsfiddle.net/pcdqz/1/ A: JqueryUI has a dependency on Jquery. Add <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> or a similar cdn link prior to loading JqueryUI.
{ "pile_set_name": "StackExchange" }
Q: Close program window from terminal without killing process I'm using linux and have a program which I want to automatically open and close on startup (with my "autostart" script). how can I do it? details: the program is xfce4-taskmanager, it opens with a little notification icon which I want in the taskbar, but I don't want the whole window open (this is why I want to open->close, so I get only the icon). I found no other way to get just the icon, but if there is it's also good. killing the process with kill or killall removes both the window and the icon. Thanks ahead A: GUI applications have windows What you want to achieve is only possible if an application is designed te have a background process running with no window. Hiding the windows Normally, a GUI application cannot run without its window, and killing the window is killing the application. What can be done to make the window invisible though, is: hiding the window by minimizing it hiding the window by unmapping it Both can be done programmatically with the help of xdotool, but if your goal is to destroy the window without destroying the application, I am afraid there is no way.
{ "pile_set_name": "StackExchange" }
Q: Best solution for lossy compression of a large amount (>10Tb) of volumetric data (astrophysics simulations) I work on large simulations of astrophysics (galaxy formation) and I have a problem of data management. In fact these simulations produce a very large amount of volumetic data (physical quantities on 3d cells (like 3d pixels)). My question is quite simple : what is, according to you, the best solution to compress such data (lossy compression). What I need is : - Adjustable lossy 3D compression - I don't need a "ready-to-use" solution, but an open-source lib/code that I can adapt to my simulation code - Ability to work on a large amount of data (the solution may come from libraries of image/volumetric image compression) Thank you very much. EDIT : This is not for plotting/displaying these data, this is for really reducing the weight of these data (because if I can reduce the weigth, I can write more time step of the simulation on disk, and so better resolve the dynamic of galaxies in post-processing) A: I am not quite sure if this is what you are looking for as this is not exactly compression and will not reduce the amount of data on your disk. But it can be used to simplify presentation and computation. A solution for presentation of large datasets is using a LOD implementation. They are per definition lossy, and some are adjustable. There are some continuous (and adjustable) LOD algorithms implemented here and here EDIT : you could actually use LOD as a compression method, if you store the output of the algorithm, but it would certainly be far from being the most efficient compression strategy
{ "pile_set_name": "StackExchange" }
Q: Looping through each row of 2D array with ForEach-Object I tried typing something like: $test = ("c2","d8","e9"),(4,1,9) (0..2) | % { "$test[0][$_] $test[1][$_]" } And I should expect it to output: c2 4 d8 1 e9 9 But I got this instead: System.Object[] System.Object[][0][0] System.Object[] System.Object[][1][0] System.Object[] System.Object[][0][1] System.Object[] System.Object[][1][1] System.Object[] System.Object[][0][2] System.Object[] System.Object[][1][2] What is the correct way to get the desired output? A: You can use variables directly in a string, but when you need to expand something more complex like a property, item in an array or another expression, then you need to use subexpressions $() $test = ("c2","d8","e9"),(4,1,9) (0..2) | % { "$($test[0][$_]) $($test[1][$_])" } c2 4 d8 1 e9 9
{ "pile_set_name": "StackExchange" }
Q: How do I route traffic from WiFi Hotspot to USB? Note:- I've found out that to achieve what I want, there is a simpler, more flexible way than reverse tethering. If you are ever in my situation, read the answer below. I reverse tether internet from laptop via USB, and wan't to share it further by creating an Hotspot on my rooted android phone. I get internet not just on my browser, but everywhere including Play Store and Whatsapp, when I reverse thether it from my laptop via USB. The only issue is that when I start a WiFi hotspot on my phone so that other devices can share this internet, they don't get internet. How do I fix this? Here is the commands I used to set up my phone to accept internet from my laptop: ifconfig rndis0 10.42.0.2 netmask 255.255.255.0 route add default gw 10.42.0.1 dev rndis0 ifconfig ccmni0 0.0.0.0 Where ccmni0 is my Mobile Data interface and rndis0 is the interface from which I get internet. Why I want to do this is irrelevant to the question, but read on if you want to. The reason for doing all this is that me and my room mate has to share a single LAN cable. Both of us run linux and have Broadcom WiFi cards, whose linux drivers don't allow you to create an AP from the laptop. I have linux only, while my friend uses linux only at times. When he is on Windows he creates a WiFi AP from his laptop using connectify. But when he is on linux, I want to temporarily create a hotspot via by mobile to share the internet. A: Although this does not specifically answer my question, I solved my problem. What I wanted to do is to share my internet with my friend via WiFi using my android mobile because my Linux powered laptop doesn't have driver support for creating WiFi APs. Broadcom sucks! I use my mobile phone to create a WiFi network(via hotspot), connect my laptop (source of internet) and other devices that require internet to the network. Now I configure my laptop to be a gateway and configure other devices to use my laptop as gateway. Here is the guide I followed. Lucky for me, I run Arch Linux. But this should work even if you are on some other linux distro like Ubuntu. So here it goes: Start hotspot on your mobile and connect the laptop which has internet and the device which needs internet connection. Create a script named start-gateway.sh with the following content. #!/bin/bash sysctl net.ipv4.ip_forward=1 iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT The script assumes that the interface which has internet is eth0 and you need to forward packets from wlan0 (your WiFi interface) to your Ethernet connection. So please confirm if these are the names of the interfaces from ifconfig output. Make the script executable and you are done: chmod u+x start-gateway.sh Whenever you need to start the gateway, execute the script with root privileges when connected to the WiFi: sudo ./start-gateway.sh Now all you have to do to get internet on other devices connected to the WiFi is to set the manually set IP configuration on those devices, giving the gateway as the IP address of your new gateway. Remember that by default the gateway will be the phone which is hosting the WiFi network(which has no internet), and you need to change the gateway to the one you have created.
{ "pile_set_name": "StackExchange" }
Q: Difference between Seagate Expansion and GoFlex HDD What are the significant differences between Seagate Expansion Portable 1 TB USB 3.0 (Model STAX1000302) and Seagate Free Agent GoFlex 1TB USB 3.0 (Model STAA1000302) except Data Encryption? I found Expansion models are cheaper. Regards, Arindam A: The output of: diff -u <(lynx -dump http://www.seagate.com/www/en-au/products/external/expansion/expansion_portable/) <(lynx -dump http://www.seagate.com/www/en-au/products/external/external-hard-drive/portable-hard-drive/) tells it all: -Seagate® Expansion™ Portable Drives +FreeAgent® GoFlex™ Ultra–portable Drive -A basic drive that goes wherever you do. +This ultra–upgradable, ultra–portable hard drive makes it ultra–easy for you +to store, backup, encrypt and access your files anytime, anywhere. - * Available with USB 2.0 or 3.0 plug–and–play connectivity. - * Transport files from one computer to another. - * Carry data wherever you need it. + * Features USB 2.0 or 3.0 plug–and–play connectivity + * Includes pre–loaded easy–to–use backup software + * Lets you upgrade to USB 3.0, FireWire^® 800 or eSATA + * Allows you to access your content on your TV, network and on–the–go + when combined with other GoFlex devices
{ "pile_set_name": "StackExchange" }
Q: Wicket: How to pass model changes to parent components? onModelChanged() doesn't work I have a component containing a form with many TextFields. The way it should work is that when changed, the value should be persisted immediately (no Save button, all through AJAX). The AJAX calls work fine, the value gets to the model. The code to save the model (and the entity contained) is in the parent component. I thought I would override onModelChanged() to propagate the changes from the components to the parent. But onModelChanged() is not called. Parent has its own model as class member field. The subcomponents use this: ReleaseTraitRowPanel( String id, IModel<IHasTraits> relModel, ... ) { ... PropertyModel<String> traitModel = new PropertyModel( relModel.getObject().getTraits(), prop); EditableLink4 link = new EditableLink4("link", traitModel){ // Pass the change notification to upper level. TODO: Does Wicket do this automatically? @Override protected void onModelChanged() { ReleaseTraitRowPanel.this.onModelChanged(); } }; ... } How should it be done? Should I pass the onModelChanged() at all? Or does wicket have some way to notify the other model of changes? Related - is CompoundPropertyModel only for forms, or can I use it with any component? I could use it here - prop is the same as id. A: Solved. The problem was that I had a Validator which always failed, and onModelChanged() is called after the validation passes. And the validation error message didn't get to FeedbackPanel since it didn't get added to AjaxRequestTarget... After all this is done, osdamv's answer also applies. I wrote a blog post about that. https://community.jboss.org/people/ozizka/blog/2013/01/21/wicket-creating-ajax-enabled-entity-based-pages
{ "pile_set_name": "StackExchange" }
Q: Multi-variate Optimization Problem Involving Sum of Log Terms $$\min_{\theta_i} \sum_{i=1}^K - \alpha_i \log(\theta_i)$$ s.t. $$1 \geq \theta_i \geq 0$$ $$\sum_{i=1}^K \theta_i = 1$$ $\alpha_i \geq 0$, but not all $\alpha_i$ is 0. I know that for $K=2$, $\theta^*_i = \frac{\alpha_i}{\sum_{j=1}^K \alpha_j}$. But, I am not sure if the same expression holds for K>2. Even if it does, how I can show it? A: Short answer : yes. Long answer: Let us set $f(\theta_1,\theta_2, ..., \theta_K):=\sum_{i=1}^K - \alpha_i \log(\theta_i)$ and for simplicity $\alpha_i \neq 0$ for all $i$. Let us set $g(\theta_1,\theta_2, ..., \theta_K):=\sum_{i=1}^K \theta_i $ Furthermore let us define a constant $c:=1$ Then the problem has the format which can be solved with the Method of Lagrange Multipliers: $$\min_{g(x)=c} f(x)$$ Acording to Lagrange there is a local minimum $x$ for that problem and a constant $\lambda$ and such that $$ \nabla f(x) = \lambda \nabla g(x) \\ g(x) =c $$ So we get (note that $\lambda$ cannot be 0) $$ - \alpha_i / \theta_i = \lambda \qquad(i=1,..,K)\\ \theta_i = - \alpha_i /\lambda \qquad(i=1,..,K) $$ Summing the last equations we get $$1=\sum_{i=1}^K \theta_i=-\lambda /\sum_{i=1}^K \alpha_i$$ so $\lambda=-\sum_{i=1}^K \alpha$. If we now substitute $\lambda$ in $- \alpha_i / \theta_i = \lambda$ we get $$\theta_i =\alpha_i/\sum_{j=1}^K \alpha_j$$ Since $f$ is a sum of convex function it is convex itself and therefore the local minimum is also a global minimum.
{ "pile_set_name": "StackExchange" }
Q: Skewed results when values go over the memory threshold N.b. The below code is deliberately done without using the library <math.h> N.b. 1 I posted earlier another question about this code, but was covering a different issue. This is the other question: Approximation of e^-x not returning the proper value To calculate the approximation of: I need to work with the following formula: I just wrote the below code to do just that. However, I see that when I try with large values for k, I start getting inaccurate results. For instance, when plugging in x=2 and k>=40 to get the value of e^-2 I don't see the correct results, but with x=2 and 12<k<40, all seems fine and I get the proper value: 0.135335. I understand this is due to the memory allocated to the values that act as numerator and denominator, but my questions are: The most I can do to fix this is to use Long double? And even then, I guess there is a memory limit again. How can I identify at which k value the memory is not enough and the results start to become inaccurate? This is so that I can prevent the user from entering k values that go over that threshold. #include <stdio.h> double f_fact(float i); double f_pot (float i, float x); int main() { double f_calculo, k, x, i; printf("Please specify the number of terms to sum (k)\n"); scanf("%lf", &k); printf("Please enter the value of the exponent (x)\n"); scanf("%lf", &x); for (i = 1; i <= k; ++i) { f_calculo = f_calculo + (double) f_pot (i, x) / f_fact(i); } printf("The result is: %lf\n", 1 + f_calculo); return 0; } double f_fact(float i) { int j; long long int factorial = 1; for (j = 1; j <= i; ++j) { factorial = factorial * j; } return (factorial); } double f_pot (float i, float x) { int j; double power = 1; for (j = 1; j <= i; ++j) { power = power * (-x); } return (power); } [1]: https://stackoverflow.com/questions/61602235/approximation-of-e-x-not-returning-the-proper-value A: About the first question: Yes, long double would increase the accuracy but also has its limits. So if you need more precision, you would have to implement your own datatype... (as mentioned in the comments) Second Question You could add a check for the limits, included in limits.h #include <limits.h> printf("The minimum value of LONG = %ld\n", LONG_MIN); printf("The maximum value of LONG = %ld\n", LONG_MAX);
{ "pile_set_name": "StackExchange" }
Q: Turtle graphics script keeps crashing when code is run I am creating a project that loads an image and converts it to 1 and zeros it will then draw this using turtle. However, every time I run it tells me that it has stopped working after the first column has been completed. If the problem is with the processing power of my computer I would like to know if there is a way to switch to a GPU to achieve the task. Any help would be greatly appreciated. Thanks def ShowMaze(possibleRoutes): turtle.delay(0) for x in range(0,len(Maze)): for y in range(0,len(Maze[0])): if Maze[x][y]==3: Maze[x][y]=0 for x in range(0,len(Maze)): turtle.forward(-5) turtle.right(90) turtle.forward(5/len(Maze[0])) turtle.left(90) for y in range(0,len(Maze[0])): if Maze[x][y]==1: turtle.fillcolor("black") turtle.begin_fill() elif Maze[x][y]==0: turtle.fillcolor("white") turtle.begin_fill() elif Maze[x][y]==4: turtle.fillcolor("green") turtle.begin_fill() elif Maze[x][y]==5: turtle.fillcolor("red") turtle.begin_fill() for i in range(0,4): turtle.forward(5/len(Maze[0])) turtle.left(90) turtle.end_fill() turtle.forward(5/len(Maze[0])) input() for ii in range(1,len(possibleRoutes)-1): turtle.pu() turtle.home() turtle.forward(-250) turtle.forward((250/len(Maze))*possibleRoutes[ii][1]) turtle.right(90) turtle.forward((250/len(Maze))*possibleRoutes[ii][0]+(250/len(Maze))) turtle.left(90) turtle.fillcolor("blue") turtle.pd() turtle.begin_fill() for x in range(0,4): turtle.forward(250/len(Maze[0])) turtle.left(90) turtle.end_fill() im = Image.open('D:/MazeSolver/ExampleMazePicture.JPG') # Can be many different formats. pix = im.load() size=250 Maze=[] length=im.size[0] # Get the width and hight of the Maze for iterating over for x in range(0,size,8): print("Row",x) row=[] for y in range(0,size,2): pix = im.load() if pix[x,y]>=(200,200,200): node=0 elif pix[x,y][0]>200 and pix[x,y][2]<200 and pix[x,y][1]<200: node=4 print("End") elif pix[x,y][1]>200 and pix[x,y][0]<50 and pix[x,y][2]<50: node=5 print("Start") elif pix[x,y]<=(50,50,50): node=1 else: print(pix[x,y]) row.append(node) Maze.append([row]) ShowMaze(Maze) A: This code is a mess. You input a JPEG maze image, called Maze, into a two dimensional array and pass it to ShowMaze(Maze) to show that you've read it in correctly. But ShowMaze() accesses Maze globally and thinks its argument is ShowMaze(possibleRoutes) where possibleRoutes through the maze were never calculated? Also: the X and Y sense of Maze seems inverted; the rows of the maze have an extra layer of list wrapped around them for no apparent reason; there's dead code included; you're not reading it in as 1s and 0s but rather four different color codes; the drawing code seems hopeless. I've reworked your code to simply read the maze into a list of lists and then display it with turtle using stamping instead of drawing to both simplify and speed up the code: from turtle import Screen, Turtle from PIL import Image CURSOR_SIZE = 20 PIXEL_SIZE = 5 COLORS = {0: 'white', 1: 'black', 4: 'green', 5: 'red'} def ShowMaze(maze): height, width = len(maze), len(maze[0]) screen = Screen() screen.setup(width * PIXEL_SIZE, height * PIXEL_SIZE) screen.setworldcoordinates(0, height, width, 0) turtle = Turtle('square', visible=False) turtle.shapesize(PIXEL_SIZE / CURSOR_SIZE) turtle.penup() screen.tracer(False) for y in range(height): for x in range(width): color = maze[y][x] if color in COLORS: turtle.fillcolor(COLORS[color]) else: turtle.fillcolor("orange") # error color turtle.stamp() turtle.forward(1) turtle.goto(0, turtle.ycor() + 1) screen.tracer(True) screen.mainloop() image = Image.open('ExampleMazePicture.JPG') # Can be many different formats. width, height = image.size # Get the width and height of the Maze for iterating over pixels = image.load() maze = [] for y in range(0, width, 4): print("Row:", y) row = [] for x in range(0, width, 4): node = -1 pixel = pixels[x, y] if pixel >= (200, 200, 200): node = 0 elif pixel[0] > 200 and pixel[1] < 200 and pixel[2] < 200: node = 4 print("End") elif pixel[0] < 50 and pixel[1] > 200 and pixel[2] < 50: node = 5 print("Start") elif pixel <= (50, 50, 50): node = 1 else: print(pixel) row.append(node) maze.append(row) ShowMaze(maze) Output based on using "Figure 1.6: Picobot’s maze." from this page as input: Hopefully this should provide you a starting point for the program you're ultimately trying to develop.
{ "pile_set_name": "StackExchange" }
Q: Small time behavior of Lévy processes Let $(X_t)_{t \geq 0}$ a Lévy process and $\varepsilon>0$. Is there anything known about the asymptotics of the probability $$\mathbb{P}(|X_t| > \varepsilon)$$ as $t \to 0$? Obviously, by the stochastic continuity, this probability converges to $0$ - but how fast? I tried to apply Markov's inequality (assuming that the corresponding moment exists); then I get $$\mathbb{P}(|X_t|>\varepsilon) \leq \frac{1}{\varepsilon} \cdot \mathbb{E}(|X_t|)$$ Unfortunately, I'm not aware of an estimate of the form $$\mathbb{E}(|X_t|) \leq C \cdot f(t)$$ for some constant $C>0$ and a function $f$ (which should converge to $0$ as $t \to 0$). The background is the following: When I tried to answer this question about Lévy processes, I was able to prove that it suffices to show that $$m \cdot \mathbb{P}(|X_{1/m}|>\varepsilon)^2$$ converges to $0$ as $m \to \infty$. And that's where I'm stuck... Thanks for any suggestions & hints! A: Lemma Let $(X_t)_{t \geq 0}$ be a one-dimensional Lévy process and $\varepsilon>0$. Then $$\limsup_{t \to 0} \frac{1}{t} \cdot \mathbb{P}(|X_{t}|>\varepsilon) \leq C $$ for some constant $C>0$. Proof: Denote by $\psi$ the characteristic exponent of $(X_t)_{t \geq 0}$. By the truncation inequality, $$\DeclareMathOperator \re {Re} \DeclareMathOperator \im {Im}\mathbb{P}(|X_{t}|>\varepsilon) \leq 7\varepsilon \cdot \int_0^{1/\varepsilon} (1-\re e^{-t \cdot \psi(y)}) \, dy \tag{1}$$ Recall that for any $u \geq 0$, $v \in \mathbb{R}$, we have $$|1-e^{-(u+\imath \, v)}| = \left| \int_0^{u+\imath \, v} e^-z \, dz \right| \leq |u+\imath \, v|.$$ Since $\text{Re} \, \psi(y) \geq 0$ for any $y \in \mathbb{R}$, this shows that $$\re(1-e^{-t \psi(y)}) \leq |1-e^{-t \psi(y)}| \leq t |\psi(y)|.$$ Since $y \mapsto \psi(y)$ is continuous, we obtain $$|1-\re e^{-t \cdot \psi(y)}| \leq C \cdot t, \qquad 0 \leq y \leq 1/\varepsilon$$ for some constant $C>0$. Plugging this estimate in $(1)$ finishes the proof. Remark Using the $d$-dimensional version of the truncation inequality $(1)$, it's not difficult to show the corresponding statement for any $d$-dimensional Lévy process. If $X$ has finite moments of second order, then the statement follows rather easily from Markov's inequality. Moreover, the example of the Poisson process shows that one cannot expect a faster convergence.
{ "pile_set_name": "StackExchange" }
Q: that there would be no perfect strategy for poker In my opinion, every imperfect information game where there is the possibility of bluffing lacks a perfect (or winning) strategy, for the simple reason that knowing your opponent's strategy will let you beat him easily (even if his strategy isn't 100% deterministic). So why do the guys that developed 'Cepheus' claim that they made a program playing poker with a perfect strategy, claiming that their AI 'is guaranteed to not lose money in the long run' ? I'm pretty sure I can create a strategy winning versus Cepheus, because I know its strategy. Where am I wrong ? A: Nash proved that every zero-sum game has a perfect strategy called a Nash equilibrium. This is a possibly randomized strategy for both players such that given that one player follows the strategy, it doesn't pay the other player to deviate from her strategy. As an example, consider the game rock, paper, scissors. One Nash equilibrium here has both players choosing their signal randomly. If one player does that, there is no point for the other player to follow any other strategy (though it doesn't hurt). Since Poker is a symmetric zero-sum game (both players are treated the same by the game), the value of the game is zero, and any Nash equilibrium on average results in zero expected profit for both players. According to Wikipedia, Cepheus is an approximation to such a strategy. As such, Cepehus' strategy may be randomized. What about bluffing? Let's consider a variant of rock, paper, scissors in which players can bluff. Say each player writes their choice on a piece of paper, and then there is some structured dialog in which players announce their choice and offer the other player to capitulate. The random strategy is still perfect, in that if one player follows it, it doesn't pay for the other player to deviate from it. While Cepehus (if it were perfect) shouldn't lose on the long run, it is not guaranteed to be a good strategy in practice, since it only promises you a small negative expected profit. Perhaps when playing against good human players it will just break even on average. That doesn't mean that humans are any better than it, just that they're not any worse. Another possibility is that while in theory the only guarantee is that it breaks even, in practice it wins against sub-optimal humans. This is an empirical question that the developers are testing right now through their website.
{ "pile_set_name": "StackExchange" }
Q: If $m$ objects are distributed among $n$ containers, then at least one container holds atleast $1 + \lfloor\frac {m − 1}{n}\rfloor$ objects. There are many ways that I can prove this. I want to prove using contradiction. The issue is that I have trouble negating the consequent. I am trying to contradict no container holds at most $1 + \lfloor\frac {m − 1}{n}\rfloor$ objects. This is really weird to interpret. It seems to say a container can hold more than $1 + \lfloor\frac {m − 1}{n}\rfloor$ objects. This is true because a container can hold m objects. This statement seems to be one that should not be contradicted. Second thought was that each container holds at most $1 + \lfloor\frac {m − 1}{n}\rfloor$ objects. This is easy to contradict because a container can have m objects. I do not think this actually implies the original implication was true, though. I do not want anyone to prove for me. I want to know if I am contradicting correct thing. A: You want the negation of the statement that $$\text{at least one container holds at least }1+\left\lfloor\frac{m-1}n\right\rfloor\text{ objects}\;.$$ That negation is: $$\text{no container holds at least }1+\left\lfloor\frac{m-1}n\right\rfloor\text{ objects}\;,$$ i.e., $$\text{no container holds }1+\left\lfloor\frac{m-1}n\right\rfloor\text{ or more objects.}$$ This is turn is equivalent to: $$\text{every container holds fewer than }1+\left\lfloor\frac{m-1}n\right\rfloor\text{ objects.}$$ In other words, if some container holds $k$ objects, then $k<1+\left\lfloor\frac{m-1}n\right\rfloor$. And since the number of objects in a container must be an integer, this means that $k\le\left\lfloor\frac{m-1}n\right\rfloor$. Thus, our negation can be restated as follows: $$\text{every container holds at most }\left\lfloor\frac{m-1}n\right\rfloor\text{ objects.}$$ Stated in more detail, it is: $$\text{if a container holds }k\text{ objects, then }k\le\left\lfloor\frac{m-1}n\right\rfloor\;.$$
{ "pile_set_name": "StackExchange" }
Q: I have upgrade ubuntu 13.10 and now my localhost not working I have upgraded my ubuntu 13.10 and i have got my localhost not working. When i tried to restrt my apache2, it gave an error like bellow, * Restarting web server apache2 [fail] * The apache2 configtest failed. Output of config test was: AH00526: Syntax error on line 1 of /etc/apache2/conf-enabled/httpd.conf: Invalid command '\xe2\x80\x9cServerName', perhaps misspelled or defined by a module not included in the server configuration Action 'configtest' failed. The Apache error log may have more information. How can i get localhost working agian... please help me A: have a look over here: https://askubuntu.com/questions/362682/ubuntu-13-10-server-403-error-after-upgrading-to-apache2-4 I just ran into this same issue, and this fixed the problem for me.
{ "pile_set_name": "StackExchange" }
Q: What is the value of an anonymous unattached block in C#? In C# you can make a block inside of a method that is not attached to any other statement. public void TestMethod() { { string x = "test"; string y = x; { int z = 42; int zz = z; } } } This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block. Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings. A: Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects. Ray Hayes points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit. A: An example would be if you wanted to reuse a variable name, normally you can't reuse variable names This is not valid int a = 10; Console.WriteLine(a); int a = 20; Console.WriteLine(a); but this is: { int a = 10; Console.WriteLine(a); } { int a = 20; Console.WriteLine(a); } The only thing I can think of right now, is for example if you were processing some large object, and you extracted some information out of it, and after that you were going to perform a bunch of operations, you could put the large object processing in a block, so that it goes out of scope, then continue with the other operations { //Process a large object and extract some data } //large object is out of scope here and will be garbage collected, //you can now perform other operations with the extracted data that can take a long time, //without holding the large object in memory //do processing with extracted data A: It's a by-product of a the parser rule that statement is either a simple statement or a block. i.e. a block can be used wherever a single statement can. e.g. if (someCondition) SimpleStatement(); if (SomeCondition) { BlockOfStatements(); } Others have pointed out that variable declarations are in scope until the end of the containing block. It's good for temporary vars to have a short scope, but I've never had to use a block on it's own to limit the scope of a variable. Sometimes you use a block underneath a "using" statement for that. So generally it's not valuable.
{ "pile_set_name": "StackExchange" }
Q: Bottom rail of wood panel door falling off I have a 20 year old, wood panel exterior door with a loose bottom rail. It looks like it's sliding off on one side. How can I fix it? If the rail is attached with a tenon I know I can just nail or pin it in place, but do modern wood doors have tenons? or are the just glued together? A: Hard to say whether it's a tenon or a few dowels, but assuming the wood is sound, you can pull the rail into place with a clamp (or a strap if you're low on 8' clamps) and put a couple of 8-10" screws through the stile into the rail. (Plenty of skinny long screws these days.) Predrill with a slightly smaller bit. Do a bit of a counterbore and you'll be able to hide the screw heads with filler. And if you haven't, paint the top/bottom of the door to seal it.
{ "pile_set_name": "StackExchange" }
Q: Many invalid symbol indices and undefined reference to main I have two programs I created. One is myThreads.c, and the other is myThreads_test.c, all in the same directory. Within that directory, I also have libslack.c which I use for its list capabilities. Finaly, I do have a myThreads.h I try to compile using: gcc -o myThreads_test.c myThreads.c -DHAVE_PTHREAD_RWLOCK=1 -lslack -lrt or gcc -o myThreads.c myThreads_test.c -DHAVE_PTHREAD_RWLOCK=1 -lslack -lrt and get the following errors: /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 12 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 21 has invalid symbol index 13 /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 22 has invalid symbol index 21 /usr/lib/gcc/i686-linux-gnu/4.6/../../../i386-linux-gnu/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status Which is weird because it seems the linker is throwing the errors not the compiler. In addition to that, depending on what order the c programs are in the above compilation commands, either myThreads.c gets deleted or myThreads_test.c gets deleted. I've neve seen that before. So I tried compiling with the different lines above. I have a feeling it has to do with the way I'm compiling though. Here is myThreads.c /*! @file myThreads.c An implementation of a package for creating, using and managing preemptive threads in linux. */ // Assignment 1 // Author: Georges Krinker // Student #: 260369844 // Course: ECSE 427 (OS) // Note: This file has been commented using doxygen style. // The API can be found at gkrinker.com/locker/OS/pa1 // Refer to doxygen.org for more info /********************************************//** * Includes ***********************************************/ #include <signal.h> #include <sys/time.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "myThreads.h" /********************************************//** * Defines ***********************************************/ #define MAX_NUMBER_OF_THREADS 20 ///< Limit on number of threads that can be created #define MAX_NUMBER_OF_SEMAPHORES 5 ///< Limit on number of semaphores that can be created #define DEFAULT_QUANTUM 250 ///< Default value for quantum if non is specified /** * Thread States */ #define BLOCKED 0 #define RUNNABLE 1 #define EXIT 2 #define RUNNING 3 #define NOTHREAD -1 /** * Error Handling */ #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while(0) /********************************************//** * Global Variables ***********************************************/ static ucontext_t mainContext; ///< Main context for initial thread static int quantum; ///< Quantum static int threads_completed; ///< 1 if all threads finished execution, ie EXIT state static int currentThread; ///< ID of currently running thread static long dispatcherCount; ///< Number of times the dispatcher has been called. static List *runQueue; ///< Thread Run Queue. Holds indices to the tcb table static mythread_control_block table[MAX_NUMBER_OF_THREADS]; ///< Holds thread control blocks static semaphore semaphores[MAX_NUMBER_OF_SEMAPHORES]; ///< Holds semaphores static int tableIndex; ///< Holds the next free table index in the table static int semaphoresIndex; ///< Holds the enxt free semaphore index in the table static sigset_t block_alarm; ///< The signal set that will be blocked /********************************************//** * Functions ***********************************************/ /** * This function initializes all the global data structures for the thread system. * * Creates a new Run Queue and initilaizes the indices for both the * TCB table and Semaphore table to 0. It then initializes the TCB * and semaphore table. Finally, [TO BE COMPLETED] */ int mythread_init(){ runQueue = list_create(NULL); tableIndex=0; semaphoresIndex=0; currentThread = -1; //No threads have been created yet. int i; quantum = DEFAULT_QUANTUM; threads_completed = 0; //Set all Thread Statuses to 'No Thread' in the TCB table for(i=0;i<MAX_NUMBER_OF_THREADS;i++){ table[i].status=NOTHREAD; } // Set all semaphores to inactive int j; for(j=0; j<MAX_NUMBER_OF_SEMAPHORES; j++) semaphores[j].active = 0; sigemptyset (&block_alarm); sigaddset (&block_alarm, SIGALRM); } /** * This function creates a new thread. * * The function is responsible for allocating the stack and setting * up the user context appropriately. The newly created thread * starts running the threadfunc function when it starts. The * threadname is stored in the TCB and is printed for info * purposes The newly created thread is in the RUNNABLE * state when inserted into the system. It is added to the run queue. * @return the ID of the newly created thread * @param *threadfunc() function to be called on context switch * @param stacksize size of stack to be allocated to */ int mythread_create(char *threadName, void (*threadfunc)(), int stacksize){ // Handle the error if any if (getcontext(&table[tableIndex].context) == -1) handle_error("ERROR IN GETCONTEXT!"); // Allocate a stack for the new thread and set it's return context table[tableIndex].context.uc_stack.ss_size = stacksize; //Set stack size table[tableIndex].context.uc_stack.ss_sp = malloc(stacksize); // allocate that space table[tableIndex].context.uc_link = &mainContext; // set the return context as the main Context // Modify the context and fill out the thread info on the TCB table makecontext(&table[tableIndex].context, threadfunc, 0); // set the function call and 0 arguments table[tableIndex].name = threadName; // set the thread name table[tableIndex].threadID = tableIndex; // set the thread ID table[tableIndex].status = RUNNABLE; // set the thread as RUNNABLE runQueue = list_append_int(runQueue, tableIndex); // add it to the run queue tableIndex++; //point to the next free slot return tableIndex-1; // returns ID of thread } /** * This function is called at the end of the function that was invoked * by the thread. * * The function firstly masks signals, sets the status of that * thread to 'EXIT' and then unblocks signals before returning. */ void mythread_exit(){ sigprocmask (SIG_BLOCK, &block_alarm, NULL); table[currentThread].status=EXIT; sigprocmask (SIG_UNBLOCK, &block_alarm, NULL); } /** * Sets the quantum for the round robin (RR) scheduler. * * @param quantum_size quantum size in us */ void set_quantum_size(int quantum_size){ quantum = quantum_size; } /** * Schedules threads in a Round Robin fashion. * * The function starts by checking if there are no more threads to run. * If that is the case, it sets threads_completed to 1 so that * run_threads() will terminate and resume to the mainContext. * If there are still runnable threads, the dispatcher switches threads * by swapping context, and putting the expired thread at the end of the * run queue. Finally, if there is only one runnable thread, that thread * is allowed to run for one more quantum. */ void dispatcher(){ dispatcherCount++; //if there are no more threads to run, and the current thread is done, set // threads_completed to 1 if(list_empty(runQueue) && table[currentThread].status==EXIT){ threads_completed=1; swapcontext(&table[currentThread].context, &mainContext); } //else switch to the next thread else if(!list_empty(runQueue)){ int nextThread = list_shift_int(runQueue); int tempCurrent = currentThread; currentThread = nextThread; // if the current thread (which is yielding to the next runnable thread) is runnable, queue it //back in the runqueue if(table[tempCurrent].status != EXIT && table[tempCurrent].status!=BLOCKED){ runQueue = list_append_int(runQueue, tempCurrent); table[tempCurrent].status = RUNNABLE; } table[nextThread].status = RUNNING; //set the the enxt thread to run sigprocmask (SIG_BLOCK, &block_alarm, NULL); //stop the dispatcher from being called while updating timing clock_gettime(CLOCK_REALTIME, &table[tempCurrent].stopTime); //record stop time table[tempCurrent].elapsedTime += (double) (table[tempCurrent].stopTime.tv_nsec - table[tempCurrent].startTime.tv_nsec); //update elapsed time clock_gettime(CLOCK_REALTIME, &table[currentThread].startTime);//record start timer of new thread sigprocmask (SIG_UNBLOCK, &block_alarm, NULL); //switch context swapcontext(&table[tempCurrent].context, &table[nextThread].context); } else{ //Keep the only thread that's runnable for 1 more quantum (do nothing!) } } /** * The runthreads() switches control from the main thread to one of the threads in the runqueue. * * The function starts by defining a signal timer that triggers every * quantum usecs and calls the dispatcher. The function then starts the * first thread by doing a context switch. */ void runthreads(){ //Set up the signal alarm to call dispatcher() every quantum interval struct itimerval tval; sigset(SIGALRM, dispatcher); tval.it_interval.tv_sec = 0; tval.it_interval.tv_usec = quantum; tval.it_value.tv_sec = 0; tval.it_value.tv_usec = quantum; setitimer(ITIMER_REAL, &tval, 0); // If there is nothing to run, throw an error! if(list_empty(runQueue)){ handle_error("In runthreads: RUN QUEUE IS EMPTY!"); } else{ int nextThread = list_shift_int(runQueue); //find the next thread to run currentThread = nextThread; //make it the current thread table[currentThread].status = RUNNING; //set it to running sigprocmask (SIG_BLOCK, &block_alarm, NULL); //stop signal from interrupting the timing calculations clock_gettime(CLOCK_REALTIME, &table[currentThread].startTime); //record start time of the new current thread sigprocmask (SIG_UNBLOCK, &block_alarm, NULL); swapcontext(&mainContext, &table[nextThread].context); //swap context } //only stop when there are no more threads to run! while(!threads_completed); } /** * This function creates a semaphore and sets its initial value to the given parameter. * * @param value initial semaphore value */ int create_semaphore(int value){ // handle error as usual if value is less than 0 if(value < 0) handle_error("semaphore initialization failed - value less than 0."); else{ semaphores[semaphoresIndex].initialValue = value; //set initial value to value semaphores[semaphoresIndex].value = semaphores[semaphoresIndex].initialValue; //set value semaphores[semaphoresIndex].active = 1; // make it ative now semaphores[semaphoresIndex].waitingThreads = list_create(NULL); //create a waitingThreads list for it } semaphoresIndex++; return semaphoresIndex-1; //return ID } /** * Calls wait() on a Semaphore * * When a thread calls this function, the value of the semaphore is decremented. * If the value goes below 0, the thread is put into a WAIT state. That means * calling thread is taken out of the runqueue if the value of the semaphore * goes below 0. * @param semaphore index of semaphore to be manipulated in the table * */ void semaphore_wait(int semaphore){ long oldDispatcherCount=dispatcherCount; //if trying to access a semaphore that doesn't show or is inactive handle it if(semaphore > semaphoresIndex || semaphores[semaphore].active==0) handle_error("Wrong semaphore index in wait()"); sigprocmask (SIG_BLOCK, &block_alarm, NULL); //mask signals for changing semaphore value (indivisibility) if(--semaphores[semaphore].value<0){ // if value < 0, add thread to waiting queue list_append_int(semaphores[semaphore].waitingThreads, currentThread); table[currentThread].status = BLOCKED; // change the status of the semaphore to BLOCKED } sigprocmask (SIG_UNBLOCK, &block_alarm, NULL); // Re-nable signals while(dispatcherCount == oldDispatcherCount); //wait for the scheduler to switch threads (could be made more efficient) } /** * Calls signal() on a Semaphore * * When a thread calls this function the value of the semaphore is incremented. * If the value is not greater than 0, then we should at least have one thread * waiting on it. The thread at the top of the wait queue associated with the * semaphore is dequeued from the wait queue and queued in the run queue. The * thread state is then set to RUNNABLE. * @param semaphore index of semaphore to be manipulated in the table * */ void semaphore_signal(int semaphore){ //if trying to access a semaphore that doesn't show or is inactive handle it if(semaphore > semaphoresIndex || semaphores[semaphore].active <0) handle_error("Wrong semaphore index in signal()"); if(++semaphores[semaphore].value<=0){ // if there are threads waiting... if(list_empty(semaphores[semaphore].waitingThreads)) //contradiction! No thread waiting? Error! handle_error("in Semaphore signal: there should be at least one waiting thread in semaphore"); //Dequeue a waiting thread and set it to RUNNABLE. Then add it to the run queue int readyThread = list_shift_int(semaphores[semaphore].waitingThreads); table[readyThread].status = RUNNABLE; list_append_int(runQueue, readyThread); } } /** * Destroys a semaphore. * * A call to this function while threads are waiting on the semaphore should fail. * That is the removal process should fail with an appropriate error message. * If there are no threads waiting, this function will proceed with the removal * after checking whether the current value is the same as the initial value of * the semaphore. If the values are different, then a warning message is * printed before the semaphore is destroyed. * @param semaphore index of semaphore to be manipulated in the table * */ void destroy_semaphore(int semaphore){ //if trying to access a semaphore that doesn't show or is inactive handle it if(semaphore > semaphoresIndex || semaphores[semaphore].active ==0) handle_error("Wrong semaphore index in destroy()"); //initil and final value check if(semaphores[semaphore].value != semaphores[semaphore].initialValue){ puts("\nWARNING: Destroying a semaphore with different initial and final values!\n"); } //check that there are no threads waiting on this baby if(!list_empty(semaphores[semaphore].waitingThreads)){ printf("Semaphore %i was not destroyed since one or more threads are waiting on it..\n",semaphore); } //destroy it by setting it to inactive! else{ semaphores[semaphore].active = 0; } } /** * Prints the state of all threads that are maintained by the library at * any given time. * * For each thread, it prints the following information in a tabular * form: thread name, thread state (print as a string RUNNING, BLOCKED, * EXIT, etc), and amount of time run on CPU. * */ void my_threads_state(){ int i; char* string; for(i=0; i<MAX_NUMBER_OF_THREADS; i++){ if(table[i].status != -1){ switch(table[i].status){ case 0: string = "BLOCKED"; break; case 1: string = "RUNNABLE"; break; case 3: string = "RUNNING"; break; case 2: string = "EXIT"; break; } printf("thread name: %s with ID number: %i is in state: %s and has run for %fms.\n", table[i].name, i, string, table[i].elapsedTime/1000000); } } } Here is myThreads.h /*! @file myThreads.h An implementation of a package for creating, using and managing preemptive threads in linux. */ // Multiple-include guard #ifndef __myThreads_H_ #define __myThreads_H_ #include <ucontext.h> #include <slack/std.h> #include <slack/list.h> /********************************************//** * Structures ***********************************************/ /*! \brief Structure that represents the thread control block (TCB). */ typedef struct _mythread_control_block { ucontext_t context; char *name; int threadID; //Between 0-# of Threads int status; // Any of the above defines struct timespec startTime; //when it was created struct timespec stopTime; // when it was stopped double elapsedTime; //start-stop in ns }mythread_control_block; typedef struct _mythread_semaphore{ int value; int initialValue; int active; List *waitingThreads; // holds indices to the semaphores table }semaphore; /********************************************//** * Functions ***********************************************/ /** * This function initializes all the global data structures for the thread system. * * Creates a new Run Queue and initilaizes the indices for both the * TCB table and Semaphore table to 0. It then initializes the TCB * and semaphore table. Finally, [TO BE COMPLETED] */ int init_my_threads(); /** * This function creates a new thread. * * The function is responsible for allocating the stack and setting * up the user context appropriately. The newly created thread * starts running the threadfunc function when it starts. The * threadname is stored in the TCB and is printed for info * purposes The newly created thread is in the RUNNABLE * state when inserted into the system. It is added to the run queue. * @return the ID of the newly created thread * @param *threadfunc() function to be called on context switch * @param stacksize size of stack to be allocated to */ int mythread_create(char *threadName, void (*threadfunc)(), int stacksize); /** * This function is called at the end of the function that was invoked * by the thread. * * The function firstly masks signals, sets the status of that * thread to 'EXIT' and then unblocks signals before returning. */ void mythread_exit(); /** * Sets the quantum for the round robin (RR) scheduler. * * @param quantum_size quantum size in us */ void set_quantum_size(int quantum_size); /** * Schedules threads in a Round Robin fashion. * * The function starts by checking if there are no more threads to run. * If that is the case, it sets threads_completed to 1 so that * run_threads() will terminate and resume to the mainContext. * If there are still runnable threads, the dispatcher switches threads * by swapping context, and putting the expired thread at the end of the * run queue. Finally, if there is only one runnable thread, that thread * is allowed to run for one more quantum. */ void dispatcher(); /** * The runthreads() switches control from the main thread to one of the threads in the runqueue. * * The function starts by defining a signal timer that triggers every * quantum usecs and calls the dispatcher. The function then starts the * first thread by doing a context switch. */ void runthreads(); /** * This function creates a semaphore and sets its initial value to the given parameter. * * @param value initial semaphore value */ int create_semaphore(int value); /** * Calls wait() on a Semaphore * * When a thread calls this function, the value of the semaphore is decremented. * If the value goes below 0, the thread is put into a WAIT state. That means * calling thread is taken out of the runqueue if the value of the semaphore * goes below 0. * @param semaphore index of semaphore to be manipulated in the table * */ void semaphore_wait(int semaphore); /** * Calls signal() on a Semaphore * * When a thread calls this function the value of the semaphore is incremented. * If the value is not greater than 0, then we should at least have one thread * waiting on it. The thread at the top of the wait queue associated with the * semaphore is dequeued from the wait queue and queued in the run queue. The * thread state is then set to RUNNABLE. * @param semaphore index of semaphore to be manipulated in the table * */ void semaphore_signal(int semaphore); /** * Prints the state of all threads that are maintained by the library at * any given time. * * For each thread, it prints the following information in a tabular * form: thread name, thread state (print as a string RUNNING, BLOCKED, * EXIT, etc), and amount of time run on CPU. * */ void my_threads_state(); #endif Finally, here is myThreads_test.c /*! @file myThreads_test.c A test program for testing myThreads.c */ // Assignment 1 // Author: Georges Krinker // Student #: 260369844 // Course: ECSE 427 (OS) // Note: This file has been commented using doxygen style. // The API can be found at gkrinker.com/locker/OS/pa1 // Refer to doxygen.org for more info /********************************************//** * Includes ***********************************************/ #include <stdio.h> #include <stdlib.h> #include "myThreads.h" /********************************************//** * Global Variables ***********************************************/ int mutex; //Mutex used by shared resources int a; int b; int mult; void multiply() { int i; for(i=0;i<1000;++i){ semaphore_wait(mutex); mult=mult+(a*b); a++; b++; semaphore_signal(mutex); } mythread_exit(); } int main(){ a=0; b=0; mult=0; mutex=create_semaphore(1); int threads = 12; // How many threads are to be created char* names[] = { "thread 0", "thread 1", "thread 2", "thread 3", "thread 4", "thread 5", "thread 6", "thread 7", "thread 8", "thread 9", "thread 10", "thread 11" }; mythread_init(); // Initialize Package set_quantum_size(50); // set quantum to 50 //Create threads int i=0; int dummy = 0; for(i=0; i<threads; i++) { dummy=mythread_create(names[i], (void *) &multiply, 100); } runthreads(); // Run threads my_threads_state(); // See state printf("The value of mult is %d\n", mult); return 0; } A: The -o means you want to specify the output file. Thus, gcc -o myThreads.c myThreads_test.c ... doesn't make much sense. Try compiling the two files separately: gcc myThreads.c -o myThreads ... gcc myThreads_test.c -o myThreads_test ... where myThreads and myThreads_test will be the executable file names.
{ "pile_set_name": "StackExchange" }
Q: Fill up white space in R Plots How does one get rid of white space when plotting in R as in the example below? I would like to do this because when I want to multiple plots on a page it looks terrible. I'm using the par function in the following way: par(mfrow=c(5,3),mai=rep(0,4), omi=rep(0,4)) pie3D(c(4,2,2,3,6,3),main="example") pie3D(c(4,2,2,3,6,3),main="example") ... pie3D(c(4,2,2,3,6,3),main="example") #do this 15 times. In my real work, it's 15 different pie charts. Which gives: A: The problem is that pie3D overwrites your margins to c(4,4,4,4). You can set margins in ?pie3D: library("plotrix") par(mfrow=c(5,3)) for (i in 1:15) pie3D(c(4,2,2,3,6,3),main="example", mar=c(0,0,1,0))
{ "pile_set_name": "StackExchange" }
Q: Force between a second and third body is such that they are rigidly bound together to form a composite body I am currently studying the textbook Classical Mechanics, fifth edition, by Kibble and Berkshire. In classical mechanics, we have that $$m_1 \mathbf{a}_1 + m_2 \mathbf{a}_2 + m_3 \mathbf{a}_3 = \mathbf{0}$$ If we suppose that the force between a second and third body is such that they are rigidly bound together to form a composite body, their accelerations must be equal: $\mathbf{a}_2 = \mathbf{a}_3$. In that case, we get $$m_1 \mathbf{a}_1 = -(m_2 + m_3) \mathbf{a}_2,$$ which shows that the mass of the composite body is just $m_{23} = m_2 + m_3$. So let's say that $m_{23}$ is the mass of a human, and $m_1$ is the mass of the Earth. We get $$(\text{Earth})\mathbf{a}_1 = -(\text{human})\mathbf{a}_2.$$ If I am interpreting this correctly, since masses are always positive, this means that we humans are decelerating towards the Earth at a deceleration of $\mathbf{a}_2$ and the Earth is accelerating towards us humans at an acceleration of $\mathbf{a_1}$ (or, equivalently, the Earth is decelerating towards at a deceleration of $\mathbf{a}_1$, and we humans are accelerating towards the Earth at an acceleration of $\mathbf{a}_2$)? But this then raises another question: If we know the masses of the two bodies, then assuming that we don't already know either of the accelerations, how is it possible for us to then calculate the accelerations $\mathbf{a}_1$ and $\mathbf{a}_2$? And, because of relativity, if everything is relative (there is no "absolute measuring stick"), how is it even possible for us to ever calculate such acceleration values? (I suspect that the issue here is that I'm not fully understanding the concept of an inertial frame of reference?) These are just some "novice" thoughts I had whilst studying the material. I would greatly appreciate it if people would please take the time to clarify this. A: Deceleration is a word I urge you to avoid using in a physics context. Acceleration is a vector quantity, so I would describe $$M_{E}\mathbf a_1= -m_H\mathbf a_2$$ as saying that the human has acceleration $\mathbf a_2$ and the Earth has acceleration $\mathbf a_1 = -\frac{m_H}{M_E}\mathbf a_2$. Equivalently, you could say that the Earth has acceleration $\mathbf a_1$ and the human has acceleration $\mathbf a_2 = -\frac{M_E}{m_h}\mathbf a_1$. The relative minus sign between the two accelerations indicates that they are in opposite directions. If we know the masses of the two bodies, then assuming that we don't already know either of the accelerations, how is it possible for us to then calculate the accelerations $\mathbf a_1$ and $\mathbf a_2$? That's what Newton's 2nd law does. If we know the forces acting on the two objects, then we can calculate their accelerations. In this particular case, imagine that the human is somewhere above the surface of the Earth (in, say, the $+\hat z$ direction). Newton's law of gravitation tells us that the force on the person is $$\mathbf F = G\frac{M_E m_h}{r^2} (-\hat z)$$ where $r$ is the distance between the human and the center of the Earth, and $-\hat r$ indicates that the force is directed downward (toward the center of the Earth). If this is the only force acting on the human, then since $\mathbf F = m\mathbf a$, we have that the human would accelerate with acceleration given by $$\mathbf a_2 = G\frac{M_E}{r^2}(-\hat z)$$ and the Earth would have acceleration $$\mathbf a_1 = G\frac{m_H}{r^2} \hat z$$ i.e. upward, toward the human. And, because of relativity, if everything is relative (there is no "absolute measuring stick"), how is it even possible for us to ever calculate such acceleration values? Velocity is relative, but acceleration is not. This particular example bumps up against the equivalence principle (which roughly says that free-fall in gravitational field is locally indistinguishable from non-accelerated motion in free space), but generally speaking, two observers with constant relative velocities must observe the same physics, but two observers with relative accelerations need (and generically will) not.
{ "pile_set_name": "StackExchange" }
Q: Place a Button in a EditView using TableLayout I am trying to make a search text field with a search button that is clickable (no rightDrawable stuff) in TableLayout. I have seen this done in RelativeLayout but I do not know how to do this in TableLayout. Here is my activity_main.xml: <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/TableLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="android.tabcards.app.MainActivity" > <TableRow android:id="@+id/searchTableRow" android:layout_width="fill_parent" android:layout_height="wrap_content" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Enter search key" /> <ImageButton android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_margin="30dp" android:src="@drawable/search" android:text="Button" /> </RelativeLayout> </TableRow> </TableLayout> I am trying to achieve something like this: ______________________ |Enter Text Here |->| ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ Edit: here is what it looks like now: A: You just need to center your EditText within your relative layout to align with the button. sample: <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:hint="Enter search key" />
{ "pile_set_name": "StackExchange" }
Q: MongoLab error - 'mongo not found' I am hosting an app on heroku and I'm trying to connect it to the MongoDB database using the MongoLab addon. One of the steps is to type: mongo ds044064-a0.mongolab.com:44064/heroku_w6fhwppg -u <dbuser> -p <dbpassword> But I keep getting the error "mongo not found" Anyone have any ideas why? The add-on is installed. Thanks! A: mongo refers to the mongo shell binary, which you'll need to install locally. It, along with all the other MongoDB binaries, can be downloaded here: https://www.mongodb.org/downloads
{ "pile_set_name": "StackExchange" }
Q: TypeError: grid is undefined I have uploaded a page where the error occurs. It´s displayed in the console (please use F12 in Firefox or Chrome Browser). http://preventdefault.lima-city.de/index.php This line is wrong: "kendo.stringify(grid.getOptions())" My Question: How must i change this code so that i could store the changed table settings? I also insert the html code here, Thx for answer ! <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.common.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.rtl.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.default.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.default.min.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> <script src="http://cdn.kendostatic.com/2014.3.1411/js/jszip.min.js"></script> <script src="http://cdn.kendostatic.com/2014.3.1411/js/kendo.all.min.js"></script> <style type="text/css"> .button-center { text-align: center; /* button position in grid */ } </style> </head> <body role="document"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> <div> <ul class="nav navbar-nav"> <li class="active"><a href="index.php">one</a></li> <li><a href="next.php">two</a></li> </ul> </div> </div> </nav> <div class="container theme-showcase" id="main" role="main"> <div class="container"> <h1>Page<small> one</small></h1> </div> <div class="row-fluid"> <div id="grid_one"></div> </div> <!-- row --> <div class="row-fluid"> <div id="log"></div> </div> <!-- row --> </div> <!-- container --> <script> <!-- --------------------------------------------------------------------------------- --> var firstNames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne", "Nige"], lastNames = ["Davolio", "Fuller", "Leverling", "Peacock", "Buchanan", "Suyama", "King", "Callahan", "Dodsworth", "White"], cities = ["Seattle", "Tacoma", "Kirkland", "Redmond", "London", "Philadelphia", "New York", "Seattle", "London", "Boston"], titles = ["Accountant", "Vice President, Sales", "Sales Representative", "Technical Support", "Sales Manager", "Web Designer", "Software Developer", "Inside Sales Coordinator", "Chief Techical Officer", "Chief Execute Officer"], birthDates = [new Date("1948/12/08"), new Date("1952/02/19"), new Date("1963/08/30"), new Date("1937/09/19"), new Date("1955/03/04"), new Date("1963/07/02"), new Date("1960/05/29"), new Date("1958/01/09"), new Date("1966/01/27"), new Date("1966/03/27")]; function createRandomData(count) { var data = [], now = new Date(); for (var i = 0; i < count; i++) { var firstName = firstNames[Math.floor(Math.random() * firstNames.length)], lastName = lastNames[Math.floor(Math.random() * lastNames.length)], city = cities[Math.floor(Math.random() * cities.length)], title = titles[Math.floor(Math.random() * titles.length)], birthDate = birthDates[Math.floor(Math.random() * birthDates.length)], age = now.getFullYear() - birthDate.getFullYear(); data.push({ Id: i + 1, FirstName: firstName, LastName: lastName, City: city, Title: title, BirthDate: birthDate, Age: age }); } return data; } <!-- --------------------------------------------------------------------------------- --> function onChangeSelection() { var selectedItem = this.dataItem(this.select()); var Text = '<h1><small>row name=</small>' + selectedItem.FirstName + " " + selectedItem.LastName + "</h1>"; console.log(Text); $("#log").html(Text); $("#ordernumber").val(selectedItem.ordernumber); } <!-- --------------------------------------------------------------------------------- --> function startbuttonclick(e) { var data = this.dataItem($(e.currentTarget).closest("tr")); var Text = "<h1><small>Button click name=</small> " + data.FirstName + " " + data.LastName + "</h1>"; console.log(Text); $("#log").html(Text); e.preventDefault(); } <!-- --------------------------------------------------------------------------------- --> $(document).ready(function() { $("#grid_one").kendoGrid({ dataSource: { data: createRandomData(10), schema: { model: { fields: { FirstName: { type: "string" }, LastName: { type: "string" }, City: { type: "string" }, Title: { type: "string" }, BirthDate: { type: "date" }, Age: { type: "number" } } } }, pageSize: 10 }, height: 500, dataBound: saveState, columnResize: saveState, columnShow: saveState, columnHide: saveState, columnReorder: saveState, columnLock: saveState, columnUnlock: saveState, selectable: true, resizable: true, columnMenu: true, scrollable: true, sortable: true, filterable: true, change: onChangeSelection, pageable: { refresh: true, pageSizes: true, buttonCount: 5, pageSizes: [5, 10, 20, 250] }, columns: [ { field: "FirstName", title: "First Name", width: "150px", }, { field: "LastName", title: "Last Name", width: "150px", }, { field: "City", hidden: true }, { field: "Title", hidden: true }, { field: "BirthDate", title: "Birth Date", template: '#= kendo.toString(BirthDate,"MM/dd/yyyy") #', width: "175px", }, { field: "Age", width: "150px", }, { command: { text: "Start", click: startbuttonclick }, title: "Start", width: "65px", attributes:{ "class":"button-center"} } ] }); <!-- ------------------------------------------------------------------------------ --> var grid = $("#grid_one").data("kendoGrid"); function saveState(e) { e.preventDefault(); localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions()); }; $(function (e) { var options = localStorage["kendo-grid-one"]; if (options) { grid.setOptions(JSON.parse(options)); } else { grid.dataSource.read(); } }); }); <!-- --------------------------------------------------------------------------------- --> </script> </body> </html> A: Edited for: Your var grid = $("#grid_one").data("kendoGrid"); only defined once, and it may not have data upon defined, it maybe insert by your kendogrid after. Domready Part should also need to have reference to it, you can either put it at origin location or move it into the function From your and dfsq's replies, the problem is that json CANNOT store a function, so you have to add it back to when retrieved from the localstorage In your current code, saveState will always be called before the setOptions one, which means the saveState just erased by your saveState function, so you have to move the setoptions code forward. Changes a lot $(document).ready(function() { // Get options first var options = localStorage["kendo-grid-one"]; if (options) { options = JSON.parse(options); // Workaround to addback event options.columns[6].command.click = startbuttonclick; } $("#grid_one").kendoGrid({ dataSource: { data: createRandomData(10), schema: { ..... }); if (options) { $("#grid_one").data("kendoGrid").setOptions(options); } <!-- ------------------------------------------------------------------------------ --> function saveState(e) { var grid = $("#grid_one").data("kendoGrid"); e.preventDefault(); localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions()); }; See Demo Here, now it works. saveState part use dfsq's may be better options.columns[6].command.click = startbuttonclick; may be can write in a more elegant style, but here I just want to show why the issues come out and how to apply a basic solution.
{ "pile_set_name": "StackExchange" }
Q: Spring ApplicationListener Neo4j BeforeSaveEvent doesn't work with Spring 4.2.0.RELEASE In my Neo4j/Spring Boot application with my Neo4jConfig I have a following hook: @Bean protected ApplicationListener<BeforeSaveEvent<BaseEntity>> beforeSaveEventApplicationListener() { return new ApplicationListener<BeforeSaveEvent<BaseEntity>>() { @Override public void onApplicationEvent(BeforeSaveEvent<BaseEntity> event) { BaseEntity entity = event.getEntity(); if (entity.getCreateDate() == null) { entity.setCreateDate(new Date()); } else { entity.setUpdateDate(new Date()); } } }; } It works perfectly with a previous version of Spring - 4.1.7.RELEASE but doesn't work with a last version 4.2.0.RELEASE I use SDN 3.4.0.RC1 and Spring Boot 1.2.5.RELEASE What could be the reason ? A: With Spring Framework 4.2+ the method in my question must look like: @EventListener public void handleBeforeSaveEvent(BeforeSaveEvent<BaseEntity> event) { BaseEntity entity = event.getEntity(); if (entity.getCreateDate() == null) { entity.setCreateDate(new Date()); } else { entity.setUpdateDate(new Date()); } } More details here: https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2
{ "pile_set_name": "StackExchange" }
Q: combine two different queries into one I have the following query: SELECT DISTINCT id, title FROM ((SELECT DISTINCT offers.id AS id, offers.title AS title FROM offers INNER JOIN categories ON offers.category=categories.title WHERE categories.title="Fashion clothes" GROUP BY offers.id ORDER BY offers.id) UNION ALL (SELECT DISTINCT offers.id AS id, offers.title AS title FROM offers INNER JOIN cities ON offers.city=cities.title WHERE cities.title="Australia" GROUP BY offers.id ORDER BY offers.id)) as subquery I would like to fetch from the table offers the rows that have category=Fashion clothes and city=Australia but when I use Union it returns all the rows . I don't know how to make it work. If anyone can help i would appreciate it. A: You don't need a union for this. Just join all the tables and have both conditions in you where clause: SELECT DISTINCT offers.id AS id, offers.title AS title FROM offers INNER JOIN categories ON offers.category=categories.title INNER JOIN cities ON offers.city=cities.title WHERE categories.title="Fashion clothes" AND cities.title="Australia" ORDER BY offers.id As noted by RubahMalam you don't even need the joins as you are joining the tables by title, so the query can be simplified to: SELECT DISTINCT offers.id AS id, offers.title AS title FROM offers WHERE offers.category="Fashion clothes" AND offers.city="Australia" ORDER BY offers.id However, it would probably be best to have separate unique id's in all your tables and use those to join them in your queries, but that's another story.
{ "pile_set_name": "StackExchange" }
Q: Rails best way to get previous and next active record object I need to get the previous and next active record objects with Rails. I did it, but don't know if it's the right way to do that. What I've got: Controller: @product = Product.friendly.find(params[:id]) order_list = Product.select(:id).all.map(&:id) current_position = order_list.index(@product.id) @previous_product = @collection.products.find(order_list[current_position - 1]) if order_list[current_position - 1] @next_product = @collection.products.find(order_list[current_position + 1]) if order_list[current_position + 1] @previous_product ||= Product.last @next_product ||= Product.first product_model.rb default_scope -> {order(:product_sub_group_id => :asc, :id => :asc)} So, the problem here is that I need to go to my database and get all this ids to know who is the previous and the next. Tried to use the gem order_query, but it did not work for me and I noted that it goes to the database and fetch all the records in that order, so, that's why I did the same but getting only the ids. All the solutions that I found was with simple order querys. Order by id or something like a priority field. A: Write these methods in your Product model: class Product def next self.class.where("id > ?", id).first end def previous self.class.where("id < ?", id).last end end Now you can do in your controller: @product = Product.friendly.find(params[:id]) @previous_product = @product.next @next_product = @product.previous Please try it, but its not tested. Thanks A: I think it would be faster to do it with only two SQL requests, that only select two rows (and not the entire table). Considering that your default order is sorted by id (otherwise, force the sorting by id) : @previous_product = Product.where('id < ?', params[:id]).last @next_product = Product.where('id > ?', params[:id]).first If the product is the last, then @next_product will be nil, and if it is the first, then, @previous_product will be nil. A: There's no easy out-of-the-box solution. A little dirty, but working way is carefully sorting out what conditions are there for finding next and previous items. With id it's quite easy, since all ids are different, and Rails Guy's answer describes just that: in next for a known id pick a first entry with a larger id (if results are ordered by id, as per defaults). More than that - his answer hints to place next and previous into the model class. Do so. If there are multiple order criteria, things get complicated. Say, we have a set of rows sorted by group parameter first (which can possibly have equal values on different rows) and then by id (which id different everywhere, guaranteed). Results are ordered by group and then by id (both ascending), so we can possibly encounter two situations of getting the next element, it's the first from the list that has elements, that (so many that): have the same group and a larger id have a larger group Same with previous element: you need the last one from the list have the same group and a smaller id have a smaller group Those fetch all next and previous entries respectively. If you need only one, use Rails' first and last (as suggested by Rails Guy) or limit(1) (and be wary of the asc/desc ordering).
{ "pile_set_name": "StackExchange" }
Q: How to add a dynamic formula to a cell reference using VBA? I am trying to add a dynamic formula to a cell using VBA. I have seen a couple of post on it but I cannot figure out what I am doing wrong. I am getting a run-time error '1004' for "Method 'Range' of object'_Worksheet' failed". What am I doing wrong? Sub AddFormulas() Dim LastNumberRow As Integer Set countBase = Sheet7.Range("CU2") colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count Dim startCount As Integer startCount = 98 For i = 1 To colCount If IsNumeric(Cells(2, startCount + i)) Then Sheet7.Range(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address Else 'Do some stuff End If Next i End Sub I have added the proposed changes from the comments below but not I get a file explorer popup window. I have altered my code with the following changes: If IsNumeric(Sheet7.Cells(2, startCount + i)) Then Set bSum = Sheet7.Cells(3, colCount + startCount) Set bSpr = Sheet6.Cells(3, startCount + i) Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address() A: I got it to work using this solution: Sub Formulas() 'Adds the formulas to the worksheet Dim rLastCell As Range Set countBase = Sheet6.Range("CU2") 'Starts at cell CU2 and counts the number of columns to the right that are being used colCount = Sheet6.Range(countBase, countBase.End(xlToRight)).Columns.Count Dim startCount As Integer startCount = 98 'This is column CT For i = 1 To colCount 'Checks to see if the value in row 2 starting at CU is a number, if it is it adds the index-match formula If IsNumeric(Sheet7.Cells(2, startCount + i)) Then bSpr = Sheet6.Cells(3, startCount + i).Address(True, False) Sheet6.Cells(3, startCount + i).Formula = "=INDEX(ORIG_MAT_DATA_ARRAY,MATCH($W3,MAT_RLOE_COLUMN),MATCH(" _ & bSpr & ",MAT_CY_HEAD))" & "/" & "INDEX(ORIG_MAT_DATA_ARRAY,MATCH($W3,MAT_RLOE_COLUMN),MATCH(""Total"",ORIG_MAT_CY_HEAD,0))" End If 'Checks to see if the value in row 2 starting at CU is the word "Total", if it is it adds the sum formula If Sheet6.Cells(2, startCount + i) = "Total" Then startCol = Cells(3, startCount + 1).Address(False, False) endCol = Cells(3, startCount + (colCount - 1)).Address(False, False) Sheet6.Cells(3, colCount + startCount) = "=SUM(" & startCol & ":" & endCol & ")" End If Next i End Sub
{ "pile_set_name": "StackExchange" }
Q: Convert byte array from Oracle RAW to System.Guid? My app interacts with both Oracle and SQL Server databases using a custom data access layer written in ADO.NET using DataReaders. Right now I'm having a problem with the conversion between GUIDs (which we use for primary keys) and the Oracle RAW datatype. Inserts into oracle are fine (I just use the ToByteArray() method on System.Guid). The problem is converting back to System.Guid when I load records from the database. Currently, I'm using the byte array I get from ADO.NET to pass into the constructor for System.Guid. This appears to be working, but the Guids that appear in the database do not correspond to the Guids I'm generating in this manner. I can't change the database schema or the query (since it's reused for SQL Server). I need code to convert the byte array from Oracle into the correct Guid. A: It turns out that the issue was the byte order you get in Guid.ToByteArray() and not Oracle itself. If you take the Guid "11223344-5566-7788-9900-aabbccddeeff" and call ToByteArray() on it, you get "44332211665588779900AABBCCDDEEFF". If you then pass that byte array back into the constructor for Guid, you get the original Guid. My mistake was trying to query the Oracle database by the original Guid format (with the dashes removed) instead of the result of the ToByteArray() call. I still have no idea why the bytes are ordered that way, but it apparently has nothing to do with Oracle. A: I just had this same issue when storing and reading Guids from Oracle. If your app needs to store and read Guids from Oracle, use the FlipEndian function from this thread: .NET Native GUID conversion Byte[] rawBytesFromOracle; Guid dotNetGuid = new Guid(rawBytesFromOracle).FlipEndian(); The flip is only required when reading back from Oracle. When writing to Oracle use Guid.ToByteArray() as normal. I spent TOO much time trying to get this simple task accomplished. Steve
{ "pile_set_name": "StackExchange" }
Q: Gerstenhaber versus Schouten In terms of formal definitions, is there any distinction between Schouten and Gerstenhaber algebras? A: Having read Schouten once, I can say that Schouten only looked for differential concomitants of tensor fields which are independent of the connection used, and found the Schouten bracket for skew multivector fields. (Added in edit: The graded Jacobi identity for it was noted by Nijenhuis.) This was extended by his student Nijenhuis together with Frölicher to tangent bundle valued forms. along the way they found also the Nijenhuis-Richardson bracket which is purely algebraic (i.e., $C^\infty(M)$-linear in each entry), so it was taken oven to the purely multilinear setting. But everything was for skew symmetric multiplications. I also read Gerstenhaber, and I seem to remember that he came independently from the pure algebraic setting, aiming for the associativity of any bilinear product. There seems to be a nice survey article of Lecomte and DeWilde on this. Edit: The following is what I remembered. It seems that the whole book is more relevant than the singe article that I remembered. De Wilde, M.(B-LIEG); Lecomte, P.(B-LIEG) Formal deformations of the Poisson Lie algebra of a symplectic manifold and star-products. Existence, equivalence, derivations. Deformation theory of algebras and structures and applications (Il Ciocco, 1986), 897–960, NATO Adv. Sci. Inst. Ser. C Math. Phys. Sci., 247, Kluwer Acad. Publ., Dordrecht, 1988.
{ "pile_set_name": "StackExchange" }
Q: Auto Scrolling in Metro App using C# and XAML I am making this Metro app which has a parent grid with 3 columns. In the col# 1, I have this login form. I want this to come at the center when the app loads. With the Sign Up and Recover passwords in col# 0 and col# 2 respectively. So I put the grid in a scrollviewer: ` <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="3*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <!--For Sign Up--> <ColumnDefinition Width="*" /> <!--For Sign In--> <ColumnDefinition Width="*" /> <!--To Recover Password--> </Grid.ColumnDefinitions>` I don't want to set the width of the grid explicitly. Because then either I would have to optimize the size for very large resolutions or very small. What I want is the col# 1 in the middle with a little of col#0 and col#2 visible at the sides of col#1. What should I set the width of grid to so that it looks consistent irrespective of the resolution? And how do I auto scroll and bring the col#1 in the middle? A: I think you need to capture the screen width programmatically. I'm a HTML/JS dev, so I don't know what the property is in XAML/C#. Then you can set your grid size relative to that. Then if it changes, your grid will be bigger. As far as the scrolling goes, I think you're looking for something like what I wrote here (http://www.codefoster.com/post/2012/06/24/How-to-Make-Your-Grid-Pan-Automatically.aspx), but you'll have to translate between the JavaScript and C# because I wrote it in JS. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: Idea of Covering Group $SU(2)$ is the covering group of $SO(3)$. What does it mean and does it have a physical consequence? I heard that this fact is related to the description of bosons and fermions. But how does it follow from the fact that $SU(2)$ is the double cover of $SO(3)$? A: Great, important question. Here's the basic logic: We start with Wigner's Theorem which tells us that a symmetry transformation on a quantum system can be written, up to phase, as either a unitary or anti-unitary operator on the Hilbert space $\mathcal H$ of the system. It follows that if we want to represent a Lie group $G$ of symmetries of a system via transformations on the Hilbert space, then we must do so with a projective unitary representation of the Lie group $G$. The projective part comes from the fact that the transformations are unitary or anti-unitary "up to phase," namely we represent such symmetries with a mapping $U:G\to \mathscr U(\mathcal H)$ such that for each $g_1,g_2\in G $, there exists a phase $c(g_1, g_2)$ such that \begin{align} U(g_1g_2) = c(g_1, g_2) U(g_1) U(g_2) \end{align} where $\mathscr U(\mathcal H)$ is the group of unitary operators on $\mathcal H$. In other words, a projective unitary representation is just an ordinary unitary representation with an extra phase factor that prevents it from being an honest homomorphism. Working with projective representations isn't as easy as working with ordinary representations since they have the pesky phase factor $c$, so we try to look for ways of avoiding them. In some cases, this can be achieved by noting that the projective representations of a group $G$ are equivalent to the ordinary representations of $G'$ its universal covering group, and in this case, we therefore elect to examine the representations of the universal cover instead. In the case of $\mathrm{SO}(3)$, the group of rotations, we notice that its universal cover, which is often called $\mathrm{Spin}(3)$, is isomorphic to $\mathrm{SU}(2)$, and that the projective representations of $\mathrm{SO}(3)$ match the ordinary representations of $\mathrm{SU}(2)$, so we elect to examine the ordinary representations of $\mathrm{SU}(2)$ since it's more convenient. This is all very physically important. If we had only considered the ordinary representations of $\mathrm{SO}(3)$, then we would have missed the "half-integer spin" representations, namely those that arise when considering rotations on fermionic systems. So, we must be careful to consider projective representations, and this naturally leads to looking for the universal cover. Note: The same sort of thing happens with the Lorentz group in relativistic quantum theories. We consider projective representations of $\mathrm{SO}(3,1)$ because Wigner says we ought to, and this naturally leads us to consider its universal cover $\mathrm{SL}(2,\mathbb C)$. A: After the answers by joshphysics and user37496, it seems to me that a last remark remains. The quantum relevance of the universal covering Lie group in my opinion is (also) due to a fundamental theorem by Nelson. That theorem relates Lie algebras of symmetric operators with unitary representations of a certain Lie group generated by those operators. The involved Lie group, in this discussion, is always a universal covering. In quantum theories one often encounters a set of operators $\{A_i\}_{i=1,\ldots, N}$ on a common Hilbert space ${\cal H}$ such that: (1) They are symmetric (i.e. defined on a dense domain $D(A_i)\subset {\cal H}$ where $\langle A\psi|\phi\rangle = \langle \psi|A\phi\rangle$) and (2) they enjoy the commutation relations of some Lie algebra $\ell$: $$[A_i,A_j]= \sum_{k=1}^N iC^k_{ij}A_k$$ on a common invariant domain ${\cal D}\subset {\cal H}$. As is known, given an abstract Lie algebra $\ell$ there is (up to Lie group isomorphisms) a unique simply connected Lie group ${\cal G}_\ell$ such that its Lie algebra coincide with $\ell$. ${\cal G}_\ell$ turns out to be the universal covering of all the other Lie groups whose Lie algebra is $\ell$ itself. All those groups, in a neighbourhood of the identity are isomorphic to a corresponding neighbourhood of the identity of ${\cal G}_\ell$. (As an example just consider the simply connected $SU(2)$ that is the universal covering of $SO(3)$) so that they share the same Lie algebra and are locally identical and differences arise far from the neutral element. If (1) and (2) hold, the natural question is: Is there a strongly continuous unitary representation ${\cal G} \ni g \mapsto U_g$ of some Lie group $\cal G$ just admitting $\ell$ as its Lie algebra, such that $$U_{g_i(t)} = e^{-it \overline{A_i}}\:\: ?\qquad (3)$$ Where $t\mapsto g_i(t)$ is the one-parameter Lie subgroup of $\cal G$ generated by (the element $a_i$ of $\ell$ corresponding to) $A_i$ and $\overline{A_i}$ is some self-adjoint extension of $A_i$. If it is the case, $\cal G$ is a continuous symmetry group for the considered physical system, the self adjoint operators $\overline{A_i}$ represent physically relevant observables. If time evolution is included in the center of the group (i.e. the Hamiltonian is a linear combination of the $A_i$s and commutes with each of them) all these observables are conserved quantities. Otherwise the situation is a bit more complicated, nevertheless one can define conserved quantities parametrically depending on time and belonging to the Lie algebra of the representation (think of the boost generators when $\cal G$ is $SL(2,\mathbb C)$). Well, the fundamental theorem by Nelson has the following statement. THEOREM (Nelson) Consider a set of operators $\{A_i\}_{i=1,\ldots, N}$ on a common Hilbert space ${\cal H}$ satisfying (1) and (2) above. If ${\cal D}$ in (2) is a dense subspace such that the symmetric operator $$\Delta := \sum_{i=1}^N A_i^2$$ is essentially self-adjoint on $\cal D$ (i.e. its adjoint is self-adjoint or, equivalently, $\Delta$ admits a unique self-adjoint extension, or equivalently its closure $\overline{\Delta}$ is self-adjoint), then: (a) Every $A_i$ is essentially self-adjoint on $\cal D$, and (b) there exists a strongly continuous unitary representation on $\cal H$ of the unique simply connected Lie group ${\cal G}_\ell$ admitting $\ell$ as Lie algebra, completely defined by the requirements: $$U_{g_i(t)} = e^{-it \overline{A_i}}\:\:,$$ where $t\mapsto g_i(t)$ is the one-parameter Lie subgroup of ${\cal G}_\ell$ generated by (the element $a_i$ of $\ell$ corresponding to) $A_i$ and $\overline{A_i}$ is the unique self-adjoint extension of $A_i$ coinciding to $A_i^*$ and with the closure of $A_i$. Notice that the representation is automatically unitary and not projective unitary: No annoying phases appear. The simplest example is that of operators $J_x,J_y,J_z$. It is easy to prove that $J^2$ is essentially self adjoint on the set spanned by vectors $|j,m, n\rangle$. The point is that one gets this way unitary representations of $SU(2)$ and not $SO(3)$, since the former is the unique simply connected Lie group admitting the algebra of $J_k$ as its own Lie algebra. As another application, consider $X$ and $P$ defined on ${\cal S}(\mathbb R)$ as usual. The three symmetric operators $I,X,P$ enjoy the Lie algebra of Weyl-Heisenberg Lie group. Moreover $\Delta = X^2+P^2 +I^2$ is essentially self adjoint on ${\cal S}(\mathbb R)$, because it admits a dense set of analytic vectors (the finite linear combinations of eigenstates of the standard harmonic oscillator). Thus these operators admit unique self-adjoint extensions and are generators of a unitary representation of the (simply connected) Weyl-Heisenberg Lie group. This example holds also replacing $L^2$ with another generic Hilbert space $\cal H$ and $X,P$ with operators verifying CCR on an dense invariant domain where $X^2+P^2$ (and thus also $X^2+P^2 +I^2$) is essentially self adjoint. It is possible to prove that the existence of the unitary rep of the Weyl-Heisenberg Lie group, if the space is irreducible, establishes the existence of a unitary operator from ${\cal H}$ to $L^2$ transforming $X$ and $P$ into the standard operators. Following this way one builds up an alternate proof of Stone-von Neumann's theorem. As a last comment, I stress that usually ${\cal G}_\ell$ is not the group acting in the physical space and this fact may create some problem: Think of $SO(3)$ that is the group of rotations one would like to represent at quantum level, while he/she ends up with a unitary representation of $SU(2) \neq SO(3)$. Usually nothing too terrible arises this way, since the only consequence is the appearance of annoying phases as explained by Josh, and overall phases do not affect states. Nevertheless sometimes some disaster takes place: For instance, a physical system cannot assume quantum states that are coherent superpositions of both integer and semi-integer spin. Otherwise an internal phase would take place after a $2\pi$ rotation. What is done in these cases is just to forbid these unfortunate superpositions. This is one of the possible ways to realize superselection rules. A: I'd like to add to Josh's answer, because he didn't really explain what a universal covering group is. Essentially, a space $T$ is a covering space of another space $U$ if, for an open subset of $U$, there's a function $f$ that maps a union disjoint open subsets of $T$ to the subset of $U$. Or, more simply worded, pick a piece of your space $U$, and I'll find you some number of different pieces of $T$ that have a function mapping them onto the piece of $U$. In the case of $T = Spin(3)$ and $U = SO(3)$, there are two disjoint subsets of $Spin(3)$ for every subset of $SO(3)$, so we say that $Spin(3) \cong SU(2)$ is the double cover of $SO(3)$. Now, the way that this relates to bosons and fermions is where Josh's answer comes in. We want physical states to live in vector spaces that carry (projective) representations of our symmetry groups. The "projective" part means that our states may pick up a phase when transformed to other states -- so, for example, if you rotate a spin-1/2 state 360$^{\circ}$, the state picks up a minus sign. It turns out that, at least in the case of $SO(3)$, we can eliminate the need for the "projective" part of this -- and thus those pesky minus signs -- by considering instead representations of the covering space.
{ "pile_set_name": "StackExchange" }
Q: Why water is so good at stopping certain bullets? When the Mythbusters tested it out, a pool of water stopped a 50. cal sniper rifle under 3 feet. Other weapons tend to go through water more easily, but high-velocity bullets just explode. Why is that? Why can water stop most bullets, and why it can't stop certain types that effectively? A: There are a couple ways to consider this situation. A somewhat simpler explanation that doesn't account for everything would be the drag equation: $$ F_{D}\,=\,{\tfrac 12}\,\rho \,u^{2}\,C_{D}\,A$$ where $F_D$ is drag force, $\rho$ is fluid density, $u$ is relative velocity, $C_D$ is the drag coefficient for the specific shape and speed, and $A$ is projected area in the direction of travel. Air is almost 800 times less dense than water. This means that going the same speed through air and water, a bullet will experience approximately 800 times more force in the water. Because of the $u^2$ term, increasing velocity increases the force dramatically, which is why faster bullets are more likely to break. Another factor is the shape, which will change the value of $C_D$. A more aerodynamic bullet would be less likely to explode on impact (though speed is likely to be a bigger factor). A more complicated explanation (and probably just as important or more important) is the compressibility of water. Water is not very compressible, and when you strike it at very high speeds, it may not initially behave as fluidly as you may like/expect. It could act more like a solid surface as the bullet impacts. To analyze this would be somewhat complex and would involve analyzing transient effects and compressibility. This is a bit more out of my wheelhouse, but something like the water hammer equation may be relevant (especially if you just flip the way you consider it, with the object approaching the water instead). This equation accounts for the equivalent bulk modulus, which describes the compressibility of the fluid. The sudden impact of fluids can be quite forceful. See also Why is jumping into water from high altitude fatal? and related links.
{ "pile_set_name": "StackExchange" }
Q: How to create a backup in Artifactory of a part of a repository? We can create backups of whole repositories in Aritfactory. One of the repo's is really too big. We want backup parts of it. Is it possible to create a backup of a part of a repository? A: The exclusion is possible only at the repository level. So, breaking up the large repo into smaller repos might be the only option available.
{ "pile_set_name": "StackExchange" }
Q: How to gently turn down a female coworker who asked for a sperm donation? I have a female co-worker (she's technically my superior but in another department). We've worked together for about 4.5 years and have been become pretty good friends, we'll always chat in the kitchen at work and occasionally see each other outside of work for drinks or whatnot. Recently she confided in me that her husband was sterile and asked if I would be willing to make a sperm donation so that she can have a child as she "really values my intelligence" (her words not mine). I think I'm simply not comfortable having a child out there whose life I have no part in (especially one being raised by someone so close by). I asked for some time to think about it but I'm sure she is expecting an answer soon. How can I turn her down in a way that won't hurt our friendship? A: Tell her exactly what you've written above. That you're "not comfortable having a child out there whose life I have no part in". If she tries to engage in a debate, remember that you don't owe her an explanation beyond that. I would absolutely not engage in a debate along the lines of "what if you could visit" or anything of the sort. When it comes to these sort of very private decisions you need not feel any pressure to elaborate. Be as polite as possible, but if she pushes the issue don't be afraid to cut her off: I can see that this was not the answer you were hoping for, but my decision is final, and I do not wish to engage in a debate. Thank you for understanding. You can then put the whole episode behind you if you wish to preserve the relationship. A: You just say, "I'm honored you thought of this. I'm sorry, that's not possible" and don't offer any further explanation or reason. Generally people want reasons to try to work around them; if you just don't want to do it then there's no need to offer a reason. Keep this in mind: in one recent case, the donor had to pay child support. Are you willing to take that risk? Even though most law absolves you of responsibility if done under a physician's supervision, if you aren't emotionally prepared for a relationship for the rest of your life with this person, it's not worth it. Co-workers come and go. Even if hurts your relationship, neither of the two of you will work there forever. Consider it an honor but don't let her guilt you into this if you're not ready. It's your life, too. A: If it's just about not having any part in the child's life, that would imply if you're allowed to have a part in the child's life, there wouldn't be a problem. Not intending to argue, just pointing out that this is something she might bring up if you mention "no part", which could lead to frustration on both sides (unless the above possibility is something you might be okay with). I'd suggest bringing how big a part you want to have instead, e.g.: I am honoured to have been asked, but unfortunately I wouldn't feel comfortable having a child out there without being the one raising them. This is much harder to argue against, because no matter how big a part you're given in their life, you still wouldn't be the one raising them. She could bring up the possibility of you having some part in the child's life in response to this, to which this simple reply should be all that's needed: It's just not the same, I still wouldn't be the one raising them.
{ "pile_set_name": "StackExchange" }
Q: How to print both key-value pairs in this Swift for-in example This example is from Apple's "A Swift Guide" section demonstrating for-in. Super newbie question, but how come it's not printing the type variable too? Is it something to do with the scope? let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 var type: String for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number type = kind } } } largest type A: Initialize type to an empty string first like this: var type: String = ""
{ "pile_set_name": "StackExchange" }
Q: h264_cuvid codec not found I'm trying to encode, apply a filter and decode a video through GPU. Im using H264_nvenc for encoding it, and trying to use h246_cuvid for the decoding, but FFMPEG can't find the decoder. Here is where the problem is decodingCodec = avcodec_find_encoder_by_name("h264_cuvid"); if (!decodingCodec) { av_log(NULL, AV_LOG_ERROR, "Codec not found DEC.\n"); return; } OS win 10 x64 EDIT: I'm actually using Zeranoe FFmpeg with the following config --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt I think that the problem is I didn't enable libnpp when compiling, could It be? A: are you sure avcodec_find_encoder_by_name() is the correct function ? Did you try avcodec_find_decoder_by_name ?
{ "pile_set_name": "StackExchange" }
Q: WSO2 Identity Server Limit on the number of IDP's I have being evaluating WSO2 Identity Server for an upcoming project. However we have a use case that would require 3,000+ SAML IDP's to be added for a given service. I can't find the relevant info online for the following. Is there a limit on the number of IDP's you can add to WSO2? What performance impact would it have? If you have worked with the product at a very large scale, can you share your experience? We are looking at 20 million+ Many thanks! :D A: There is no exact limitation for number of IDPs. This depends on the system resources. There might be a performance impact based on number of concurrent users, network latency, system resources etc.
{ "pile_set_name": "StackExchange" }
Q: Problems with displaying bitmap image in alert dialog I got a problem whenever i try to display my bitmap image on my alert dialog, the apps will force close or crash by display "unfortunately blabla.. has stopped", i guess something wrong with my bitmap image, any1 can help? thanks, below are my code: enter code here @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.marker_detail); String valueretrievee=null; //valueretrieve="2"; //get the large image view picView = (ImageView) findViewById(R.id.picture); //get the gallery view picGallery = (Gallery) findViewById(R.id.gallery); //create a new adapter imgAdapt = new PicAdapter(this); //set the gallery adapter picGallery.setAdapter(imgAdapt); //set the click listener for each item in the thumbnail gallery picGallery.setOnItemClickListener(new OnItemClickListener() { //handle clicks public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //set the larger image view to display the chosen bitmap calling method of adapter class picView.setImageBitmap(imgAdapt.getPic(position)); //start AlertDialog.Builder alertadd = new AlertDialog.Builder(ARTAADAfterTouch.this); //ImageView imageView = (ImageView) findViewById(R.id.picture); ImageView imageView = (ImageView) findViewById(R.id.picture); final Bitmap bitmap = Bitmap.createBitmap(imgAdapt.getPic(position)); imageView.setImageBitmap(bitmap); alertadd.setView(imageView); alertadd.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); alertadd.setNegativeButton("No", null); alertadd.show(); //end picView.setImageBitmap(bitmap); } }); } public void setData(String valueretrieve) { this.valueretrieve=valueretrieve; } public String getData() { return valueretrieve; } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { //check if we are returning from picture selection if (requestCode == PICKER) { //import the image } } //superclass method super.onActivityResult(requestCode, resultCode, data); //the returned picture URI Uri pickedUri = data.getData(); //declare the bitmap Bitmap pic = null; //declare the path string String imgPath = ""; //retrieve the string using media data String[] medData = { MediaStore.Images.Media.DATA }; //query the data Cursor picCursor = managedQuery(pickedUri, medData, null, null, null); if(picCursor!=null) { //get the path string int index = picCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); picCursor.moveToFirst(); imgPath = picCursor.getString(index); } else imgPath = pickedUri.getPath(); //pass bitmap to ImageAdapter to add to array imgAdapt.addPic(pic); //redraw the gallery thumbnails to reflect the new addition picGallery.setAdapter(imgAdapt); //display the newly selected image at larger size picView.setImageBitmap(pic); //scale options picView.setScaleType(ImageView.ScaleType.FIT_CENTER); } public class PicAdapter extends BaseAdapter { //use the default gallery background image int defaultItemBackground; //gallery context private Context galleryContext; //array to store bitmaps to display private Bitmap[] imageBitmaps; //placeholder bitmap for empty spaces in gallery Bitmap placeholder; //Intent ft= getIntent(); // gets the previously created intent //String firstKeyName = ft.getStringExtra("firstKeyName"); // will return "FirstKeyValue" public PicAdapter(Context c) { //instantiate context galleryContext = c; //copy right by aaron yong -> OVER HERE //String firstKeyName = intent.getStringExtra("firstKeyName"); // will return "SecondKeyValue" //create bitmap array imageBitmaps = new Bitmap[5]; //decode the placeholder image //placeholder = BitmapFactory.decodeResource(getResources(), R.drawable.hotel1); //placeholder = BitmapFactory.decodeResource(getResources(), R.drawable.hotel2); //more processing //Intent intent = getIntent(); //String valueretrieve = intent.getStringExtra("firstKeyName"); //set placeholder as all thumbnail images in the gallery initially for(int i=0; i<imageBitmaps.length; i++) { Bundle extras = getIntent().getExtras(); if (extras != null) { valueretrieve = extras.getString("myFirstKey"); } TextView theTextView = (TextView) findViewById(R.id.textView2); theTextView.setText(valueretrieve); //copy right by aaron yong ->> YESS! msut use equal!! if(theTextView.getText().equals("1")) { imageBitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.shop1); imageBitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.hotel1); } else if(theTextView.getText().equals("2")) { imageBitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.it1); imageBitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.hotel2); } else if(theTextView.getText().equals("3")) { imageBitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.transport1); imageBitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.transport2); } //imageBitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.hotel1); //imageBitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.hotel2); imageBitmaps[i]=placeholder; } //get the styling attributes - use default Andorid system resources TypedArray styleAttrs = galleryContext.obtainStyledAttributes(R.styleable.PicGallery); //get the background resource defaultItemBackground = styleAttrs.getResourceId( R.styleable.PicGallery_android_galleryItemBackground, 0); //recycle attributes styleAttrs.recycle(); } //************************************************* //return number of data items i.e. bitmap images public int getCount() { return imageBitmaps.length; } //return item at specified position public Object getItem(int position) { return position; } //return item ID at specified position public long getItemId(int position) { return position; } //get view specifies layout and display options for each thumbnail in the gallery public View getView(int position, View convertView, ViewGroup parent) { //create the view ImageView imageView = new ImageView(galleryContext); //specify the bitmap at this position in the array imageView.setImageBitmap(imageBitmaps[position]); //set layout options imageView.setLayoutParams(new Gallery.LayoutParams(470, 400)); //scale type within view area imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); //set default gallery item background imageView.setBackgroundResource(defaultItemBackground); //return the view return imageView; } //helper method to add a bitmap to the gallery when the user chooses one public void addPic(Bitmap newPic) { //set at currently selected index imageBitmaps[currentPic] = newPic; } //return bitmap at specified position for larger display public Bitmap getPic(int posn) { //return bitmap at posn index return imageBitmaps[posn]; } } } The logcat link in txt format : http://pastebin.com/4DSwxXx8 relevant logcat 05-10 00:22:24.867: E/AndroidRuntime(2276): FATAL EXCEPTION: main 05-10 00:22:24.867: E/AndroidRuntime(2276): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.addViewInner(ViewGroup.java:3339) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.addView(ViewGroup.java:3210) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.addView(ViewGroup.java:3186) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.app.AlertController.setupView(AlertController.java:413) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.app.AlertController.installContent(AlertController.java:241) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.app.AlertDialog.onCreate(AlertDialog.java:337) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.app.Dialog.dispatchOnCreate(Dialog.java:355) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.app.Dialog.show(Dialog.java:260) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.app.AlertDialog$Builder.show(AlertDialog.java:951) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.apu.ARTAAD.activity.ARTAADAfterTouch$1.onItemClick(ARTAADAfterTouch.java:123) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.widget.AdapterView.performItemClick(AdapterView.java:298) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.widget.Gallery.onSingleTapUp(Gallery.java:981) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.GestureDetector.onTouchEvent(GestureDetector.java:588) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.widget.Gallery.onTouchEvent(Gallery.java:958) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.View.dispatchTouchEvent(View.java:7246) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2168) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1903) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2090) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1417) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.app.Activity.dispatchTouchEvent(Activity.java:2410) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2038) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.View.dispatchPointerEvent(View.java:7426) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3220) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3165) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4292) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4271) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4363) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:179) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.os.MessageQueue.nativePollOnce(Native Method) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.os.MessageQueue.next(MessageQueue.java:125) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.os.Looper.loop(Looper.java:124) 05-10 00:22:24.867: E/AndroidRuntime(2276): at android.app.ActivityThread.main(ActivityThread.java:5195) 05-10 00:22:24.867: E/AndroidRuntime(2276): at java.lang.reflect.Method.invokeNative(Native Method) 05-10 00:22:24.867: E/AndroidRuntime(2276): at java.lang.reflect.Method.invoke(Method.java:511) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 05-10 00:22:24.867: E/AndroidRuntime(2276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 05-10 00:22:24.867: E/AndroidRuntime(2276): at dalvik.system.NativeStart.main(Native Method) enter code here A: You should change it to final View alertDialog= factory.inflate(R.layout.alert_dialog, null); ImageView imageView= (ImageView) view .findViewById(R.id.selectedImage); imageView.setImageBitmap(imgAdapt.getPic(position)); AlertDialog.Builder alertadd = new AlertDialog.Builder(ARTAADAfterTouch.this); alertadd.setView(alertDialog); alertadd.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); alertadd.setNegativeButton("No", null); alertadd.show(); add this to your layout directory (name it "alert_dialog.xml") <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FFFFFF" tools:context=".MainActivity" > <ImageView android:id="@+id/selectedImage" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
{ "pile_set_name": "StackExchange" }
Q: how to reject http request in expressjs app? My app has to load some data into memory at beginning of the program. I'd like to reject any request until all the data is loaded. What is the approach that I can use in expressjs? A: You might put app.listen into a callback that's run on completion for whatever data it is you're loading, instead of checking on a per-request basis. expressjs will not respond to any requests before app.listen is called.
{ "pile_set_name": "StackExchange" }
Q: AngularJS - $httpBackend cannot read nested JSON property I am trying to set up a http GET request expectation via jasmine but I'm getting following error: TypeError: Cannot read property 'user' of undefined The service function I want to test looks like: function getData() { return $http.get('http://example.com/data') .then(function (response) { return response.data.example.user; }); } A GET request to the URL "http://example.com/data" returns following data: { "id": "1", "example": { "user": [ { "name": "John", "wife": [ { "name": "Jane", "age": "27" } ] } } } The corresponding test looks like this: describe("Service: myService", function () { beforeEach(module("myApp")); var myService, $httpBackend; beforeEach(inject(function (_myService_, _$httpBackend_) { myService = _myService_; $httpBackend = _$httpBackend_; $httpBackend.whenGET("http://example.com/data").respond("some data"); })); afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it("should call the correct URL", function() { $httpBackend.expectGET("http://example.com/data"); myService.getData(); $httpBackend.flush(); }); Somehow I am not able to test a http GET request as soon as the service function (that I want to test) returns a nested JSON property instead of the entire JSON. Thanks in advance! A: Data responded by API should be mock data in correct format, here getData is method is expecting in object format, so that could return user from it. like response.data.example.user Code $httpBackend.whenGET("http://example.com/data").respond({ "id": "1", "example": { "user": [] //to keep you code working } })
{ "pile_set_name": "StackExchange" }
Q: What is .phpunit.result.cache When I run tests with PhpUnit on a new package I'm creating for Laravel, it generates the file .phpunit.result.cache. What to do with that? Do I add it to my .gitignore file or not? I'm using PHPUnit 8.0.4 A: This file helps PHPUnit remember which tests previously failed, which can speed up your testing flow if you only re-run failed tests during development. This is useful for test-driven workflows in which you have configured tests to run automatically, such as on file save, and the same collection of tests is being run repeatedly. It is also a good idea to add the cache file .phpunit.result.cache to your .gitignore so that it does not end up being committed to your repository. https://laravel-news.com/tips-to-speed-up-phpunit-tests If you would prefer not to generate the file then you can run phpunit with the --do-not-cache-result option, as pointed out by @Slack Undertow in the comments. This might be desired when running tests as part of a build pipeline, for example. Or, as @codekandis pointed out, the same option is available as the cacheResult attribute in phpunit.xml.
{ "pile_set_name": "StackExchange" }
Q: Android Programming: TextView isn't displaying full string I have a TextView that I am trying to make display a 2d character-based grid. In my Java code I have created a 2d array, I take that array filled with strings and append each entry one next to another, and when the end of the array row is reached, i also append a newline character (.n). In this way I then take the big long singular string full of all the entries in the array (in order with the \n) and do setText(string). That way, the TextView is supposed to display a 2d grid on the display. It sort-of does this: the top row and the bottom row are both fine, but every row in between there are missing spaces between the end character in the row, and somewhere (approximately 13 characters) from the left side. Here is the code snippets from making the array, filling it with characters, and making that array into a long string: for(int row = 0; row < 22; row++){ for(int column = 0; column < 22; column++){ if(row == 0 || row == 21){ playField[row][column] = "#"; }else if(row > 0 && row < 21 ){ if(column == 0 || column == 21){ playField[row][column] = "#"; }else{ playField[row][column] = " "; } } } Now, the turning the array into a string: temp = new String(); for(int i = 0; i < 22; i++){ for(int j = 0; j < 22; j++){ temp+=playField[i][j]; } temp+="\n"; }return temp; This string is what I use text.setText(temp) on, and it works, but it goes like this: # in column 1, about 10 blank spaces (as intended) then another # in column 13 or so, and then next row. On the top row, there are all 22 # signs, and on the bottom row there are all 22 # signs. I have my textView set as such in the xml: <TextView android:id="@+id/grid" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"/> A: I think the problem is that you didn't declared your TextView to use the monospace typeface, so all the spaces are there, but they are not as wide as the # symbol. You can specify the typeface of the TextView like this: android:typeface="monospace"
{ "pile_set_name": "StackExchange" }
Q: php - ucwords function is not working like intended Here is my code: $column5 = array( 'london-airport', 'newyork-airport', 'paris-airport', 'barcelona-international-airport' ); foreach ($column5 as $airport) { $btitle = str_replace("-", " ", $airport); $title = ucwords($btitle); echo '<h3>'.$title.'</h3>'; } This will output "london airport" instead of "London Airport". I want it to display the second way. I also tried: $btitle = str_replace(strtolower("-", " ", $airport)); $btitle = str_replace(strtolower(trim("-", " ", $airport))); $btitle = str_replace(trim("-", " ", $airport)); But without success, any suggestions? A: The code is right, it worked for me. Also, ucwords was introduced in PHP 4 so will not work in order version if in case yours is. http://php.net/manual/en/function.ucwords.php
{ "pile_set_name": "StackExchange" }
Q: Is "breath of life" in Genesis 2:7 is the same as spirit? And the Lord God formed man of the dust of the ground, and breathed into his nostrils the breath of life; and man became a living soul. Genesis 2:7 (KJV) What is the meaning of "breath of life" here? Is there any relation between spirit of man? A: The phrase in Hebrew is נִשְׁמַת חַיִּים (nishmat chayyim). The Hebrew word typically translated as "spirit" in English is רוּחַ (ruach). Here is a link to a Jewish understanding of the distinctions between neshamah, nefesh, and ruach. However, it is my belief that neshamah and ruach are probably equivalent to one another. For example, in Genesis 2:7, it is said that God inspired into man the נִשְׁמַת חַיִּים (nishmat chayyim), or "breath of life" (A.V.). Later on in Genesis 7:21-22, where the narrative is speaking about all those who died on the face of the earth in the flood (viz. "And all flesh died that moved upon the earth, both of fowl, and of cattle, and of beast, and of every creeping thing that creepeth upon the earth, and every man..."), regarding them it says, "...all in whose nostrils was the breath of life..." (A.V.). Here, the phrase "breath of life" is translated from the Hebrew phrase נִשְׁמַת־רוּחַ חַיִּים (nishmat ruach chayyim), which is like saying "the nishmah of the ruach chayyim." Grammatically, I would understand this phrase as nishmat being in apposition (genitive of apposition) to ruach chayyim, and thus meaning, "the nishmah, that is to say, the ruach chayyim." In summary, it seems as though they are equivalent. @Fraser Orr: Yes. That would be prefential. But, you could still read it as: nishmat, that is to say ruach, chayyim. A better view of the appositive: 2 Sam. 22:16; Psa. 18:15 In parallelism: Job 4:9, 33:4; Isa. 42:5 With epexegetical vav: Job 34:14
{ "pile_set_name": "StackExchange" }
Q: select everything from a table for a column in my mysql database i have the following tables: FACULTY (fid int, fname varchar(25), deptid int, primary key(fid)) CLASS (name varchar(4),meets_at varchar(9),room varchar(4), fid int,primary key (name), foreign key (fid) references faculty (fid)) I want to select the names of faculties who go to all the rooms. I tried using following : SELECT DISTINCT F.FNAME FROM FACULTY F WHERE NOT EXISTS (( SELECT * FROM CLASS C EXCEPT (SELECT C1.ROOM FROM CLASS C1 WHERE C1.FID=F.FID))); and got the following error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EXCEPT also tried with: SELECT DISTINCT F.FNAME FROM FACULTY F LEFT JOIN CLASS C ON C.FID = F.FID WHERE C.FID IS NULL and got "Empty Set" even when in my database there is a faculty who goes to all the rooms. A: When you use except the two table must be compatible, try this : SELECT DISTINCT F.FNAME FROM FACULTY F WHERE NOT EXISTS ( ( SELECT ROOM FROM CLASS C) EXCEPT (SELECT C1.ROOM FROM CLASS C1 WHERE C1.FID=F.FID) ); EDIT The question was tagged to sql server so I gave the answer keeping that in mind, for mysql use this : SELECT FID, COUNT(*) FROM ( (SELECT DISTINCT f.fname, f.fid, c1.room FROM faculty f JOIN class c1 ON f.fid = c1.fid) tb1 JOIN (SELECT DISTINCT room AS room2 FROM class) tb2 ON tb1.room = tb2.room2 ) GROUP BY FID HAVING COUNT(*) IN (SELECT COUNT(DISTINCT Room) FROM Class); fiddle:http://sqlfiddle.com/#!8/cff12/4
{ "pile_set_name": "StackExchange" }
Q: List row characters of a table I have the following data and would like to count each of them and put it in another column. Input: col1 col2 col3 col4 A a a a a B a c c c C a b b c D a - b c E b - b c So the output looks something like: col1 col2 col3 col4 count A a a a a a B a c c c a,c C a b b c a,b,c D a - b c a,b,c,- E b - b c b,c,- A: One solution is to use apply dt$count <- apply(dt,1,function(x)I(unique(x))) col1 col2 col3 col4 count A a a a a a B a c c c a, c C a b b c a, b, c D a - b c a, -, b, c E b - b c b, -, c Maybe better output if you sort your result, But not exactly the desired one: dt$count <- apply(dt,1,function(x)I(sort(unique(x)))) col1 col2 col3 col4 count A a a a a a B a c c c a, c C a b b c a, b, c D a - b c -, a, b, c E b - b c -, b, c
{ "pile_set_name": "StackExchange" }