text
stringlengths
64
81.1k
meta
dict
Q: Spyne - how to duplicate one elements of wsdl file created by spyne? I need to duplicate one of the elements of generated wsdl file. My code is like this: class SDPSimulator(ServiceBase): @rpc(UserCredential, Unicode, Unicode, Unicode, Integer, _returns=SendSmsReturn.customize(sub_name='return')) def sendSms(ctx, userCredential, srcAddress, regionIds,msgBody,maxSendCount): I want to create my request wsdl file like this with Spyne: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loc="localhost" xmlns:apps="apps.simulator.views"> <soapenv:Header/> <soapenv:Body> <loc:sendSms> <!--Optional:--> <loc:userCredential> <!--Optional:--> <apps:password>test</apps:password> <!--Optional:--> <apps:username>test</apps:username> </loc:userCredential> <!--Optional:--> <loc:srcAddress>982156898</loc:srcAddress> <!--Optional:--> <loc:regionIds>77</loc:regionIds> <loc:regionIds>78</loc:regionIds> <loc:regionIds>79</loc:regionIds> <!--Optional:--> <loc:msgBody>Hi there</loc:msgBody> <!--Optional:--> <loc:maxSendCount>12</loc:maxSendCount> </loc:sendSms> </soapenv:Body> </soapenv:Envelope> How can I write my code to duplicate regionIds in wsdl file and send a request like above? A: I finally find it :) To do so I have to write my code like this: class SDPSimulator(ServiceBase): @rpc(UserCredential, Unicode, Unicode.customize(max_occurs='unbounded'), Unicode, Integer, _returns=SendSmsReturn.customize(sub_name='return')) def sendSms(ctx, userCredential, srcAddress, regionIds, msgBody, maxSendCount): With this part of code: Unicode.customize(max_occurs=50) I can specify how many times <regionIds></regionIds> could be duplicated.
{ "pile_set_name": "StackExchange" }
Q: Cambiar color de una fila de una tabla php dependiendo de una palabra espero me puedan ayudar nuevamente. tengo mi tabla y quiero que cuando aparezca la palabra MALO me marque la fila con algún COLOR . ADJUNTO imagen de mi tabla en la web y mi tabla en código espero me sepan entender. GRACIAS ADJUNTO CÓDIGO HA PETICIÓN .... Notebook Nota: Informacion Ingresada Por: Juan González <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Lista de equipos funcionales</a> </h4> </div> <div id="collapse1" class="panel-collapse collapse "> <div class="panel-body"> <center><strong><a>Total Equipos Contados</a></strong> <?php $sql = "SELECT * FROM notebook WHERE estado='1'"; $result = mysql_query($sql); $numero = mysql_num_rows($result); echo '.:: '.$numero.' ::. '; ?></br></br></center> <table border="1" class="table table-hover" style="font-size:11px;width:98%;"> <tr> <th> <center> # </center> </th> <th> <center> numero </center> </th> <th> <center> marca </center> </th> <th> <center> modelo </center> </th> <th> <center> pantalla </center> </th> <th> <center> teclas </center> </th> <th> <center> hdd </center> </th> <th> <center> ram </center> </th> <th> <center> bateria </center> </th> <th> <center> cargador </center> </th> <th> <center> bolso </center> </th> <th> <center> ubicacion </center> </th> <th> <center> tipouso </center> </th> <th> <center> responsable </center> </th> <th> <center> fecharegistro </center> </th> <th> <center> notas </center> </th> <th colspan="2" > <center> Opciones </center> </th> </tr> <?php $consulta = "SELECT * FROM notebook WHERE estado='1'"; $resultado = mysql_query($consulta,$link); while($fila = mysql_fetch_array($resultado)){ ?> <tr> <td><?php $rut = $fila['id']; echo $rut; ?></td> <td><?php echo $fila['numero']; ?></td> <td><?php echo $fila['marca']; ?></td> <td><?php echo $fila['modelo']; ?></td> <td><?php echo $fila['pantalla']; ?></td> <td><?php echo $fila['teclas']; ?></td> <td><?php echo $fila['hdd']; ?></td> <td><?php echo $fila['ram']; ?></td> <td><?php echo $fila['bateria']; ?></td> <td><?php echo $fila['cargador']; ?></td> <td><?php echo $fila['bolso']; ?></td> <td><?php echo $fila['ubicacion']; ?></td> <td><?php echo $fila['tipouso']; ?></td> <td><?php echo $fila['responsable']; ?></td> <td><?php echo $fila['fecharegistro']; ?></td> <td><?php echo $fila['notas']; ?></td> <td> <a href="#?rut=<?php echo $rut; ?>" title="Editar"> Editar </a> </td> <td> <a href="eliminar_notebook.php?rut=<?php echo $rut; ?>" title="Eliminar"> Eliminar</a> </td> </tr> <?php } ?> </table> </li> </ul> </div> </div> </table> A: La condición debes hacerla donde esta el <TD> si quieres pintar una sola celda o el <TR> si quieres pintar la fila entera. Luego tienes que identificar si queres pintar cuando la palabra sea exactamente "MALO" o que contenga "MALO" por ejemplo "CAMALOTE". Si quieres que sea exactamente solo debes hacer un condicional de igual, por ejemplo if ( "MALO" === $variable ). Si quieres que contenga la palabra "MALO" debes hacer un condicional con la propiedad strrpos que te ayuda a buscar la posicion de un elemento en el cuerpo. Por ejemplo: if ( strrpos( $varialbe, "MALO" ) !== false ) {.
{ "pile_set_name": "StackExchange" }
Q: Making token accessible to other views after being set in class I have an angular 2 project where I want to make an api call and grab a token. Then I want to set the token in a property within that class. I want to then be able to grab that token from other parts of my app. This may be a simple question, but once I set that property, is it always available to other classes as someone goes from view-to-view? A: You can create a shared service (class, that you are referring) and then Set a value of token to some class property. Provide service in AppModule Inject the service in all the components, where you want to access the service property. Access service property in component view using service object created during DI. DEMO
{ "pile_set_name": "StackExchange" }
Q: Error with passing json constructed data and receiving xmldocument as output I have the following ajax call to webservice to pass json data and get response xml data, when i debug the code the flow is not reaching the webservice var keyword2 = "{\"keyword1\":\"" + keyword1 + "\",\"streetname\":\"" + address1 + "\",\"lat\":\"" + lat + "\",\"lng\":\"" + lng + "\",\"radius\":\"" + radius + "\"}"; $.ajax({ type: "POST", async: false, url: "/blockseek3-9-2010/JsonWebService.asmx/GetList", data: keyword2, contentType: "application/json; charset=utf-8", dataType: "json", failure: ajaxCallFailed, success: function(response) { GDownloadUrl(response, function(data) { var xml = GXml.parse(response.xml); var markers = xml.documentElement.getElementsByTagName('marker'); map.clearOverlays(); var sidebar = document.getElementById('sidebar'); sidebar.innerHTML = ''; alert(markers.length); if (markers.length == 0) { sidebar.innerHTML = 'No results found.'; map.setCenter(new GLatLng(40, -100), 4); return; } var bounds = new GLatLngBounds(); for (var i = 0; i < markers.length; i++) { var name = markers[i].getAttribute('name'); var address = markers[i].getAttribute('address'); var distance = parseFloat(markers[i].getAttribute('distance')); var point = new GLatLng(parseFloat(markers[i] .getAttribute('lat')), parseFloat(markers[i] .getAttribute('lng'))); var imagepath = markers[i].getAttribute('imagepath'); var marker = createMarker(point, name, address, imagepath); map.addOverlay(marker); var sidebarEntry = createSidebarEntry(marker, name, address, distance, imagepath); sidebar.appendChild(sidebarEntry); bounds.extend(point); } map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); }); } }); }); This will be my code snippet on webservice side [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public XmlDocument GetList(string keyword1, string streetname, string lat, string lng, string radius) { XmlDocument xmlDoc= CreateXML( keyword1,streetname,lat,lng,radius); //save file to application folder which will be refferd by client application xmlDoc.Save(@"D:\blockseek3-9-2010\Block3.xml"); return xmlDoc; } A: Two things. Are you sure that the URL /blockseek3-9-2010/JsonWebService.asmx/GetList is correct, this is relative to the page that the Ajax call is being made from. What is the full URL to the page running this query? Your WebMethod has specified a Json response format [ScriptMethod(ResponseFormat = ResponseFormat.Json)] but in the Javascript code you are accessing response.xml which will be undefined for a Json object. By your description, I think you need to change the WebMthod to [ScriptMethod(ResponseFormat = ResponseFormat.Xml)], you can still use Json to invoke the WebMethod from the client side. Note: Point 2 is not related to why you can't call the web service, this point relates to an issue you will face once you resolve the core issue of not actually hitting the WebMethod.
{ "pile_set_name": "StackExchange" }
Q: name of elliptic pde with a power law nonlinearity Consider an equation like $$-\Delta u = |u|^p u $$ in $\Omega$ with $u=0$ on $ \partial \Omega$ where $\Omega$ a domain in $ R^N$ and $ u:\Omega \rightarrow R^N$. Here $p$ is arbitrary or maybe $p=2$. Or consider Neumann problems like this with a zero order term $u$ added to the left. Do these equations have a name? (I am interested in what kind of results are known and I have no clue what to google). thank you very much. A: The case $p=2$ is the nonlinear Schrödinger equation, more generally written as $$Eu=-\Delta u+\kappa|u|^2 u,$$ with coefficients $E,\kappa\in\mathbb R$. It describes the propagation of light in nonlinear optical fibers and is also a model for a superfluid. In the one-dimensional case the equation can be solved exactly for $\kappa<0$. It supports socalled "soliton" solutions, localized in space. As written the differential equation applies to harmonic solutions $\propto e^{-iEt}$ in the time domain; alternatively, consider functions of both space and time and replace the left-hand-side of the equation by $i\partial u/\partial t$. Generalizations with $p$ an even integer are also studied in this context, see for example Schrödinger equation with a power-law nonlinearity.
{ "pile_set_name": "StackExchange" }
Q: SELECT statement subquery EDIT: I need the overall total in there subtracting both direct and indirect minutes. I'm trying to SUM M. Minutes as an alias "dminutes". Then, take the SUM of M.minutes again and subtract M.minutes that have "indirect" column value (and give it "inminutes" alias). However, it's showing me null, so the syntax is wrong. Suggestions? table = tasks column = task_type Example: M.minutes total = 60 minutes M. minutes (with "direct" task_type column value) = 50 minutes (AS dminutes) M. minutes (with "indirect" task_type column value) = 10 minutes (AS inminutes) SQL statement: SELECT U.user_name, SUM(M.minutes) as dminutes, ROUND(SUM(M.minutes))-(SELECT (SUM(M.minutes)) from summary s WHERE ta.task_type='indirect') as inminutes FROM summary S JOIN users U ON U.user_id = S.user_id JOIN tasks TA ON TA.task_id = S.task_id JOIN minutes M ON M.minutes_id = S.minutes_id WHERE DATE(submit_date) = curdate() AND TIME(submit_date) BETWEEN '00:00:01' and '23:59:59' GROUP BY U.user_name LIMIT 0 , 30 A: I think something like this should work. You might have to tweak it a little. SELECT direct.duser_id, indirect.iminutes, direct.dminutes, direct.dminutes - indirect.iminutes FROM (SELECT U.user_id AS iuser_id, SUM(M.minutes) AS iminutes FROM summary S JOIN users U ON U.user_id = S.user_id JOIN minutes M ON M.minutes_id = S.minutes_id JOIN tasks TA ON TA.task_id = S.task_id WHERE TA.task_type='indirect' AND DATE(submit_date) = curdate() AND TIME(submit_date) BETWEEN '00:00:01' and '23:59:59' GROUP BY U.user_id) AS indirect JOIN (SELECT U.user_id AS duser_id, SUM(M.minutes) AS dminutes FROM summary S JOIN users U ON U.user_id = S.user_id JOIN minutes M ON M.minutes_id = S.minutes_id JOIN tasks TA ON TA.task_id = S.task_id WHERE TA.task_type='direct' AND DATE(submit_date) = curdate() AND TIME(submit_date) BETWEEN '00:00:01' and '23:59:59' GROUP BY U.user_id) AS direct WHERE indirect.iuser_id = direct.duser_id
{ "pile_set_name": "StackExchange" }
Q: Android : How to change Playback Rate of music using OpenSL ES I am working on a music player in which I need to change tempo (playback speed of music) without changing the pitch. I'm not able to find any native android class to do so. I tried SoundPool but it doesn't work with large music files and it also doesn't seems to work on many devices. I also tried AudioTrack but again no luck. Now I am trying android NDK audio example which use OpenSL ES to handle music. Now I just want to add set playback rate feature in this example. Can anyone show me how do I add change playback rate function in it? A: I have solved my problem. Here is my complete native code for OpenSL ES in case of anybody need this : #include <jni.h> #include<android/log.h> // LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog 넣어주세요 #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "OSLESMediaPlayer", __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "OSLESMediaPlayer", __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO , "OSLESMediaPlayer", __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN , "OSLESMediaPlayer", __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , "OSLESMediaPlayer", __VA_ARGS__) // for native audio #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include <assert.h> #include <sys/types.h> // engine interfaces static SLObjectItf engineObject = NULL; static SLEngineItf engineEngine; // URI player interfaces static SLObjectItf uriPlayerObject = NULL; static SLPlayItf uriPlayerPlay; static SLSeekItf uriPlayerSeek; static SLPlaybackRateItf uriPlaybackRate; // output mix interfaces static SLObjectItf outputMixObject = NULL; // playback rate (default 1x:1000) static SLpermille playbackMinRate = 500; static SLpermille playbackMaxRate = 2000; static SLpermille playbackRateStepSize; //Pitch static SLPitchItf uriPlaybackPitch; static SLpermille playbackMinPitch = 500; static SLpermille playbackMaxPitch = 2000; // create the engine and output mix objects JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_createEngine( JNIEnv* env, jclass clazz) { SLresult result; // create engine LOGD("create engine"); result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); // realize the engine LOGD("realize the engine"); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // get the engine interface, which is needed in order to create other objects LOGD("get the engine interface"); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix, with environmental reverb specified as a non-required interface LOGD("create output mix"); const SLInterfaceID ids[1] = {SL_IID_PLAYBACKRATE}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); assert(SL_RESULT_SUCCESS == result); // realize the output mix LOGD("realize the output mix"); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); } JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_releaseEngine( JNIEnv* env, jclass clazz) { // destroy URI audio player object, and invalidate all associated interfaces if (uriPlayerObject != NULL) { (*uriPlayerObject)->Destroy(uriPlayerObject); uriPlayerObject = NULL; uriPlayerPlay = NULL; uriPlayerSeek = NULL; } // destroy output mix object, and invalidate all associated interfaces if (outputMixObject != NULL) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = NULL; } // destroy engine object, and invalidate all associated interfaces if (engineObject != NULL) { (*engineObject)->Destroy(engineObject); engineObject = NULL; engineEngine = NULL; } } /* void OnCompletion(JNIEnv* env, jclass clazz) { jclass cls = env->GetObjectClass(thiz); if (cls != NULL) { jmethodID mid = env->GetMethodID(cls, "OnCompletion", "()V"); if (mid != NULL) { env->CallVoidMethod(thiz, mid, 1234); } } }*/ void playStatusCallback(SLPlayItf play, void* context, SLuint32 event) { //LOGD("playStatusCallback"); } // create URI audio player JNIEXPORT jboolean Java_com_swssm_waveloop_audio_OSLESMediaPlayer_createAudioPlayer( JNIEnv* env, jclass clazz, jstring uri) { SLresult result; // convert Java string to UTF-8 const jbyte *utf8 = (*env)->GetStringUTFChars(env, uri, NULL); assert(NULL != utf8); // configure audio source // (requires the INTERNET permission depending on the uri parameter) SLDataLocator_URI loc_uri = { SL_DATALOCATOR_URI, (SLchar *) utf8 }; SLDataFormat_MIME format_mime = { SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED }; SLDataSource audioSrc = { &loc_uri, &format_mime }; // configure audio sink SLDataLocator_OutputMix loc_outmix = { SL_DATALOCATOR_OUTPUTMIX, outputMixObject }; SLDataSink audioSnk = { &loc_outmix, NULL }; // create audio player const SLInterfaceID ids[2] = { SL_IID_SEEK, SL_IID_PLAYBACKRATE }; const SLboolean req[2] = { SL_BOOLEAN_FALSE, SL_BOOLEAN_TRUE }; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &uriPlayerObject, &audioSrc, &audioSnk, 2, ids, req); // note that an invalid URI is not detected here, but during prepare/prefetch on Android, // or possibly during Realize on other platforms assert(SL_RESULT_SUCCESS == result); // release the Java string and UTF-8 (*env)->ReleaseStringUTFChars(env, uri, utf8); // realize the player result = (*uriPlayerObject)->Realize(uriPlayerObject, SL_BOOLEAN_FALSE); // this will always succeed on Android, but we check result for portability to other platforms if (SL_RESULT_SUCCESS != result) { (*uriPlayerObject)->Destroy(uriPlayerObject); uriPlayerObject = NULL; return JNI_FALSE; } // get the play interface result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_PLAY, &uriPlayerPlay); assert(SL_RESULT_SUCCESS == result); // get the seek interface result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_SEEK, &uriPlayerSeek); assert(SL_RESULT_SUCCESS == result); // get playback rate interface result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_PLAYBACKRATE, &uriPlaybackRate); assert(SL_RESULT_SUCCESS == result); /* // get playback pitch interface result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_PITCH, &uriPlaybackPitch); assert(SL_RESULT_SUCCESS == result);*/ // register callback function result = (*uriPlayerPlay)->RegisterCallback(uriPlayerPlay, playStatusCallback, 0); assert(SL_RESULT_SUCCESS == result); result = (*uriPlayerPlay)->SetCallbackEventsMask(uriPlayerPlay, SL_PLAYEVENT_HEADATEND); // head at end assert(SL_RESULT_SUCCESS == result); SLmillisecond msec; result = (*uriPlayerPlay)->GetDuration(uriPlayerPlay, &msec); assert(SL_RESULT_SUCCESS == result); // no loop result = (*uriPlayerSeek)->SetLoop(uriPlayerSeek, SL_BOOLEAN_TRUE, 0, msec); assert(SL_RESULT_SUCCESS == result); SLuint32 capa; result = (*uriPlaybackRate)->GetRateRange(uriPlaybackRate, 0, &playbackMinRate, &playbackMaxRate, &playbackRateStepSize, &capa); assert(SL_RESULT_SUCCESS == result); result = (*uriPlaybackRate)->SetPropertyConstraints(uriPlaybackRate, SL_RATEPROP_PITCHCORAUDIO); if (SL_RESULT_PARAMETER_INVALID == result) { LOGD("Parameter Invalid"); } if (SL_RESULT_FEATURE_UNSUPPORTED == result) { LOGD("Feature Unsupported"); } if (SL_RESULT_SUCCESS == result) { assert(SL_RESULT_SUCCESS == result); LOGD("Success"); } /* result = (*uriPlaybackPitch)->GetPitchCapabilities(uriPlaybackPitch, &playbackMinPitch, &playbackMaxPitch); assert(SL_RESULT_SUCCESS == result);*/ /* SLpermille minRate, maxRate, stepSize, rate = 1000; SLuint32 capa; (*uriPlaybackRate)->GetRateRange(uriPlaybackRate, 0, &minRate, &maxRate, &stepSize, &capa); (*uriPlaybackRate)->SetRate(uriPlaybackRate, minRate); */ return JNI_TRUE; } JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_releaseAudioPlayer( JNIEnv* env, jclass clazz) { // destroy URI audio player object, and invalidate all associated interfaces if (uriPlayerObject != NULL) { (*uriPlayerObject)->Destroy(uriPlayerObject); uriPlayerObject = NULL; uriPlayerPlay = NULL; uriPlayerSeek = NULL; uriPlaybackRate = NULL; } } void setPlayState(SLuint32 state) { SLresult result; // make sure the URI audio player was created if (NULL != uriPlayerPlay) { // set the player's state result = (*uriPlayerPlay)->SetPlayState(uriPlayerPlay, state); assert(SL_RESULT_SUCCESS == result); } } SLuint32 getPlayState() { SLresult result; // make sure the URI audio player was created if (NULL != uriPlayerPlay) { SLuint32 state; result = (*uriPlayerPlay)->GetPlayState(uriPlayerPlay, &state); assert(SL_RESULT_SUCCESS == result); return state; } return 0; } // play JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_play(JNIEnv* env, jclass clazz) { setPlayState(SL_PLAYSTATE_PLAYING); } // stop JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_stop(JNIEnv* env, jclass clazz) { setPlayState(SL_PLAYSTATE_STOPPED); } // pause JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_pause(JNIEnv* env, jclass clazz) { setPlayState(SL_PLAYSTATE_PAUSED); } // pause JNIEXPORT jboolean Java_com_swssm_waveloop_audio_OSLESMediaPlayer_isPlaying( JNIEnv* env, jclass clazz) { return (getPlayState() == SL_PLAYSTATE_PLAYING); } // set position JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_seekTo( JNIEnv* env, jclass clazz, jint position) { if (NULL != uriPlayerPlay) { //SLuint32 state = getPlayState(); //setPlayState(SL_PLAYSTATE_PAUSED); SLresult result; result = (*uriPlayerSeek)->SetPosition(uriPlayerSeek, position, SL_SEEKMODE_FAST); assert(SL_RESULT_SUCCESS == result); //setPlayState(state); } } // get duration JNIEXPORT jint Java_com_swssm_waveloop_audio_OSLESMediaPlayer_getDuration( JNIEnv* env, jclass clazz) { if (NULL != uriPlayerPlay) { SLresult result; SLmillisecond msec; result = (*uriPlayerPlay)->GetDuration(uriPlayerPlay, &msec); assert(SL_RESULT_SUCCESS == result); return msec; } return 0.0f; } // get current position JNIEXPORT jint Java_com_swssm_waveloop_audio_OSLESMediaPlayer_getPosition( JNIEnv* env, jclass clazz) { if (NULL != uriPlayerPlay) { SLresult result; SLmillisecond msec; result = (*uriPlayerPlay)->GetPosition(uriPlayerPlay, &msec); assert(SL_RESULT_SUCCESS == result); return msec; } return 0.0f; } //llllllllllllllllllll JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_setPitch( JNIEnv* env, jclass clazz, jint rate) { if (NULL != uriPlaybackPitch) { SLresult result; result = (*uriPlaybackPitch)->SetPitch(uriPlaybackPitch, rate); assert(SL_RESULT_SUCCESS == result); } } JNIEXPORT void Java_com_swssm_waveloop_audio_OSLESMediaPlayer_setRate( JNIEnv* env, jclass clazz, jint rate) { if (NULL != uriPlaybackRate) { SLresult result; result = (*uriPlaybackRate)->SetRate(uriPlaybackRate, rate); assert(SL_RESULT_SUCCESS == result); } } JNIEXPORT jint Java_com_swssm_waveloop_audio_OSLESMediaPlayer_getRate( JNIEnv* env, jclass clazz) { if (NULL != uriPlaybackRate) { SLresult result; SLpermille rate; result = (*uriPlaybackRate)->GetRate(uriPlaybackRate, &rate); assert(SL_RESULT_SUCCESS == result); return rate; } return 0; } // create URI audio player JNIEXPORT jboolean Java_com_swssm_waveloop_audio_OSLESMediaPlayer_setLoop( JNIEnv* env, jclass clazz, jint startPos, jint endPos) { SLresult result; result = (*uriPlayerSeek)->SetLoop(uriPlayerSeek, SL_BOOLEAN_TRUE, startPos, endPos); assert(SL_RESULT_SUCCESS == result); return JNI_TRUE; } // create URI audio player JNIEXPORT jboolean Java_com_swssm_waveloop_audio_OSLESMediaPlayer_setNoLoop( JNIEnv* env, jclass clazz) { SLresult result; if (NULL != uriPlayerSeek) { // enable whole file looping result = (*uriPlayerSeek)->SetLoop(uriPlayerSeek, SL_BOOLEAN_TRUE, 0, SL_TIME_UNKNOWN); assert(SL_RESULT_SUCCESS == result); } return JNI_TRUE; } Just compile it using ndk-build command and use it. If anybody get success in changing pitch then please tell me the solution. Here is android.mk file LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := audio-tools LOCAL_SRC_FILES := OSLESMediaPlayer.c LOCAL_CFLAGS := -DHAVE_CONFIG_H -DFPM_ARM -ffast-math -O3 LOCAL_LDLIBS += -lOpenSLES -llog include $(BUILD_SHARED_LIBRARY) and Application.mk file APP_STL := gnustl_static APP_CPPFLAGS += -fexceptions -frtti APP_ABI := armeabi armeabi-v7a And wrapper class, you can use its function directly in your project package com.swssm.waveloop.audio; public class OSLESMediaPlayer { public native void createEngine(); public native void releaseEngine(); public native boolean createAudioPlayer(String uri); public native void releaseAudioPlayer(); public native void play(); public native void stop(); public native void pause(); public native boolean isPlaying(); public native void seekTo(int position); public native int getDuration(); public native int getPosition(); public native void setPitch(int rate); public native void setRate(int rate); public native int getRate(); public native void setLoop( int startPos, int endPos ); public native void setNoLoop(); public interface OnCompletionListener { public void OnCompletion(); } private OnCompletionListener mCompletionListener; public void SetOnCompletionListener( OnCompletionListener listener ) { mCompletionListener = listener; } private void OnCompletion() { mCompletionListener.OnCompletion(); int position = getPosition(); int duration = getDuration(); if( position != duration ) { int a = 0; } else { int c = 0; } } } A: This may be of some help (taken from the NDK OpenSL documentation): Playback rate The supported playback rate range(s) and capabilities may vary depending on the platform version and implementation, and so should be determined at runtime by querying with PlaybackRate::GetRateRange or PlaybackRate::GetCapabilitiesOfRate. That said, some guidance on typical rate ranges may be useful: In Android 2.3 a single playback rate range from 500 per mille to 2000 per mille inclusive is typically supported, with property SL_RATEPROP_NOPITCHCORAUDIO. In Android 4.0 the same rate range is typically supported for a data source in PCM format, and a unity rate range for other formats.
{ "pile_set_name": "StackExchange" }
Q: What are the dos and don'ts related to massaging an infant? I was thinking of giving him a strong head massage, but then I read somewhere that newborn heads are not supposed to be touched strongly since bones aren't joint at the back of the head. What are the dos and don'ts related to massaging an infant? How to hold the infant and how much pressure should be applied where? If I put him on his tummy for back massage, he won't be to support his neck and his nose will be buried in the mattress. What's the way out? A: Until the age of two the bone plates in his skull won't be fused, so yes, head massage that might move the bones would be a bad idea. Maybe just a very gentle scalp massage instead? As for back massage, just turn his head to the side so he can breathe freely. Infant massage can be beneficial for everyone, so long as you move slowly, respond to his cues (if he doesn't like it, he will let you (and everyone within earshot) know :) ), and look at it as a bonding opportunity. Most hospitals in the US (don't know your location, so I'm going by mine :> ) offer classes in infant massage. Here's some basic info from the Mayo Clinic on infant massage.
{ "pile_set_name": "StackExchange" }
Q: Confused about WdPasteOptions enumeration in Word VBA I am using Word 2013. The WdPasteOptions enumeration contains the following: wdKeepSourceFormatting 0 Keeps formatting from the source document. wdMatchDestinationFormatting 1 Matches formatting to the destination document. wdKeepTextOnly 2 Keeps text only, without formatting. wdUseDestinationStyles 3 Matches formatting to the destination document using styles for formatting. These are used for the four paste options: PasteFormatWithinDocument PasteFormatBetweenDocuments PasteFormatBetweenStyledDocuments PasteFormatFromExternalSource The dialog in Word includes an choice of "Merge Formatting" for all four options, but there is nothing in the enumeration whose name matches this. Upon inspection, the "Merge Formatting" choice has a value of 1, corresponding to wdMatchDestinationFormatting. The simplest explanation would be that what Word now calls "Merge Formatting" used to be "Match Destination Formatting." A less plausible explanation is that Word changed the options so that "Merge Formatting" not only has a different name but behaves differently from "Match Destination Formatting." Does anyone know whether these two refer to the same functionality or different functionality? A: No one not from Microsoft can say for certain, but... As far as I know, "Merge Formatting" would be the same as matching destination formatting. This is Word's original, design default in order to make it easier to seemlessly combine documents from different sources into one "coherent" document. FWIW I have my doubts whether those four object model enumerations exactly match the UI commands. I think you also need to throw the Paste Special options into the mix to get closer to the full spectrum. The object model commands are written before the Word UI is finalized for the version in which things are introduced - so commands in the UI may well not match the name of the corresponding part of the object model. In addition, Microsoft may decide to change the caption of a command in the UI at a later point. For reasons of backwards compatibility the name of the corresponding part of the object model will not be changed. This means tha code which worked in earlier versions will continue to run in newer versions.
{ "pile_set_name": "StackExchange" }
Q: How to open a browser with a url from maven build I'm building a web-application with Maven3 and run it via mvn jetty:run-war. Now I'd like to open the web-app from my maven build in the system browser. A: I solved my problem on os windows, which is currently my only build system. After the jetty server is started and hosting my web-app the build makes a start call via antrun: <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>Run URL in system browser.</id> <phase>install</phase> <configuration> <target> <exec executable="start" vmlauncher="false"> <arg line="http://localhost:8080/rap?startup=entrypoint"/> </exec> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin>
{ "pile_set_name": "StackExchange" }
Q: Does this inequality hold? proof or counterexample Does the following inequality $$ \sup_{x\in (0,1)}u^2(x)\leq C_1\int_0^1 x u^2(x)\,\textrm{d}x+C_2\int_0^1 x(u')^2(x)\,\textrm{d}x $$ hold for all $ u\in C^1(0,1)$? If so please give me a proof, and a counterexample if not. Thanks. A: Consider the family of functions $$ \phi_\epsilon(x) = 1- x^\epsilon $$ for $\epsilon \in (0,1/4)$. Clearly these functions are in $C^1(0,1)$, and $\sup \phi_\epsilon^2 = 1$ for every $\epsilon$. Compute $$ \int_0^1 x (1-x^\epsilon)^2 \mathrm{d}x = \int_0^1 x - 2 x^{1+\epsilon} + x^{1+2\epsilon} \mathrm{d}x = \frac12 - \frac{2}{2+\epsilon} + \frac{1}{2+2\epsilon} = \frac{\epsilon^2}{(2\epsilon + 2)(\epsilon + 2)} $$ and $$ \int_0^1 x (-\epsilon x^{\epsilon -1})^2 \mathrm{d}x = \epsilon^2 \int_0^1 x^{2\epsilon - 1}\mathrm{d}x = \frac{\epsilon^2}{2\epsilon} $$ Hence we have that the RHS is order $O(\epsilon)$ while the left hand side is order 1 for this family of functions, hence the desired uniform bound cannot be achieved. Another way to see the obstruction is to take the change of variables $y = \log x$. Then your inequality becomes equivalent to $$\sup_{y\in (-\infty,0)} v^2 \lesssim \int_{-\infty}^0 e^{2y} v(y)^2 \mathrm{d}y + \int_{-\infty}^0 (v'(y))^2 \mathrm{d}y$$ This is clearly false by taking $\psi(y)$ a smooth function such that $\psi |_{y < -5} = 1$ and $\psi |_{y > -3} = 0$ and considering the family $\psi_\lambda(y) = \psi(y/\lambda)$ as $\lambda \to \infty$. (Note that the scaling in $y$ is equivalent to raising to a power in $x$.)
{ "pile_set_name": "StackExchange" }
Q: In OS X, is it better to put apps in /Applications or in ~/Applications? I've noticed that pkg installers and obviously apps installed from the App Store) put apps in the /Applications file, yet Steam usually puts them in ~/Applications. Both work, and both are writable by the user, but are there circumstances under which one should be done over the other? I am the only user of this computer, and shared folders aside, I've disabled guest access. (this is coming from a Linux user, so having a root folder be writable seems wrong, unless my permissions are wrong from the start) A: What no-one seems to have pointed out so far is that /Applications are usable by everybody & ~/Applications are only for that user. Some installers will ask if you want to install for this user or for everybody. That's how it can differentiate. That will be one of the reasons Steam installs to there, as it's a per user license. Apple's app licensing, though 'per ID' doesn't prevent all a machine's users from accessing apps purchased under another user account, so everything else usually goes in /Applications by default. Of course, if you're the machine's sole user, the distinction becomes moot. A: By default the root directory should not be directly writable, by other then root, without being prompt for permission with other users in Finder and or using sudo from the command line. IMO /Applications should be used over ~/Applications for most applications as that is the default location. Also I certainly do not want to bloat out my Home folder with applications. I like keeping User Data separate from the OS and Applications, it just makes logical sense for many reasons.
{ "pile_set_name": "StackExchange" }
Q: Verilog Syntax Error with endmodule I've been stuck here for a day. I use edaplayground for running this code but I don't khow what's wrong with my it. It says syntax error in the last line where I wrote endmodule, please help. module lifo #(parameter n=4,w=4) ( input insert ,clk,output isEmpety,isfull,error,inout [w-1:0]data); logic h=$clog2(n); reg [n-1:0]mem[w-1:0]; reg [h:0]sp; reg [w-1:0]datar; wire [w-1:0] #(0) data=datar; always@* begin if(reset==1) begin assign datar={n{z}}; assign sp={h{1'b0}}; assign isfull=0; assign isEmpety=0; assign error=0; end if(insert==1) begin if(isEmpety==1) begin assign mem[sp]=data; assign isEmpety=0; if(error==1) assign error=0; end else if(isfull==1) begin assign mem[sp]=data; assign error=1; end else begin assign sp=sp+1; assign stack[sp]=data; if(sp=={h{1}}) assign isfull=1; end end if(insert==0) begin if(sp=={h{0}}&&(isEmpety!=1)) begin assign datar=mem[sp]; assign isEmpety=1; end else if(isEmpety==1) begin assign datar=mem[sp]; assign error=1; end else begin assign datar=mem[sp]; if(sp!={h{0}}) assign sp=sp-1; if(error==1) assign error=0; if(isfull==1) assign isfull=0; end end endmodule Thank you for your help. A: Before endmodule include a end your missing the end for always block. and remove the assign keyword in always block. this style of coding is not recommended. i have edited code for you check it out module lifo #(parameter n=4,w=4) ( input insert ,clk,output isEmpety,isfull,error,inout [w-1:0]data); logic h=$clog2(n); reg [n-1:0]mem[w-1:0]; reg [h:0]sp; reg [w-1:0]datar; wire [w-1:0] #(0) data=datar; always@* begin if(reset==1) begin datar={n{z}}; sp={h{1'b0}}; isfull=0; isEmpety=0; error=0; end if(insert==1) begin if(isEmpety==1) begin mem[sp]=data; isEmpety=0; if(error==1) error=0; end else if(isfull==1) begin mem[sp]=data; error=1; end else begin sp=sp+1; stack[sp]=data; if(sp=={h{1}}) isfull=1; end end if(insert==0) begin if(sp=={h{0}}&&(isEmpety!=1)) begin datar=mem[sp]; isEmpety=1; end else if(isEmpety==1) begin datar=mem[sp]; error=1; end else begin datar=mem[sp]; if(sp!={h{0}}) sp=sp-1; if(error==1) error=0; if(isfull==1) isfull=0; end end end endmodule My advice is write code in a proper order and you will able to fine the errors easily.
{ "pile_set_name": "StackExchange" }
Q: How to in C# keep a set number of letters for a string in console writeline Ok so basically I want something like Console.WriteLine( "{0}: {1}/{2}hp {3}/{4}mp {5}", character.Identifier, character.CurrentHealth, character.MaxHealth, character.CurrentMagic, character.MaxMagic, character.Fatigue ); and then have the character.Identifier (which is basically a name) have a set number of letters which it will replace with spaces if needed so that in might print Josh: 20/20hp 20/20mp 3 or J: 20/20hp 20/20mp 3 but the HP and then mp and everything else is always in line. I am aware that its probably one of the {0:} but i couldn't figure out one that works A: The second argument in the {0} notation can give you a fixed width field, so if you wanted the identifier (name) to always be 10 characters long and be left justified, you would use {0,-10} MSDN is a good resource for this kind of question too, if you read the documentation for String.Format it has an example of a fixed width table that might be similar to what you want. Also, as Hogan's answer correctly points out, you would have to append the : to the string outside of the format string if you want it right next to the name. A: You can right pad a string with spaces by using: character.Identifier.PadRight(10); This should give you the format you are after.
{ "pile_set_name": "StackExchange" }
Q: Is there any scriptural reference that women should take bath before preparing the food? In many families, they ask women to take bath before preparing food. Is there any scriptural reference that women should take bath before preparing the food? Note: This is regarding morning food and not other meals like dinner. A: From Vyasa Smriti's Chapter 2: A wife should quit her bed before her lord, cleanse (wash) her person, fold up the beds, and make her house clean and tidy. (20) Then having entered the chamber of Homa (sacrificial fire) she should (first) wash and plaster its floor, and; then the yard of her house, and after that, wash with warm water the vessels of oils, clarified butter, etc., which are used in connection with Agnikaryayas, and keep them in their proper places. (21) Thus having performed her morning (house-hold) duties, arrd pondered over the dishes of different {flavours (to be prepared, that day), and allotment of work to different workers, and the daily expenditure of the household, she should make obeisance to her elders and superiors. (24) Then she should decorate her person with the ornaments given to her by her father-in-law, husband, father, mother, maternal uncle, or relations. (25) Pure in her thought, speech and action, and obedient to the dictates of her lord, she should follow him (in life) like his own shadow, seek his good like a trusted friend, and minister /to his desires like a servant. 26 27) Then having finished cooking, she should report of it to her husband saying, " the rice is cooked." The husband having made offerings therewith to the Vishvadevas, she should first feed the children, and ithen serve out the morning meal to her lord. (28) Now, bathing is a Nitya Karma which is mandatory for everyone. Before eating anything in the morning one must bath first. So, it is obvious that the wife must have bathed once already before she entered the Homa chamber. From this answer we get some relevant verses regarding the importance of bathing in the morning: A person who is not bathed but eats food, that food is as bad as excretion, or, Perpetual impurity is spoken of for all of them, who,- without bathing, offering oblations to the Fire and making gifts, partake of [their] meals'. (Daksha Smriti, Chapter 6) And, thereafter, at some time, she does the cooking. But it is not mentioned in the text that she should bath again before cooking. Now, if it was required then it would have been specifically mentioned. So, the conclusion is that the one bath she has taken in the morning is enough. No more baths are needed. Clarification: My answer is not suggesting that before you eat each time one needs to take bath and that's just absurd and never prescribed in scriptures. In Hinduism the three acts - attending nature's calls, brushing teeth, bathing (in that order) - are collectively called PrAtakritya. And, Hindu scriptures prescribe that after waking up from bed one should complete Pratakritya first before consuming anything (food or water). So, the wife, if she is following Dharmic instructions, must have already taken bath once in the early morning. And, if she had, there is no need for her to bath again before cooking.
{ "pile_set_name": "StackExchange" }
Q: How to get original exception back from std::exception once caught? // Example program #include <iostream> #include <string> #include <stdexcept> void log(const std::exception& e) { try { throw e; } catch (const std::logic_error& e1) { std::cout << "logic_error: " << e1.what() << std::endl; // How to get logic_error back once caught? } catch (const std::exception& e1) { std::cout << "exception: " << e1.what() << std::endl; } } int main() { try { throw std::logic_error("sth wrong"); } catch (const std::exception& e) { log(e); } } I don't want to add more catch clauses is because I want to have a central place to log detailed exception message, it could be very different across different exceptions. Is there a way to narrow down the std::exception to derived exception in the catch clause? A: You can rethrow the original exception in your log method to preserve its original state. This way everything should work as you would expect it. Modified log method looks like this: void log(const std::exception& e) { try { throw; } catch (const std::logic_error& e1) { std::cout << "logic_error: " << e1.what() << std::endl; } catch (const std::exception& e1) { std::cout << "exception: " << e1.what() << std::endl; } } See throw expression for more details on how throw e and throw differs in this example. A: std::exception::what() is virtual. So you don't need to get back the original type to write the logs. You just have to ensure that what() is redefined for your custom exceptions that inherits std::exception. This may become: void log(const std::exception & e) { std::cout << e.what() << std::endl; } A: You might use std::rethrow_exception: void log(std::exception_ptr eptr) { try { if (eptr) { std::rethrow_exception(eptr); } } catch (const std::logic_error& e1) { std::cout << "logic_error: " << e1.what() << std::endl; } catch (const std::exception& e1) { std::cout << "exception: " << e1.what() << std::endl; } } int main() { try { throw std::logic_error("sth wrong"); } catch (const std::exception&) { // or even catch (...) log(std::current_exception()); } }
{ "pile_set_name": "StackExchange" }
Q: codeigniter best practice - multiple models Just a quick question about best practice in MVC development. Let's say that I've got two controllers (cont1, cont2), each of which uses a separate model, model1 & model2. all files are complex, models contain dozens of methods. Say, I finished developing of the first controller and I'm in the middle of work on the second one. I need to create a method in model2 which will be exactly the same as one of methods in model1. It's only a tiny method, to get, for example, a list of categories of some sort. What's the best approach of work - should I duplicate the method and include it in my model2, or should I retrieve it from model1? The reasonable thing to do would be to get it from model1, but I don't know if that would affect the execution time, as it would have to load both models.. I would be grateful for some feedback thanks k A: Loading a second model will not have a noticeable impact on execution time. This is probably the way to go. Also, each model should encapsulate data logic for a specific 'object'. You can think of each model almost like a database table. So you probably do not really want to have the same method in two different places - and if you do, you may want to consider creating a plugin.
{ "pile_set_name": "StackExchange" }
Q: how to use textfied and button to get results from an if else statement how to use if else statement using textfield as an input then use a button to show results, I have tried using the code the bellow ,but it does not allow me to use " if else " condition for second condition , below is my code; int x = Integer.parseInt(jTextField1.getText()); if (x>=120&x<200) {JOptionPane.showMessageDialog(null, "select drum : PPJ upwards")}; if else (x>=230&x<=300); {JOptionPane.showMessageDialog(null,"select drum :RRf Upwards");} else {JOptionPane.showMessageDialog(null,"incorrect entry");} } } A: The correct way to write if else condition is as below if (condition1 && condition2) { } else if (condition3 && condition4) { } else { } And if my assumtions are correct below s how your code should be written as following; int x = Integer.parseInt(jTextField1.getText().toString()); // getText needs to be converted to String before parsing it to int. if (x>=120 && x<200) { //in the if condition you need two && not one & JOptionPane.showMessageDialog(null, "select drum : PPJ upwards");//semicolon should be here }//putting semicolon here is wrong else if (x>=230 && x<=300)//putting semicolon here is also wrong { JOptionPane.showMessageDialog(null,"select drum :RRf Upwards"); } else { JOptionPane.showMessageDialog(null,"incorrect entry"); }
{ "pile_set_name": "StackExchange" }
Q: What is 'Maximal length of created query' in exporting a database I am using phpMyAdmin and I want to export all of the data from the database. Does the property 'Maximal length of created query' affect the amount of data you export? A: No, it doesn't. It does affect the size of the exported file somewhat. The only thing that happens is that it limits the number of inserted rows per INSERT statement. So you end up with more, smaller statements. Here's some info from their wiki: The option 'Maximal length of created query' seems to be undocumented. But experiments has shown that it splits large extended INSERTS so each one is no bigger than the given number of bytes (or characters?). Thus when importing the file, for large tables you avoid the error "Got a packet bigger than 'max_allowed_packet' bytes". See http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html
{ "pile_set_name": "StackExchange" }
Q: MAKEINTRESOURCE returning bad pointers for resource ID's I'm having an issue where the MAKEINTRESOURCE macro always seems to return a bad pointer whenever I pass it my MFC resource ID's. The resource ID's are all listed in Resource.h and they match up with what the ID's are set to in the resource properties. I'm new to MFC so I'm not entirely sure I understand how the resources & their ID's work, but it seems to me that the bad pointers would indicate that my resources aren't being stored in the correct place in memory? This is an old project that I'm trying to add something new to, and I checked anf when I try doing MAKEINTRESOURCE with older resources (that are definitely working, they show up and are functional when I run the application) I also get bad pointers. What could be causing this? edit: the project is using the unicode character set as well, if that makes any difference A: If by "bad pointers" you mean "pointers that don't point to resource objects in memory", then MAKEINTRESOURCE() is working correctly. The thing is that in order to pass either strings or integer IDs using the same function parameter, the Windows API functions make a weird pointer conversion which is detected by the function as a "oh wait, this is not a pointer, it's a resource ID". This is documented behavior. For example, in the documentation for LoadBitmap(), it says: lpBitmapName [in]: A pointer to a null-terminated string that contains the name of the bitmap resource to be loaded. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. The MAKEINTRESOURCE macro can be used to create this value. Creating an invalid pointer by re-interpreting an arbitrary integer value is a legal C++ construct, but dereferencing the invalid pointer is undefined behavior. In this case, the function receiving the argument checks if the high-order word is 0 and if so, uses the low-order word as an integer and never dereferences the pointer. Note: If this feels like a nasty hack, it's because it is a nasty hack.
{ "pile_set_name": "StackExchange" }
Q: JSQMessages feedback customization I'm using JSQMessages (https://github.com/jessesquires/JSQMessagesViewController) to handle chat within my application. I would like to show inside JSQMessages UI if the message was delivered, if the message was read by the other end or if there was a problem in the delivery ( the same functions performed by other chat applications ). How can I customize it to show this information ? My goal is to add a check, a double check or a red exclamation if the message could not be delivered. Any ideas how I can accomplish this using JSQMessages ? Thanks a lot, Daniel A: You can add a status enum in your JSQMessage model class to represent different delivery status flags. and in your JSQMessagesController subclass you can override this method : - (NSAttributedString *)collectionView:(JSQMessagesCollectionView *)collectionView attributedTextForCellBottomLabelAtIndexPath:(NSIndexPath *)indexPath and return an NSAttributedString matching the delivery flag you want to show. Bear in mind that this has nothing to do with the backend. JSQMessages is for UI only so backend work has to be done by you. you can get more information here : https://github.com/jessesquires/JSQMessagesViewController/issues/190
{ "pile_set_name": "StackExchange" }
Q: Password reset question answer complexity I need to implement a password reset feature for a system that will be controlled by a security question and answer pair. The problem is that I can't guarantee I'll have a valid e-mail address or cell number for the account that I can use to communicate a reset link or code. This means the entire process will happen on the web page. I will have a known e-mail address for the user, but it's an address that was issued by the system in the first place, meaning the fact that someone is using this feature at all may imply they no longer have access to that account. In this circumstance, it seems like the security answer effectively becomes an alternative password, in that knowing the Question (I plan on requiring you to select the correct question from a list, as well) and Answer for an account are the same as knowing the password. This makes me think that you'd need to have the same kind of complexity requirements for the security answer that you do for a password. However, I can't recall ever seeing this implemented. If I've run into requirements at all, it's usually something simple, like at least 3 characters just to make sure you put something verifiable into the field. They're also relying on the fact that send the code to a registered location in place of the additional complexity. I plan to mitigate this by also sending an e-mail on completion, or when the session expires on failure, and by limiting the number of attempts in a given time frame. The system administrator has the ability to do a reset manually, without knowing the question/answer or original password, so I can't lose control of the account. But it seems like I'm still missing something. How should I handle this? A: In this circumstance, it seems like the security answer effectively becomes an alternative password That's right. Which is also why this seems like a really bad idea. It will only work as a feature if the question is something simple, something the user will know without having to remember it, which means that an attacker can figure it out as well (by searching for info online, on facebook, asking the victim, etc). Your current idea would weaken the security of your user accounts considerably, so I would look for an alternative. The best way would be to require an alternate email address or phone number (such as most email providers such as google do). Another alternative (if you require real names for sign-up) would be to require something like the copy of an identifying document for password recovery. An attacker might still be able to get this (especially if they know their victim personally), but it would be a bit more complicated. If you want to stick with your concept, at the very least I would perform password resets via phone instead of online, to deter some attackers.
{ "pile_set_name": "StackExchange" }
Q: Drupal programmatically stop module hook I am using the autoassignrole module to assign ROLE#1 to anyone registering on my site. Once signed in, users with ROLE#1 permissions can create users of their own for which I am using the uCreate module. I have it setup so that when creating users via the uCreate module, the new user can be assigned ROLE#2 or ROLE#3 permissions. The problem is at this point. The new user also inherits the ROLE#1 from the autoassignrole module. So, I put together a custom module and implemented hook_user and the plan is to detect when a user is being registered and programmatically stop the autoassignrole user_hook ... how do I do that? A: There are 2 potential solutions that I see at a high level: If uCreate has a custom form to create users, you can alter that form to also include a on-submission database query that removes the role from the user being created You can check if adding a condition to the autoassignrole module is possible-to attempt to disable autoassignment if the user's creation comes from an administration/uCreate add user URL
{ "pile_set_name": "StackExchange" }
Q: Dynamics CRM 365 - Invalid User Authorization The user authentication passed to the platform is not valid Whenever I click on an opportunity to customize it The window bellow opens It appears that the customization window is trying to open an activity window and it should open a opportunity chart window. The only error displayed is "Invalid User Authorization The user authentication passed to the platform is not valid" and there are no errors in the debug window. Note: Opportunity Charts are the only charts with this problem. If I try and customize a company chart the problem does not occur. Publishing a chart from XRMToolbox works. It is only in the customization window that the problem occurs. In the production version of my site, the problem does not occur. I have tried clearing my browsers cache as suggested here. ---UPDATE 1--- In response to @ConorGallagher Is it any of the opportunity charts or just particular ones? It is ALL opportunity charts. NONE of them will open. Have you tried opening up developer tools and checking network to see what exactly is failing? I have and the developer tools do not reveal any errors. Customization page: Chart page: Or using fiddler do analyse it and find out what exactly is failing? This is all I get from fiddler when I click on a chart: Are there any encryption settings that differ between production and dev? Encryption settings are the same between the two. Is the dev organization a database copy of production or a new install? Dev organization is a copy of the production that was working prior to in place upgrade. Does it happen when you're logged directly onto the server and try customizing charts? It happens on PC and directly on server. ---Update 2--- In response to @ConorGallagher I'd have expected a 401 (or some http error) someplace on the network tab in developer tools. Can you double check that tab just to see. I would have also but everything in the network tab is a 200. Except the first one is a 302. See fiddler output bellow v. In response to @Pawel Gradecki 1) You should not check Developer Tools for script errors, switch the tab to "Network" and check for any HTTP errors there. See above snapshoot to @ConorGallagher of my network window ^. Also you did not enable HTTPS decryption on fiddler, so your log is not very meaningful, you should enable this first and then recheck fiddler My apologies here is the fiddler output with decryption enabled: This is much more helpful. The page appears to not be able to find the source map (404) and then redirects to the error page (302). I'm not sure though if it redirects because it can't find the source map or because of some other error. 2) Check server Trace logs, they can show some additional info that can be used for troubleshooting https://raw.githubusercontent.com/MasterProgrammer200/stackoverflow/master/crm/log-opportunity-user-auth.txt 4) Can you open some working chart designer (for example for account) and copy the full URL and paste it to a separate window. Do the same with Opportunity chart (copy and paste it to separate window). If it's still not working for Opportunity compare both URLs, try to play with them a little (exchange some query string parameters). I played with the url https://crmcanada-dev.url.com/main.aspx?appSolutionId=%7bFD140AAF-4DF4-11DD-BD17-0019B9312238%7d&extraqs=etc%3d1%26id%3d%7bA3A9EE47-5093-DE11-97D4-00155DA3B01E%7d&pagetype=vizdesigner#665349499 Now if I change the url to: https://crmcanada-dev.url.com/main.aspx?appSolutionId=%7bFD140AAF-4DF4-11DD-BD17-0019B9312238%7d&extraqs=etc%3d3%26id%3d%7bA3A9EE47-5093-DE11-97D4-00155DA3B01E%7d&pagetype=vizdesigner#665349499 (Since 1 is the Company object and 3 is the opportunity object). I still get redirected to the invalid user page. Remember to check very carefully server Trace, because it can tell you something meaningful. If you will have something there, paste it here so we can also have a look at it. See above link ^. One more idea that came into my mind - try to backup your organization database, restore it under different name, import it under different name (so you should have a separate organization on DEV). Sometimes there are errors during organization import that do not stop the import itself, but cause some strange behaviour of the CRM. Check if this re-imported organization has the same problem. This would be a last resort. A: After a week of pleading and sacrificing burnt offerings to the programming gods (aka Microsoft support) we were finally able to figure out what the problem was. The problem was that prior to the upgrade from CRM 2016 to CRM 365 we had removed a managed solution but for some reason one of the fields in the view didn't go with it. When we upgraded to 365 the unremoved field caused an error. Upon investigation we found a exclamation mark in a circle next to the problematic field in the view creator. To fix the problem we went through every view and removed the troublesome field which for us was new_opportunitytype. Then we used the bellow query to scan the CRM database for occurrences of new_opportunitytype and had to remove it from a form by editing the xml in the SystemFormBase table In short, hide yo kids, hide yo wife, check yo views, but most of all Microsoft needs better error handling. Helpful query from Microsoft Support: /*This query searches the entire CRM database for the specified string*/ declare @TableName char(256) declare @ColumnName char(256) declare @FindString char(256) declare @sql char(8000) /*Replace X with character(s) you which to find and Y with its replacement*/ set @FindString = '[enter a guid or string or something]' /*select o.name, c.name from syscolumns c inner join sysobjects o on o.id = c.id where o.xtype = 'U'*/ declare T_cursor cursor for select o.name, c.name from sysobjects o inner join syscolumns c on o.id = c.id where o.xtype = 'U' and c.xtype in (175,239,99,231,35,167) open T_cursor fetch next from T_cursor into @TableName, @ColumnName while (@@fetch_status <> -1) begin set @sql = 'if exists (select * from ' + rtrim(@TableName) + ' where ' + rtrim(@ColumnName) + ' like ''%' + rtrim(@FindString) + '%'') begin print ''Table = ' + rtrim(@TableName) + ' Column = ' + rtrim(@ColumnName) + ''' end' exec(@sql) fetch next from T_cursor into @TableName, @ColumnName end close T_cursor deallocate T_cursor
{ "pile_set_name": "StackExchange" }
Q: What is interior and exterior drifting? I've heard of 'inverse' or 'interior' drifting, and same with exterior... I think it was to do with statistics or something... What's the difference and how does it affect gameplay? A: Do you mean modifying your drift path? You can do this by steering more to the left (or right) while you are already drifting. For example, if you're drifting left, you can get a sharper drift by steering even more to the left, or a wider drift by steering to the right; lesser to the left. (Of course, reverse the directions if you're drifting to the right) Just note that you can only do this while having your drift mode set to manual. The example below shows the difference in paths when doing a wide/sharp drift as compared to a normal drift to the right.
{ "pile_set_name": "StackExchange" }
Q: Error running new gwt app in hosted mode, OS X 10.6 I just created a new project using webAppCreator from GWT which worked fine. However, when I try to run ant hosted it fails with the following output: [java] On Mac OS X, ensure that you have Safari 3 installed. [java] Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load required native library 'gwt-ll'. Detailed error: [java] Can't load library: /usr/local/gwt-mac-1.7.1/libgwt-ll.dylib) [java] [java] Your GWT installation may be corrupt [java] at com.google.gwt.dev.shell.LowLevel.init(LowLevel.java:106) [java] at com.google.gwt.dev.shell.mac.LowLevelSaf.init(LowLevelSaf.java:135) [java] at com.google.gwt.dev.BootStrapPlatform.initHostedMode(BootStrapPlatform.java:68) [java] at com.google.gwt.dev.HostedModeBase.<init>(HostedModeBase.java:362) [java] at com.google.gwt.dev.SwtHostedModeBase.<init>(SwtHostedModeBase.java:127) [java] at com.google.gwt.dev.HostedMode.<init>(HostedMode.java:271) [java] at com.google.gwt.dev.HostedMode.main(HostedMode.java:230) Related ANT task "hosted": <target name="hosted" depends="javac" description="Run hosted mode"> <java failonerror="true" fork="true" classname="com.google.gwt.dev.HostedMode"> <classpath> <pathelement location="src"/> <path refid="project.class.path"/> </classpath> <jvmarg value="-Xmx256M"/> <jvmarg value="${XstartOnFirstThreadFlag}"/> <!--<jvmarg value="${d32Flag}"/>--> <jvmarg value="-d32" /> <arg value="-startupUrl"/> <arg value="MyApplication.html"/> <!-- Additional arguments like -style PRETTY or -logLevel DEBUG --> <arg value="com.disney.MyApplication"/> </java> </target> A: Copy or make a dynamic link of libgwt-ll.jnilib to libgwt-ll.dylib and try it again. Looks like someone else had a similar issue when using SoyLatte JVM. Details can be found here.
{ "pile_set_name": "StackExchange" }
Q: How can i setContentView in RelativeLayout? (progressbar) can someone please explain to me how i can so setContentView in a relative layout? i added an activity but i'm getting errors, nullpointers... i tried this: public ProgressbarActivity(Context context) { super(context); Activity a = new Activity(); RelativeLayout rl = new RelativeLayout(getContext()); LinearLayout k = new LinearLayout(getContext()); k.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); LinearLayout z = new LinearLayout(getContext()); z.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); RoundRectShape s = new RoundRectShape(f, null, null); ShapeDrawable shapedrawable = new ShapeDrawable(s); shapedrawable.setShape(s); shapedrawable.getPaint().setColor(0xffffffff); RoundRectShape s1 = new RoundRectShape(f, null, null); ShapeDrawable sd = new ShapeDrawable(s1); sd.setShape(s1); sd.getPaint().setColor(0xff0080ff); rl.setLayoutParams(new LayoutParams(200, 25)); LayoutParams lp = new LayoutParams(200, 20); rl.setPadding(0, 100, 0, 0); rl.setGravity(Gravity.CENTER_HORIZONTAL); ImageView iv = new ImageView(getContext()); iv.setBackgroundDrawable(shapedrawable); iv.setLayoutParams(lp); GradientDrawable g = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colours); ImageView iv3 = new ImageView(getContext()); iv3.setBackgroundDrawable(g); iv3.setLayoutParams(lp); ClipDrawable cd = new ClipDrawable(sd, Gravity.LEFT, ClipDrawable.HORIZONTAL); ImageView iv2 = new ImageView(getContext()); iv2.setBackgroundDrawable(cd); iv2.setLayoutParams(lp); cd.setLevel(5000); rl.addView(iv); rl.addView(iv2); rl.addView(iv3); a.setContentView(rl); onCreate(); } what did i do wrong? can someone please explain it? I'm getting a nullPointerException... this is my logCat: 03-30 06:58:27.369: E/AndroidRuntime(1534): FATAL EXCEPTION: main 03-30 06:58:27.369: E/AndroidRuntime(1534): java.lang.RuntimeException: Unable to start activity ComponentInfo{eng.pim.app/eng.pim.app.PimActivity}: java.lang.NullPointerException 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.ActivityThread.access$600(ActivityThread.java:123) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.os.Handler.dispatchMessage(Handler.java:99) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.os.Looper.loop(Looper.java:137) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-30 06:58:27.369: E/AndroidRuntime(1534): at java.lang.reflect.Method.invokeNative(Native Method) 03-30 06:58:27.369: E/AndroidRuntime(1534): at java.lang.reflect.Method.invoke(Method.java:511) 03-30 06:58:27.369: E/AndroidRuntime(1534): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-30 06:58:27.369: E/AndroidRuntime(1534): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-30 06:58:27.369: E/AndroidRuntime(1534): at dalvik.system.NativeStart.main(Native Method) 03-30 06:58:27.369: E/AndroidRuntime(1534): Caused by: java.lang.NullPointerException 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.Activity.setContentView(Activity.java:1855) 03-30 06:58:27.369: E/AndroidRuntime(1534): at eng.pim.app.ProgressbarActivity.<init>(ProgressbarActivity.java:77) 03-30 06:58:27.369: E/AndroidRuntime(1534): at eng.pim.app.PimActivity.onCreate(PimActivity.java:24) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.Activity.performCreate(Activity.java:4465) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 03-30 06:58:27.369: E/AndroidRuntime(1534): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 03-30 06:58:27.369: E/AndroidRuntime(1534): ... 11 more A: There are many things wrong with your code: 1) If ProgressbarActivity is an Activity you don't use the constructor for initialization, you must use the onCreate() method to initialize views, build data, setup threads etc. 2) You never do this: Activity a = new Activity(); if you want to start a new activity with your layout that you build then you must use an Intent to start the new activity: Intent i = new Intent(CurrentActivityName.this, OtherActivityName.class); startActivity(i); The above code will work in an activity, otherwise instead of CurrentActivityName.this you'll have to get a reference to some Context(you could use the application context with the method getApplicationContext()) and also you must call startActivity() on that Context reference. If you want the new activity to have the layout that you build then move that code in the new activity onCreate() method, use setContentView() there with the Relativelayout that you built and use the above code with the Intent to start that activity. (Note: you must declare the new activity in the manifest) 3) RelativeLayout stacks views(one on top of the others), if this isn't what you want then use rules to correctly position the views in that layout Maybe you should see some tutorials on how to do it: -- for Activity creation and starting one: http://developer.android.com/guide/topics/fundamentals/activities.html -for RelativeLayout use: http://developer.android.com/resources/tutorials/views/hello-relativelayout.html
{ "pile_set_name": "StackExchange" }
Q: Is there a driver for Nvidia Titan Xp GPU for ubuntu? I have a Titan Xp collector's edition. Since I wasn't able to find a driver on nvidia's website for Titan Xp on Ubuntu, I didn't install any driver. But now my computer screen freezes randomly sometimes and I suspect it's caused by lack of driver. When the screen freezes, it freezes for about 10 seconds and it goes no-signal, at which point the led on my graphics card starts to blink periodically. Has anyone experienced this before? EDIT: one of the answers says to use the 384 driver. However that driver doesn't work for CUDA with linux 4.13 kernel. see https://devtalk.nvidia.com/default/topic/1028904/nvidia-driver-not-loading-after-cuda-9-1-installation-with-runfile/#5234072 So I installed 390.12 as suggested in that post but I still occasionally encounter these freezes. Right now I just want to know if this seems like a graphics card driver issue or did I not install Ubuntu correctly? Or is this a problem with firefox? Since everytime it seems to freeze when I'm using firefox (though I don't have that many samples) A: For 64-bit Linux Nvidia recommends Version: 384.111 Release Date: 2018.1.4 Operating System: Linux 64-bit Language: English (US) File Size: 77.25 MB Supported products NVIDIA TITAN Series: NVIDIA TITAN Xp, NVIDIA TITAN X (Pascal), GeForce GTX TITAN X, GeForce GTX TITAN, GeForce GTX TITAN Black, GeForce GTX TITAN Z See: http://www.nvidia.com/download/driverResults.aspx/128737/en-us So you may start with installing nvidia-384 package from software-properties-gtk (Software & Updates)
{ "pile_set_name": "StackExchange" }
Q: Which way is better to reset index in a pandas dataframe? There are 3 ways to reset index - reset_index(), inplace, and manually setting the index as df.index = list(range(len(df))) Since inplace is going to be deprecated in pandas 2, which way is better - reset_index() or manual setting and why? A: When assigning to the index, the rest of the data in your DataFrame is not changed, just the index. If you call reset_index, it creates a copy of your original DataFrame, modifies its index, and returns that. You may prefer this if you're chaining method calls (df.reset_index().method2().method3() as opposed to df.index = ...; df.method2().method3()), but for larger DataFrames, this becomes inefficient, memory wise. Direct assignment is preferred in terms of performance, but what you should prefer depends on the situation.
{ "pile_set_name": "StackExchange" }
Q: How to unit test method with disposable objects in it I was having unit test about my controller which was looking like that: [Test] public void Test() { //Arrange var dummySeamlessCustomerRequest = CustomerControllerTestsHelper.CreateDummyCustomerRequest(); var dummySeamlessCustomerResponse = CustomerControllerTestsHelper.CreateDummyCustomerResponse(); _mockSeamlessService.Setup(s => s.GetSeamlessCustomerCallRequest(_controller.Request, "Credit Customer")) .Returns(new ModuleResultSet<SeamlessCustomerRequest>(HttpStatusCode.OK, null, dummySeamlessCustomerRequest)); _mockAdapter.Setup(a => a.SendCreditCustomerCallToProvider(dummySeamlessCustomerRequest)) .Returns(dummySeamlessCustomerResponse); //Act var actionResult = _controller.CreditCustomer(); var expectedResponse = actionResult as ResponseMessageResult; //Assert Assert.IsNotNull(expectedResponse); Assert.AreEqual(CustomerControllerTestsHelper.CreateSeamlessCustomerResponseString(dummySeamlessCustomerResponse), expectedResponse.Response.Content.ReadAsStringAsync().Result); } My targeted method by the test is the following: public override IHttpActionResult CreditCustomer() { //... using (var response = new HttpResponseMessage()) { //... return this.ResponseMessage(response); } } I left most important part of the method to me(if you think I should show more tell me but there are only some service calls that I mock in my test with ease. Problem is that when I run my test I receive following error: Test Name: Test Test FullName: ETIAdapter.Tests.Controllers.CustomerControllerTests.Test Test Outcome: Failed Test Duration: 0:00:00.005 Result StackTrace: at System.Net.Http.HttpContent.CheckDisposed() at System.Net.Http.HttpContent.ReadAsStringAsync() at ETIAdapter.Tests.Controllers.CustomerControllerTests.Test() in D:\Repositories\test_seamless-service\seamless-service\src\ETIAdapter.Tests\Controllers\CustomerControllerTests.cs:line 79 Result Message: System.ObjectDisposedException : Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'. I tried to search for solutions to test such methods but I couldn't find it. Most of the questions are about custom objects that implement IDisposable so they are mocking them , but I can't do that with HttpResponseMessage. A: The response message is wrapped in a using statement which will call dispose once the method goes out of scope. Remove the using statement public override IHttpActionResult CreditCustomer() { //... var response = new HttpResponseMessage(); //... return this.ResponseMessage(response); } You are trying to manage code you do not control. The disposal of the response is managed by the framework. In this scenario there is no need to manage the HttpResponseMessage as the framework will dispose of it once the flow has been completed. By trying to dispose of it yourself you are breaking the framework (which you do not control). The framework expects to get a valid response message and use it.
{ "pile_set_name": "StackExchange" }
Q: Year/Quarter to datetime datatype I am trying to convert the "Year_Quarter" column (object) to datetime64 datatype.Note there is a space between year and quarter. df Year_Quarter 0 2009 Q1 1 2009 Q1 2 2009 Q2 I tried the code below df['Year_Quarter']=pd.to_datetime(df['Year_Quarter'].str.replace(' ', ''))+pd.offsets.QuarterBegin(startingMonth=1) However, I got the following error: AttributeError: Can only use .str accessor with string values! Thank you for your help! A: I'm not sure about the type of your df do you mind to add the output of df.info() When I try to reproduce it I don't have any error. import pandas as pd df = pd.DataFrame({'Year_Quarter': {0: '2009 Q1', 1: '2009 Q1', 2: '2009 Q2'}}) df['Year_Quarter'] = pd.to_datetime(df['Year_Quarter'].str.replace(' ', '')) Year_Quarter 0 2009-01-01 1 2009-01-01 2 2009-04-01
{ "pile_set_name": "StackExchange" }
Q: high charts with master-detail and handles I'm using highcharts to build a chart and I need to use the api that it exposes to do certain things. however I would like my chart to be a master-detail type chart like the one in the highstock library but which has the handles on them. I know i can create a master-detail in highcharts but it does not seem have the handles for dragging the selected range. A: In the end I used highstock and found an example with multiple series in the 'master' chart which is called 'navigator' the highstock charts. Example: http://jsfiddle.net/davidoleary/NudSK/
{ "pile_set_name": "StackExchange" }
Q: Issues with multiple with_items in a task I have a task which has multiple with_items and hence pick the latest defined item in the delegate which is not the expected result - name: Add secondaries run_once: true delegate_to: "{{ item }}" with_items: - "{{ groups['mongodb-active'] }}" shell: /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))' with_items: - "{{ groups['mongodb-arbiter'] }}" A: you cant have two with_items clauses. assuming you want to iterate the list groups['mongodb-active'] and execute the shell module for each item in the groups['mongodb-arbiter'] list, you could do it like that: --- - hosts: localhost gather_facts: false vars: mongodb_active_list: - host1 - host2 - host3 mongodb_arbiter_list: - json_a - json_b - json_c tasks: - name: print debug debug: msg: "running on host: {{ item.0 }}, shell module with argument: {{ item.1 }}" loop: "{{ query('nested', mongodb_active_list, mongodb_arbiter_list) }}" UPDATE: after understanding better the requirement, the task i would suggest is: - name: Add secondaries delegate_to: "{{ groups['mongodb-active'][0] }}" shell: /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))' with_items: - "{{ groups['mongodb-arbiter'] }}" it will delegate the task to the first host of the mongodb-active group (which is supposed to have only 1 host as clarification states), and iterate the task for all the hosts of the mongodb-arbiter group. hope it helps
{ "pile_set_name": "StackExchange" }
Q: Facebook share button anchor tag vs including javascript What is different of having a facebook share button just by having an anchor tag: <a href="http://www.facebook.com/sharer.php?u=<url to share>&t=<title of content>"> <img src="custom.jpg" /> </a> than having one with the javascript provided by FB follow by the anchor tag? <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> I just want to verify I'm not missing any of the basic functionality of sharing a link by using the anchor tag only because I want to use the anchor tag way to customize my button image. A: The end result of the share is the same, as when you click the button it ends up taking you to the same endpoint. The difference is in how the button looks (and the count that shows up if that's the layout you've chosen).
{ "pile_set_name": "StackExchange" }
Q: how to refer a computed column in MS SQL? I have written a query as follows. create table registration( id int identity(1000,1) , first_name varchar(45) unique, sur_name varchar(45), address_line1 varchar(45), address_line2 varchar(45), state varchar(45), city varchar(45), email_id varchar(45), contact_no varchar(45), date_of_birth date, apply_type varchar(45), qualification varchar(45), gender varchar(45), password as CONVERT(VARCHAR(4),DATEPART(dd,GETDATE())) + substring(CONVERT(VARCHAR(4),DATENAME(mm,GETDATE())),1,3) + convert(varchar(4),FLOOR(RAND(CHECKSUM(NEWID()))*(999-100)+100)), hint_question varchar(50), hint_answer varchar(50), user_id as substring(apply_type,1,4) + convert(char(45),id) persisted primary key not null); create table passport( id int identity(1000,1), Passport_Number as substring(Booklet_type,1,2) + convert(varchar(100),id) persisted primary key not null, user_id varchar(200) constraint fk_uid foreign key(user_id) references registration(user_id) on delete cascade, Type_of_Passport varchar(45), Type_of_Service varchar(50), Booklet_type varchar(50), Address1 varchar(50), Address2 varchar(50), City varchar(50), State varchar(50), Country varchar(50)n Pin int, Number_of_Years int, Date_Of_Application date, Issue_Date date, Amount int, Reason_for_reissue varchar(50), Expired_Date date); But I'm getting the following error: Column 'registration.user_id' is not the same length or scale as referencing column 'passport.user_id' in foreign key 'fk_uid'. Columns participating in a foreign key relationship must be defined with the same length and scale. How to rectify this problem? A: cast or convert the user_id in registration to varchar(200) ie same as the one in passport user_id as CONVERT(VARCHAR(200), substring(apply_type,1,4) + convert(char(45),id) ) persisted primary key not null);
{ "pile_set_name": "StackExchange" }
Q: Python xlwt - making a column readonly (cell protect) Is there a way to make a particular cell read-only/write protected in python xlwt? I know there's is a cell_overwrite_ok flag which does not allow to overwrite contents of cells (all cells) but can this be done on cell by cell basis. Thanks, Sun A: Excel cells have a locked attribute that is enabled by default. However, this attribute is only invoked when the worksheet's protection attribute is also set to True. If the worksheet is not protected, the locked attribute is ignored. Therefore, your question isn't best framed as how to make cells read-only. Rather, the question is how to make cells editable after protecting the worksheet. ...Here you are: from xlwt import Workbook, Worksheet, easyxf # ... # Protect worksheet - all cells will be read-only by default my_worksheet.protect = True # defaults to False my_worksheet.password = "something_difficult_to_guess" # Create cell styles for both read-only and editable cells editable = easyxf("protection: cell_locked false;") read_only = easyxf("") # "cell_locked true" is default # Apply your new styles when writing cells my_worksheet.write(0, 0, "Can't touch this!", read_only) my_worksheet.write(2, 2, "Erase me :)", editable) # ... The cell styles (easyxf class) are also useful for declaring background color, font weight, etc. Cheers.
{ "pile_set_name": "StackExchange" }
Q: How to access the current element's attribute in a jQuery expression? I would like to call a function on each selected element: $('any valid selector').existingFunction({ p1:<myAttributeValueForTheCurrentElement> }); I've tried: $('any valid selector').existingFunction({ p1: this.attr('myAttributeValueForTheCurrentElement') }); but apparently this refers to HTMLDocument because I got the error message: 'Object # has no method 'attr'' A: this is bound to the outer scope. Your code is equivalent to the following: var obj = { p1: this.attr('myAttributeValueForTheCurrentElement') }; $('any valid selector').existingFunction(obj); You are going to need to iterate over the elements in the collection. $('selector').each(function(){ var options = { p1: $(this).attr('myAttributeValueForTheCurrentElement') }; $(this).existingFunction(options); });
{ "pile_set_name": "StackExchange" }
Q: Minecraft gift card/code Is there a Minecraft gift card/code that allows you to buy better weapons in-game? My stepson is obsessed. I can't work out whether gift cards/codes just buy you the game or allow you to purchase better weapons in-game? I'm in Australia. A: No, Minecraft does not have any form of micro transactions (buying weapons/cosmetic items). Gift cards are solely for obtaining the game. Besides, part of the fun of the game is making the weapons.
{ "pile_set_name": "StackExchange" }
Q: Invariant subspaces Let T be a linear operator on a finite dimensional vector space V over a field F such that every subspace of V is invariant under T then how to prove T is digonalizable ? Is the converse true ? A: The property implies that $T=cI$ for some scalar $c$. First, since every subspace is invariant, every (non-zero) vector is an eigenvector. Now suppose $u$ and $v$ are independent, $Tu=au$, $Tv=bv$. Then $$T(u+v)=au+bv.$$But we also have $$T(u+v)=c(u+v)$$for some scalar $c$. Independence shows that $a=c=b$. So $T=c I$. A: If $v_1,\ldots,v_n $ is a basis, then for each $j $ we have $Tv_j=\lambda _jv_j $ for some $\lambda \in F $, since the subspace $Fv_j $ is invariant. So $T $ is diagonalizable. This property means that $T $ is diagonalizable in every basis, so it is very strong; so the converse does not hold. Let $V=\mathbb R^2$ and $$T=\begin {bmatrix}1&0\\0&2\end {bmatrix}. $$ Consider the subspace $$V_0=\left\{(a,a)^T: a\in\mathbb R\right\}. $$ Then $T $ is diagonalizable (in the canonical basis) but $V_0$ is not invariant.
{ "pile_set_name": "StackExchange" }
Q: More elegant way to express ((x == a && y == b) || (x == b && y == a))? I'm trying to evaluate ((x == a && y == b) || (x == b && y == a)) in Swift, but it seems a bit verbose. Is there a more elegant way? A: If the elements are Hashable, you can use Set: Set([a,b]) == Set([x,y]) If they not, you can use tuples to get rid of many extra symbols: (a,b) == (x,y) || (a,b) == (y,x)
{ "pile_set_name": "StackExchange" }
Q: When I escape all the input, sometimes It leaves slashes (\) in the string and inserts it to database. Why does it happen and how can I solve this? I have found stripslashes function but I would rather find where I am adding more slashes than I should. My functions use mysql_real_escape_string once for each variable and I am querying database using "insert into foo(bar,bar) values($baz,$baz)" maybe this is the problem. phpinfo gives magic_quotes_gpc On On magic_quotes_runtime Off Off magic_quotes_sybase Off Off static function insert($replyto,$memberid,$postid,$comment) { $message=array(); $lenmax=1000; $lenmin=5; $toolong="comment is too long."; $tooshort="comment is too short."; $notarget="replied comment is deleted"; $nomember="you are not a member"; $notpost="commented post is deleted"; switch(true) { case strlen($comment)<$lenmin: $message[]= $tooshort; break; case strlen($comment)>$lenmax: $message[]=$toolong; break; case $replyto!=NULL && !commentexists($replyto): $message[]=$notarget; break; case !memberexists($memberid): $message[]=$nomember; break; case !postexists($postid): $message[]=$nopost; break; case count($message)>0:return $message; break; } $replyto=mysql_real_escape_string($replyto); $memberid=mysql_real_escape_string($memberid); $postid=mysql_real_escape_string($postid); $comment=mysql_real_escape_string($comment); if($replyto==NULL) mysql_query("insert into fe_comment(memberid,postid,comment) values($memberid,$postid,'$comment')"); else mysql_query("insert into fe_comment(replyto,memberid,postid,comment) values($replyto,$memberid,$postid,'$comment')"); } my hosting firm has magic_quotes_gpc on and I don't have access to php.ini file I am using plesk panel to configure things. php documentation says An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form. My insert queries are inserted with slashes in the database and My php version is 5.2.3 documentation also says If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice. So I am checking if I escaped values twice I am not able to find anywhere I escaped the values twice. now I am using $comment=mysql_real_escape_string(stripslashes($comment)); but I think it shouldn't become a standard in my codes because it doesn't look like "the right way" even though it saves the day. magic_quotes_gpc automaticly escapes all and also is not reliable because it is deprecated. so I have created a .htaccess file and copied it into all directories I have an index.php file, .htaccess files have this text only php_flag magic_quotes_gpc Off I ran phpinfo and it still gives magic_quotes_gpc On On magic_quotes_runtime Off Off magic_quotes_sybase Off Off now I need a way to disable the magic quotes gpc and I have no access to the php.ini file. I am looking for the ways to edit .htaccess files now. A: I think it shouldn't become a standard in my codes because it doesn't look like "the right way" You are right. magic quotes stuff has nothing to do with sql stuff and shouldn't be connected to it. Because magic quotes is a site-wide problem and sql escaping is sql only related problem. So, they need different treatment an should be never used in conjunction. You have to get rid of magic quotes unconditionally, because it spoiling not only SQL stuff but every data manipulation of your site. So, it would be wise to put some stripslashes code in whatever bootstrap file to be run on every call of the script. The code you can find in numerous implementations of such a code, just google for the 'stripslashes_deep' function. It would be wise to have this code always run (of course under the condition checking get_magic_quotes_gpc()) despite of the actual state of magic quotes, just for sake of compatibility. But there is another possibility to turn them off: try to create a php.ini file in the root of your application. However, there is a grave mistake in your code. In fact, it doesn't protect anything. You are escaping $memberid and $postid but don't quote them!. Thus, there is no protection at all. Just because escaping works only when used with quoting. Please, remember: Escaping is not a synonym for security! Escaping alone can help nothing. There is a whole set of rules to be followed. I wrote a decent explanation recently, so, I wouldn't repeat myself: Replacing mysql_* functions with PDO and prepared statements
{ "pile_set_name": "StackExchange" }
Q: foreach loop returns zero results I am pulling data from a json file and I get results no problem but I a only get 1 result. So when I do a foreach loop I get no results. json results: { "channels": [ { "position": 4, "id": "901", "name": "Away" }, { "position": 0, "id": "900", "name": "General" }, { "position": 1, "id": "889", "name": "HQ" }, { "position": 2, "id": "888", "name": "Base" } ], } I can echo out this: echo $json_array['channels'][0]['position']; echo $json_array['channels'][0]['id']; echo $json_array['channels'][0]['name']; But whatever I try I only get 1 result I do a foreach loop and it does nothing foreach($json_array as $item) { echo $item['channels'][0]['position']; echo $item['channels'][0]['id']; echo $item['channels'][0]['name']; } Am I missing something? A: You are getting the value of first object only. $json_array['channels'] is an array of objects, you need to loop over that objects. This should work: foreach($json_array['channels'] as $item) { echo $item['position']; echo $item['id']; echo $item['name']; } To make it clear to understand, this is how it would work with a for loop: for($index = 0; $index < count($json_array['channels']); $index++) { echo $json_array['channels'][$index]['position']; echo $json_array['channels'][$index]['id']; echo $json_array['channels'][$index]['name']; } A: You missing collection iteration foreach($json_array['channels'] as $item) { echo $item['position']; echo $item['id']; echo $item['name']; } A: Using foreach, you can now access every element of array channels by variable $item foreach($json_array['channels'] as $item) { echo $item['position']; echo $item['id']; echo $item['name']; } Doc: http://php.net/manual/en/control-structures.foreach.php
{ "pile_set_name": "StackExchange" }
Q: Why host stops when halting LXC guest? I'm following these directions to create an LXC box on Debian 7 (wheezy): http://fabiorehm.com/blog/2013/07/18/crafting-your-own-vagrant-lxc-base-box/ I start a container/guest using this command: sudo lxc-start -n wheezy-base But when I halt it, the host stops as well. sudo halt What am I doing wrong? How to stop an LXC guest correctly and get back to the host? Thank you A: You're using Debian 7, and don't have access to LXC user namespaces (which should be available in jessie, and are available in stretch). So, "root" in a container is equivalent to root on the host. Thus when you call sudo halt you are doing so as root for the whole system. (Containers on such older systems are not secure and cannot be made secure; you should be using a newer version of Debian, or preferably a Red Hat-based system, for any container work that requires even a moderate amount of security.) To kill a container, from outside the container use lxc-stop. lxc-stop -n wheezy-base -k From inside the container, try kill -PWR 1 to fake the container's init process into thinking the (nonexistent) power button has been pressed.
{ "pile_set_name": "StackExchange" }
Q: BULK INSERT into specific columns? I want to bulk insert columns of a csv file to specific columns of a destination table. Description - destination table has more columns than my csv file. So, I want the csv file columns to go to the right target columns using BULK INSERT. Is this possible ? If yes, then how do I do it ? I saw the tutorial and code at - http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/ and http://www.codeproject.com/Articles/439843/Handling-BULK-Data-insert-from-CSV-to-SQL-Server BULK INSERT dbo.TableForBulkData FROM 'C:\BulkDataFile.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) They don't show you how you can control where data is inserted. A: Yes, you can do this. The easiest way is to just create a View that Selects from the target table, listing the columns that you want the data to go to, in the order that they appear in the source file. Then BULK INSERT to your View instead of directly to the Table.
{ "pile_set_name": "StackExchange" }
Q: How to insert a entity at the end of a table using JPA? Hello and happy new year for everyone. I need to insert a record at the end of a table (the table has not set autoincrement) using JPA. I know I could get the last id (integer) and apply to the entity before insert, but how could that be done? Which way would be most effective? A: There is no such thing as "the end of the table". Rows in a relational table are not sorted. Simply insert your new row. If you need any particular order, you need to apply an ORDER BY when selecting the rows from the table. If you are talking about generating a new ID, then use an Oracle sequence. It guarantees uniqueness. I would not recommend using a "counter table". That solution is either not scalable (if it's correctly implemented) or not safe (if it's scalable). That's what sequences were created for. I don't know JPA, but if you can't get the ID from a sequence then I suggest you find a better ORM. A: Well, while i do not know where the end of a table really is, JPA has a lot of options for plugging in ID generators. One common option is to use a table of its own, having a counter for each entity you need an ID for (from http://download.oracle.com/docs/cd/B32110_01/web.1013/b28221/cmp30cfg001.htm). @Id(generate=TABLE, generator="ADDRESS_TABLE_GENERATOR") @TableGenerator( name="ADDRESS_TABLE_GENERATOR", tableName="EMPLOYEE_GENERATOR_TABLE", pkColumnValue="ADDRESS_SEQ" ) @Column(name="ADDRESS_ID") public Integer getId() { return id; } ...other "Generator" strategies to be googled... EDIT I dare to reference @a_horse_with_no_name as he says he does not know about JPA. If you want to use native mechanisms like sequence (that are not available in every DB) you can declare such a generator in JPA, too. I do not know what issues he encountered with the table approach - i know large installations running this successfully. But anyway, this depends on a lot of factors besides scalability, for example if you want this to be portable etc. Just lookup the different strategies and select the appropriate.
{ "pile_set_name": "StackExchange" }
Q: How to map values of one dataframe to asecond dataframes of different length using PANDAS i have daily stock data in a dataframe as below: Date Open High Low Close Volume Change Week_Number 1 2018-03-19 0.479304 0.479304 0.479304 0.479304 2050 -0.040000 12 2 2018-03-20 0.479304 0.479304 0.479304 0.479304 0 0.000000 12 3 2018-03-21 0.499275 0.499275 0.489290 0.489290 28265 0.020833 12 4 2018-03-22 0.489290 0.489290 0.489290 0.489290 75 0.000000 12 5 2018-03-23 0.489290 0.489290 0.489290 0.489290 0 0.000000 12 6 2018-03-26 0.489290 0.489290 0.479304 0.479304 7020 -0.020408 13 7 2018-03-27 0.479304 0.479304 0.479304 0.479304 0 0.000000 13 8 2018-03-28 0.474312 0.474312 0.474312 0.474312 2861 -0.010417 13 9 2018-03-29 0.474312 0.474312 0.474312 0.474312 0 0.000000 13 10 2018-03-30 0.474312 0.474312 0.474312 0.474312 0 0.000000 13 11 2018-04-02 0.474312 0.474312 0.474312 0.474312 0 0.000000 14 I then take this data and convert it to weekly stock data and perform a calculation (weekly_Final) as per below Open High Low Close Volume Change Weekly_Final Year Week_Number 2018 12 0.479304 0.499275 0.479304 0.489290 30390 NaN 2 13 0.489290 0.489290 0.474312 0.474312 9881 -0.030612 1 14 0.474312 0.474312 0.474312 0.474312 0 0.000000 0 15 0.474312 0.474312 0.449348 0.459333 40277 -0.031579 3 16 0.459333 0.469319 0.459333 0.469319 10000 0.021739 0 what i now need to do is take the weekly final column and map the values in weekly final to the corresponding weekly_Number in the daily dataframe to produce the following: Date Open High Low Close Volume Change Week_Number Weekly_Final 1 2018-03-19 0.479304 0.479304 0.479304 0.479304 2050 -0.040000 12 2 2 2018-03-20 0.479304 0.479304 0.479304 0.479304 0 0.000000 12 2 3 2018-03-21 0.499275 0.499275 0.489290 0.489290 28265 0.020833 12 2 4 2018-03-22 0.489290 0.489290 0.489290 0.489290 75 0.000000 12 2 5 2018-03-23 0.489290 0.489290 0.489290 0.489290 0 0.000000 12 2 6 2018-03-26 0.489290 0.489290 0.479304 0.479304 7020 -0.020408 13 1 7 2018-03-27 0.479304 0.479304 0.479304 0.479304 0 0.000000 13 1 8 2018-03-28 0.474312 0.474312 0.474312 0.474312 2861 -0.010417 13 1 9 2018-03-29 0.474312 0.474312 0.474312 0.474312 0 0.000000 13 1 10 2018-03-30 0.474312 0.474312 0.474312 0.474312 0 0.000000 13 1 11 2018-04-02 0.474312 0.474312 0.474312 0.474312 0 0.000000 14 0 I'm relatively novice with python/ pandas and so far my attempts to achieve this have failed miserably. I have tried to use pd.np.where statements but I am continually met with errors relating to the differing data frame sizes. thanks in advance A: You could do this. pd.merge(left=daily_stock_data, right=weekly_stock_data[['Week_Number', 'Weekly_Final']], how="inner", on="Week_Number") Check out pandas.merge() for more
{ "pile_set_name": "StackExchange" }
Q: Four concerns on this short passage? I was so stunned by her sudden change of mood that I couldn’t process her words. I just stood there staring at her. She swung her schoolbag as if she were about to hit me on the head with it, but changed her mind and ran off toward her entrance. I went home, crying. I cried on and off for the rest of the day . My grandmother and then my mother kept asking me what was wrong, but I wouldn’t say. I didn’t really understand it myself. Perhaps what I was feeling was shame—not just the mortification of having made the wrong assumption about Tania’s father but the deeper, sickening humiliation of ** being excluded from the **élite group of children who had fathers. (from Katania, published in The New Yorker). What does it mean I couldn't process her words ? What does it mean cry on and off ? What does it mean sickening humiliation of , I mean what does sickening here mean? What is an élite group ? A: 1.) I couldn't process her words. I couldn't understand her words (meaning) or I couldn't make out her words. (hearing) 2.) Cry on and off To cry and stop crying then cry again and stop etc. 3.) Sickening humiliation So humiliated that they felt sick (as in the humiliation was unbearable even to the point it was nauseous.) 4.) élite group wealthy or a socially high status group This can be answered with a dictionary for the most part.
{ "pile_set_name": "StackExchange" }
Q: Proper way to include student evaluations for job application? I've seen a handful of academic teaching jobs request that the applicant send "copies of student evaluations" as part of the application. How exactly is this supposed to be done? Pick and choose your favorites / all the positive evaluations? Send an entire class's evaluations for completeness? Emphasize well written (possibly long) ...OR...pick short and sweet but very positive? Ex: "Best instructor I ever had!!!" Include somewhat negative ones to demonstrate "realism"? What's the proper format? PDF or doc file with paragraphs of comments? An addition to the cover letter? Etc.. In general, what's the proper way to go about (or perhaps best practices for) including student evaluations in an application?? Note: "student evaluation" = "course evaluation" (i.e., comments students make about the course/instructor). A: I've been involved in three searches over the last three years. We typically only request teaching evaluations from candidates who've made our short list for phone/skype interviews since it generates an immense number of pages of material to review. We want a .pdf of all of your teaching evaluations. If it becomes apparent that you've edited or selected evaluations the people reading them will have good reason to discount what you sent them. The only way to avoid this is to include all of your evaluations for every course that you've taught (or for more experienced folks all evaluations from the past three years or some similar period.) You should take whatever was given to you by your institution, and convert it to .pdf format. Don't transform it in any other way.
{ "pile_set_name": "StackExchange" }
Q: std::less compiling issue I am trying to use a user defined class 'A' with the template std::less. I have also a function overriding < operator as required by std::less. This code is not compiling. #include<iostream> #include<functional> using namespace std; class A{ public: A(int x=0):a(x){} int a; bool operator<(const A& ref){ return a<ref.a; } }; int main() { A a1(1); A a2(2); std::less<A> comp; if( comp(a1,a2)){ cout<<"less"<<endl; } else{ cout<<"more"<<endl; } } A: Make it bool operator<(const A& ref) const{ return a<ref.a; }
{ "pile_set_name": "StackExchange" }
Q: XCUIApplication replacements for UIATarget captureScreenWithName() We are trying to migrate from UIAutomation to XCUITests and did use the captureScreenWithName() API to programmatically generate screen shots. What is the replacement in the XCUITests ? (I know that automatically screenshots are taken in case of error, but we have a special test which runs forever in a loop and evaluates QA click,tap commands via network similar to the appium-xcuitest-driver https://github.com/appium/appium-xcuitest-driver) Do I need to rip out private headers (XCAXClient_iOS.h) like the appium guys did in order to get a screenshot API? Edit I used the actual code line for the accepted solution from https://github.com/fastlane/fastlane/blob/master/snapshot/lib/assets/SnapshotHelper.swift and its just this for IOS XCUIDevice.sharedDevice().orientation = .Unknown or in objC [XCUIDevice sharedDevice].orientation =UIInterfaceOrientationUnknown; I use a process on the host to lookup in the "Logs/Test/Attachments" directory all Screenshot_*.png files before the call , and find the new shot then after the call as the new file added in this directory. A: Gestures (taps, swipes, scrolls...) cause screenshots, and screenshots are also often taken while locating elements or during assessing expectations. Fastlane's snapshot tool uses a rotation to an unknown orientation to trigger a screenshot event (which has no effect on the app): https://github.com/fastlane/fastlane/tree/master/snapshot - you can use this if you want to be in control of some screenshots.
{ "pile_set_name": "StackExchange" }
Q: nonellipsed forms: "to glory" vs. "to hell" -- Is there a rule? To glory! I've come across the bizarre (is it?) question that's asking me to write the complete form of this exclaiming 'sentence'. I came along the sentence below as the nonellipsed expansion: [Let's go] to glory! However, it gets a bit hilarious if you want to apply the same to "to hell with the guns!": [Let's go] to hell with the guns! It's rather [Go] to hell with the guns! Are these exceptions? Is there a general rule we can apply to the phrases than begin with the structure "to + noun"? Is there ellipsis here, since I don't seem to see it? I've been taught that to write a complete expansion for the ellipsed form, you should choose what's the nearest and yet the shortest. Is this true? A: "to hell with X" is not truly ellipsis as you understand it; it is a set phrase, meaning, basically, "for all I care, X can go to hell" Thus "the hell with you" This is not abstruse; it is similar to other classic constructions "away with you!" "off with you" which both mean "Go away". (I know this doesn't explain why. I'll do more digging and try to improve this answer)
{ "pile_set_name": "StackExchange" }
Q: What is black hole spin? First of, congrats to the people at LIGO. In this article, the BBC notes that the latest LIGO results show that a new black hole was formed with a spin of $0.2$ (dimensionless number). What exactly is this number? Is this simply the ratio of the angular momentum that the blackhole is observed to have as a ratio of the maximal angular momentum as limited by some physics (Kerr Metric?)? A: Yes, the dimensionless spin such as $0.2$ in this case is simply the ratio $$ a= 0.2 = \frac{|\vec J_{\rm measured}|}{|\vec J_{\rm max}(M)|}$$ where the denominator is the maximum angular momentum allowed for the same value of the mass (as the measured mass). For the $d=4$ Kerr black hole, the maximum (the angular momentum of the extremal Kerr black hole) is $$ |\vec J_{\rm max}(M)| = \frac{GM^2}{c} $$ Note that at least one of the initial December 26th black holes had $a\geq 0.2$ while the final black hole's spin is estimated to be $a\approx 0.7$. That large value is coming mostly from the orbital angular momentum, the relative motion of the initial black holes. Black holes with $a\gt 1$ are "overextremal" and they are prohibited because for this excessive value of the angular momentum (it's similar for too high electric charges), the black hole solution has no horizon at all, so it is not really a black hole (because the presence of the event horizon is what defines the black hole). Moreover, such a "naked singularity" is almost certainly prohibited in any complete theory of (quantum) gravity. The limiting case $a=1$ of the extremal black holes is possible and interesting. It has various special properties, e.g. it radiates no Hawking radiation. A: Is this simply the ratio of the angular momentum that the blackhole is observed to have as a ratio of the maximal angular momentum as limited by some Physics (Kerr Metric?)? Yes, exactly. For a spinning black hole there are two event horizons, an inner and an outer horizon. The positions of the horizons are given by: $$ r = \tfrac{1}{2}\left(r_s \pm \sqrt{r_s^2 - 4\left(\frac{J}{Mc}\right)^2}\right) \tag{1} $$ where $J$ is the angular momentum and $r_s = 2GM/c^2$ is the Schwarzschild radius. If the black hole isn't spinning then $J=0$ and equation (1) gives the horizon positions as $r=0$ and $r=r_s$ i.e. just a Schwarzschild black hole. As we increase the angular momentum the inner horizon moves outwards and the outer horizon moves inwards, and when: $$ r_s^2 = 4\left(\frac{J}{Mc}\right)^2 \tag{2} $$ the two horizons meet and disappear to leave a naked singularity. This is then called an extremal black hole, and a simple rearrangement of (2) gives the extremal angular momentum as: $$ J_\text{ex} = \frac{Mc}{2}r_s = \frac{GM^2}{c} $$ The value of $0.2$ means $0.2J_\text{ex}$. I was going to ramble on about the physical significance of this, but Luboš has beaten me to it. See his answer for the details.
{ "pile_set_name": "StackExchange" }
Q: GtkNotebook add-tab button Is it possible in Gtk+ to have an add-tab button inline with the tabs in a notebook, ala Opera or Google Chrome? I do know that Opera uses Qt and Chrome uses custom tabs, but is it possible in pure Gtk+? A: Sure. Check out the class BrandedNotebook at line 1384 of this file. Unfortunately Gtk+ doesn't give you a "nice" way to do this, but you should be able to determine the amount of space available, and use it as you wish. In the case of BrandedNotebook, a pixbuf is drawn in the space, and mouse clicks are handled within the coordinates of the pixbuf.
{ "pile_set_name": "StackExchange" }
Q: php:Can't find the column but it is in the database I am having trouble figuring out what's wrong whit my code. The code is used to take out specific columns from 2 big tables from a database. But we also need to sum 1 specific value when after I have used the query. The problem is in this part $query = substr($query, 4); $sql2 = "SELECT SUM(Forspris) FROM orderrad JOIN orderhuvud on orderhuvud.OrderKund = orderrad.Orderdatum where ". $query; echo $sql2; $result = mysqli_query($conn, $sql2) or die(mysqli_error($conn)); while($row = mysqli_fetch_array($result)){ echo print_r($row); } this is the error i get: SELECT SUM(Forspris) FROM orderrad JOIN orderhuvud on orderhuvud.OrderKund = orderrad.Orderdatum where OrderKund = '15' AND Orderdatum between '2015-04-16' AND '2015-05-06'Unknown column 'orderrad.Orderdatum' in 'on clause' but it longer up in the code it can find the column orderdatum in the query <!doctype html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="css.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> </head> <body> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "garp"; $conn = new mysqli ($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } /* $query = $_GET['query']; */ $orderkund = $_GET['Orderkundinput']; $artikel = $_GET['Artikelinput']; $startDate =$_GET['startDate']; $endDate =$_GET['endDate'] ; $MCkys = "orderdatum"; $min_length = 2; $artikelQuery=""; $orderkundQuery=""; if(strlen($artikel) >= $min_length){ $artikel = htmlspecialchars($artikel); $artikel = mysqli_real_escape_string($conn, $artikel); $artikelQuery = " AND Artikelnr = '$artikel'"; } if (strlen($orderkund) >= $min_length){ $orderkund = htmlspecialchars($orderkund); $orderkund = mysqli_real_escape_string($conn, $orderkund); $orderkundQuery = " AND OrderKund = '$orderkund'"; } if (strlen($startDate) >= $min_length){ $startDate = htmlspecialchars($startDate); $startDate = mysqli_real_escape_string($conn, $startDate); $startDateQuery = " AND Orderdatum between '$startDate' "; } if (strlen($endDate) >= $min_length){ $endDate = htmlspecialchars($endDate); $endDate = mysqli_real_escape_string($conn, $endDate); $endDateQuery = "AND '$endDate'"; } $query = $artikelQuery.$orderkundQuery.$startDateQuery.$endDateQuery; if(strlen($query) >= $min_length){ $sql = "SELECT OrderHuvud.Ordernummer ,OrderHuvud.OrderserieIK ,OrderKund ,Fakturakund ,Orderdatum ,Erreferens ,Levereratvarde ,Radnummer ,Artikelnr ,Benamning ,Leveranstid ,Ursprungligtantal ,Levereratantal ,Forspris ,Bruttopris ,Varukostnad FROM garp.OrderHuvud left join garp.OrderRad on OrderHuvud.Ordernummer = OrderRad.Ordernummer where OrderHuvud.OrderserieIK = 'K'" .$query; $raw_results = $conn->query ($sql); $row_cnt = false === $raw_results ? 0 : $raw_results->num_rows; echo " <p class='rows'> Numbers of rows loaded: $row_cnt </p>"; if($row_cnt > 0){ while($raw_result = mysqli_fetch_array($raw_results)){ echo "<table class='table'><thead class='thead-light'><tr><th class='col'>".'Ordernummer'."</th><th class='col'>".'OrderserieIK'."</th><th class='col'>".'Orderkund'."</th><th class='col'>".'fakturakund'."</th><th class='col'>".'orderdatum'."</th><th class='col'>".'erreferens'."</th><th class='col'>".'leveratvarde'."</th><th class='col'>".'radnummer'."</th><th class='col'>".'artikelnr'."</th><th class='col'>".'benamning'."</th><th class='col'>".'leveranstid'."</th><th class='col'>".'Ursprungligtantal'."</th><th class='col'>".'Levereratantal'."</th><th class='col'>".'forspris'."</th><th class='col'>".'bruttopris'."</th><th class='col'>".'varukostnad'."</th></tr></thead>"; echo "<tbody><tr><td>".$raw_result['Ordernummer']."</td><td>".$raw_result['OrderserieIK']."</td><td>".$raw_result['OrderKund']."</td><td>".$raw_result['Fakturakund']."</td><td>".$raw_result['Orderdatum']."</td><td>".$raw_result['Erreferens']."</td><td>".$raw_result['Levereratvarde']."</td><td>".$raw_result['Radnummer']."</td><td>".$raw_result['Artikelnr']."</td><td>".$raw_result['Benamning']."</td><td>".$raw_result['Leveranstid']."</td><td>".$raw_result['Ursprungligtantal']."</td><td>".$raw_result['Levereratantal']."</td><td>".$raw_result['Forspris']."</td><td>".$raw_result['Bruttopris']."</td><td>".$raw_result['Varukostnad']."</td></tr></tbody></table>"; } } else{ echo "No return"; } } else{ echo "Minimum length is ".$min_length; } $query = substr($query, 4); $sql2 = "SELECT SUM(Forspris) FROM orderrad JOIN orderhuvud on orderhuvud.OrderKund = orderrad.Orderdatum where ". $query; echo $sql2; $result = mysqli_query($conn, $sql2) or die(mysqli_error($conn)); while($row = mysqli_fetch_array($result)){ echo print_r($row); } ?> Column Names: A: SELECT SUM(Forspris) FROM orderrad where orderhuvud.OrderKund Your table is orderrad and in your where you try to use another table (orderhuvud) but you need to join first in order to use it, or select from it. SELECT SUM(Forspris) FROM orderrad JOIN orderhuvud on orderhuvud.your_column_to_match = orderrad.your_column_to_match where orderhuvud.OrderKund = '15' AND orderhuvud.Orderdatum between '2015-04-16' AND '2015-05-06' Above code will join your table. In order to join them you need to find this column that both tables share and is the same for them so you join them on this. Just a really clear example, please don't hate for the w3school, this example is really really clear for inner join. Read more here!!!
{ "pile_set_name": "StackExchange" }
Q: Internet Explorer finds error in core Vue.js file I have a Vue.js-based application which works fine in all browsers. Except, you guessed it... When I try to open it in Internet Explorer, I get this error: Expected identifier in vue.min.js, line 6 character 4872 When I navigate to that line/character, it shows that the error is in code that says: var i=e.extends; To be precise, IE places the cursor right after the dot in the expression above when I go to the error. Vue.js is included from https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js but I get the same issue if I include it locally. Is there a solution to this besides telling users to use a different browser? A: I made a test with above Vue JS file in IE. Based on my testing results, I find that this error can occur with older versions of IE like IE-5, IE-7, IE-8. Error did not occurred with IE-9, IE-10, IE-11. Here is a testing result. Here, I want to suggest you to upgrade to IE 11 version which latest and only supported version currently. Microsoft had already stopped providing support for other older versions of IE. If you upgrade to IE 11 than it will be helpful to solve your issue.
{ "pile_set_name": "StackExchange" }
Q: Repetition in javascript using variables I'm trying to simplify my javascript. This is what I've got: $("select#selectme").change(function () { $(this).find("option:selected").each(function () { if ($(this).attr("value") == "select-a") { $('#industry').val('a1'); } else if ($(this).attr("value") == "select-b") { $('#industry').val('b1'); } }); }).change(); etc, for the whole alphabet. I would like to get the letter of the alphabet dynamically, to avoid repetition: "select-x" and .val('x1); etc. What would be the best approach? Thanks. A: $("select#selectme").change(function () { $(this).find("option:selected").each(function () { var val = $(this).attr("value"), letter = val.substring(val.length - 1); $("#industry").val(letter + "1"); }); }).change(); You could get the letter like this so you dont need all the if conditions for the whole alphabet. You are also just overriding the value of #industry so your iteration over the selected options seem unnecessary in this case. You could just get the value of the last one but I assume you actually have another reason for this iteration? In case you actually do not need that loop through selected options, you can just get rid of it and get the last one $("select#selectme").change(function () { var val = $(this).val(), lastval = val[val.length - 1], letter = lastval.substring(lastval.length - 1); $("#industry").val(letter + "1"); }).change();
{ "pile_set_name": "StackExchange" }
Q: Oracle 12c column_name inconsistency So I have this small problem with Oracle 12c. Whenever I do a query like SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE table_name = 'EMP'; I get the column names in the right order empno ename ... but when I run it again the column names get reversed. deptno comm ... ename empno Anyone knows why this happens? Is this a new "feature" implemented in 12c or it's just me that get this the wrong way? And most important is there a way to fix this? Thanks in advance and sorry if this is a dumb question. A: Use order by column_id; and you will allways get the right order of columns
{ "pile_set_name": "StackExchange" }
Q: Parsing command line parameters As an example of my problem consider the following situation: A user launches a program from command line with a syntax similar to this python prog.py "hi there" hi=Hello there=World! The output of the program is "Hello World!". My question refers to the part of parsing the arguments. How can I save the information contained in the "hi=Hello there=World!" part in order to use it? From there I should be able to do something with it. I don't have the slightest idea of what the parameters are going to be so the solution needs to be as generic as possible. A: you have to do something like this... save this as "argtest.py": import sys def main(x): print(x) if __name__ == "__main__": print sys.argv #notice this is whatever you put in the arguments print sys.argv[0] # this is the name of the file you used main(sys.argv[1]) this will pass the first arg into main() so if you are running from command line python argtest.py hello your output will be hello in your main() you would of course define whatever you want to do with the argument personally i do my parsing in under the if __name__=="__main__": line usually something like arguments = [x.split('=') for x in sys.argv[1:]] #if you want to seperate arguments like "pie=apple fart=stinky" sys.argv is a list of whatever you put after python argtest.py space seperated for example if you do python argtest.py apple pie comma poop sys.argv[1] == 'apple' sys.argv[2] == 'pie' sys.argv[3] == 'comma' sys.argv[4] == 'poop'
{ "pile_set_name": "StackExchange" }
Q: Using first char syntax with pgfkeys I am learning how to use first char syntax with pdfkeys. I want to make macros options more human, but then turn them into numbers for easier if-then analysis. But right now I am having some troubles: The following MWE \documentclass{article} \usepackage{xparse} \usepackage{expl3} \usepackage{pgfkeys} \makeatletter \pgfkeys{ /handlers/first char syntax = true, /MakePage/.is family, /MakePage, PageNumbering/.style = {ResetPageTF/#1/.get = \@@ResetPageNumbering}, Footer/.style = {FooterTypes/#1/.get = \@@FooterType}, ResetPageTF/.cd, Reset/.initial = 1, Continue/.initial = 0, FooterTypes/.cd, Blank/.initial = 4, Empty/.initial = 0, First/.initial = 1, Last/.initial = 2, Middle/.initial = 3, } \NewDocumentCommand{\MakePage}{ o m }{ \pgfkeys{/MakePage, #1}% The \textbf{footer type} will be% \if\@@FooterType0 Empty \fi \if\@@FooterType1 First \fi \if\@@FooterType2 Last \fi \if\@@FooterType3 Middle \fi \if\@@FooterType4 Blank \fi The \textbf{page numbering will be} \if\@@ResetPageNumbering1% Reset \else% Continued \fi } \makeatother \begin{document} \MakePage[Footer = Blank, PageNumbering = Reset]{Hello} \end{document} Produces something wrong. What is going wrong? A: In \pgfkeys you called FooterTypes/.cd after ResetPageTF/.cd, which leads you to the key path /MakePage/ResetPageTF/FooterTypes and /MakePage/FooterTypes stays undefined. Adding /MakePage, before FooterTypes/.cd will lead you to the correct path. I also took the freedom to implement the single char syntax. It's basically from the manual (page 880). The important part here is to know, that the argument given to the macro contains the key char, e.g. with :Middle \singlechar@footer gets :Middle as its argument. It's the job of this macro to get rid of it. Here it is done with \singlechar@@footer. Remark: in the code the \typeout lines are just for debugging and will write some information to the log file. The code: \documentclass{article} \usepackage{xparse} \usepackage{expl3} \usepackage{pgfkeys} \makeatletter \pgfkeys{ /handlers/first char syntax = true, /handlers/first char syntax/the character !/.initial=\singlechar@pagenumbering, /handlers/first char syntax/the character :/.initial=\singlechar@footer, /MakePage/.is family, /MakePage, PageNumbering/.style = {ResetPageTF/#1/.get = \@@ResetPageNumbering}, Footer/.style = {FooterTypes/#1/.get = \@@FooterType}, ResetPageTF/.cd, Reset/.initial = 1, Continue/.initial = 0, % go up again! /MakePage, % without it, the next line will lead to /MakePage/ResetPageTF/FooterTypes FooterTypes/.cd, Blank/.initial = 4, Empty/.initial = 0, First/.initial = 1, Last/.initial = 2, Middle/.initial = 3, } \newcommand\singlechar@pagenumbering[1]{% \typeout{XXXXXXXXXXXXXXXXXXXX page @: |#1|}% \singlechar@@pagenumbering#1\@@scend } \def\singlechar@@pagenumbering#1#2\@@scend{% \typeout{XXXXXXXXXXXXXXXXXXXX page @@: |#1|#2|}% \pgfkeysalso{PageNumbering={#2}}% } \newcommand\singlechar@footer[1]{% \typeout{XXXXXXXXXXXXXXXXXXXX footer @: #1}% \singlechar@@footer#1\@@scend } \def\singlechar@@footer#1#2\@@scend{% \typeout{XXXXXXXXXXXXXXXXXXXX footer @@: |#1|#2|}% \pgfkeysalso{Footer={#2}}% } \NewDocumentCommand{\MakePage}{ o m }{ \pgfkeys{/MakePage, #1}% The \textbf{footer type} will be% \typeout{XXXXXXXXXXXXXXXXXXXX footer: \meaning\@@FooterType} \if\@@FooterType0 Empty \fi \if\@@FooterType1 First \fi \if\@@FooterType2 Last \fi \if\@@FooterType3 Middle \fi \if\@@FooterType4 Blank \fi The \textbf{page numbering will be} \typeout{XXXXXXXXXXXXXXXXXXXX page: \meaning\@@ResetPageNumbering} \if\@@ResetPageNumbering1% Reset \else% Continued \fi } \makeatother \begin{document} \MakePage[Footer = Blank, PageNumbering = Reset]{Hello} \MakePage[:Empty,!Continue]{Hello} \end{document} The result:
{ "pile_set_name": "StackExchange" }
Q: Debugging a UIBezierPath I'm struggling to display a UIBezierPath that I generate in code, so in my attempt to debug it, I want to print the coordinates it is plotted on. I can't find this technique anywhere. Can someone share this, given the code below? Thanks UIBezierPath* beizerPath2 = [UIBezierPath bezierPath]; [beizerPath2 moveToPoint:CGPointMake(0.0, 167)]; [beizerPath2 addLineToPoint:CGPointMake(100, 40)]; [beizerPath2 addLineToPoint:CGPointMake(200, 70)]; [beizerPath2 addLineToPoint:CGPointMake(300, 30)]; [beizerPath2 addLineToPoint:CGPointMake(320, 30)]; [beizerPath2 addLineToPoint:CGPointMake(320, 167)]; [beizerPath2 closePath]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.path = [beizerPath2 CGPath]; //print Bezier/Path co-ordinates here. A: Not sure what you mean by "co-ordinates it is plotted on." You can get the minimum bounding rectangle for a path with the -bounds method. When you are debugging and want to use NSLog(), also don't overlook the very helpful NSString macros, such as NSStringFromCGRect(), e.g. NSLog(@"%@", NSStringFromCGRect([path bounds])); If I misunderstood your question, please clarify.
{ "pile_set_name": "StackExchange" }
Q: MySQL insert country iso or country id from another table I want to insert each visitor's country in my database. Maxmind returns the 2 letters country ISO that I could store in a VARCHAR(2), that would use 2 bytes, or, alternatively, I can use an UNSIGNED TINYINT that would use 1 byte, and would be the id from a table with all the countries. However I hit a bump; I need MyISAM engine for fast insertions, but MyISAM does not support FOREIGN KEYS, so I guess that for each insertion, I will have to make a select in the countries table to retrieve the country id. I don't know what is the best option, I absolutely need to use MyISAM as there will be lots of insertions but I don't want to constantly make SELECTs to retrieve the country id. A: If you only need the 2-letter ISO country code (and not the country name, language, or other information) then I'd say that storing it as CHAR(2) with no external table would be less resource-intensive than storing it as SMALLINT (TINYINT wouldn't be enough to cover all countries) with a lookup to an additional table. Note: there is no need for VARCHAR(2) in this case, CHAR(2) would be more efficient.
{ "pile_set_name": "StackExchange" }
Q: Basic comments formatting in Orchard CMS I am playing with Orchard CMS. The problem is that comments are formatted as plain text and even <p> tags are not generated. How to make possible a basic formatting such as <p> or may be <b>, <i>? A: You override the view ListOfComments.cshtml within your own theme, then you can change what is output to the ui. Orchard allows you to override any view/shape within your theme, hence allowing you to basically do whatever you like.
{ "pile_set_name": "StackExchange" }
Q: ADB: undo commands if I gave the command adb shell settings put global enable_freeform_support 1 how can I now reactivate the previous state? Maybe putting the 0 value instead of 1 in the above command line? A: Yes , you can reactivate previous state using putting 0 and restart the phone. adb shell settings put global enable_freeform_support 0
{ "pile_set_name": "StackExchange" }
Q: Using Relationships in NoSQL vs SQL For starters i am new to the NoSQL concept. I am developing essentially an API to allow users to create and store objects within our db. This will happen through a variety of front-end programs and lead to programs saving private data per user, programs sharing data, and data mining - accessing the relevant data on many users. A user can have many objects and we are not placing restrictions on what the object is or how it is accessed (programs will be responsible for ensuring communication between themselves), so likely objects will be arrays of other objects etc. What is important is a PER OBJECT ACL for users with various permissions. I also anticipate things such as tags of objects etc. Various lookups i can imagine are: direct - user asks for file list mine - as a user what can i see list owned - what objects have i created list tagged - what objects are tagged with 'appX' that i can access. and there will inevitably be many others I include the above to show the scenario i'm considering. While at the moment i don't care so much about scalability i like the NoSQL schema free concept so that applications can query for object data i don't know about eg. /user/obj/1/2/3 where all i know is user has obj. However the scenario seems very relational to me. User has obj, obj has permissions, permission has user and attrs etc. And i'm pretty sure i could build it in an RDMS base with just a lot of serialized objects and json data stores but it seems a prime NoSQL project (and i've heard a lot and would like to try it out). So the questions: Is this a job for NoSQL? How do i efficiently create such links between objects (was thinking mongodb) and in general is there any documents/tutorials about how to model data in NoSQL to handle such things without excessive lookups (hopefully from an RDMS perspective). From what i've been reading i can't see a way of storing such data that can easily allow the above cases without essentially reverting to a relational system. Should there be a RDMS/ key-val compromise whereby core auth and privlidges are handled in RDMS giving a key off to the key/val for the object lookup (not sure how sub-object /user/obj/1/2 permission would work here). Should this ever be the answer? :) Any other general advice is appreciated. The touted facebook use case must answer such relationship questions so i'm sure NoSQL can do it - i'm just yet to see how it can do it better. Thanks for sticking with a long question. A: NOSQL: Massive numbers of users, speed is essential, don't really care about data integrity (its a bonus if it happens) SQL (RDBMS): Everything else.
{ "pile_set_name": "StackExchange" }
Q: How do I get unique running apps in bottom panel for each KDE/Kubuntu workspace? I am using KDE 4.13.3 (I believe it is the kubuntu-desktop download) on Ubuntu 14.04. I changed Systems Settings->Workspace Appearance and Behavior->Workspace Behavior->Virtual Desktops to have 4. However, if I have Firefox running in Workspace 1, it shows up, not just in the bottom panel of Workspace 1, but also Workspace 2, Workspace 3, and Workspace 4, partially defeating the purpose of having Workspaces in the first place, and not what I would expect as the default behavior. Is there a way I can get applications started in one Workspace to only display in the bottom panel of the Workspace they were started in - or is that bottom panel for "all workspaces"? A: Right click on the task manager located on the bottom panel -> access Settings -> select "Only show tasks from the current desktop".
{ "pile_set_name": "StackExchange" }
Q: How can i install AMD Catalyst 15.9 Proprietary Ubuntu Graphics Driver Hello could someone navigate me on how to install this driver: http://support.amd.com/en-us/download/desktop?os=Ubuntu%20x86%2064 Ubuntu Version: 14.04 lts 64-bit Gpu: Amd Radeon HD 8850M Thank you in advance! A: Just open the Additional Drivers app (search it in Dash/Start) and use it to install fglrx. It's the same driver, but easier to install and update. If you want to get the driver from the website, just choose the top download option and double click the downloaded .deb. .deb files are installer packages for Ubuntu.
{ "pile_set_name": "StackExchange" }
Q: Can I run Gnome 3 in Classic Desktop and still switch to default Unity? I am using Unity and am pretty stisfied. Anyway I want to give Gnome 3 a try within my working machine. Can I upgrade my system (Natty) so I have Gnome3 (+Shell) in the Classic Desktop mode and still switch back to a functional Unity default Natty Desktop? A: As far as I know Unity only works with Gnome 2 and both Gnome versions do not really reside side to side with each other.
{ "pile_set_name": "StackExchange" }
Q: Set can contain duplicates? UPDATE: The answer is actually in the documentation: Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. Case closed, thanks everyone! Edit: The referenced topic about duplicates in a hash sets does have the same point, however it does not answer my question: Why is the documentation not saying anything about that a set is only guaraneteed to work with immutable objects? edit2: I do understand what happens. The set of course cannot know when the hashcode of the entities change after they have been added. But the point is that imo the documentation should clearly state that sets only work properly with immutable objects. I've been working with Java for more than 5 years now, and don't laugh, but only now I realized something about the Sets. I thought I understood what a set is, namely what the doc says: A collection that contains no duplicate elements. More formally, sets * contain no pair of elements e1 and e2 such that * e1.equals(e2), and at most one null element. But, this is totally not true?! See here: public static void main(String[] args) { Set<Entity> entitySet = new HashSet<>(); Entity e1 = new Entity("One"); Entity e2 = new Entity("Two"); entitySet.add(e1); entitySet.add(e2); e2.name = "One"; // ! System.out.println("Objects equal:" + e1.equals(e2)); Iterator<Entity> iterator = entitySet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } static class Entity { String name; Entity(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (!(obj instanceof Entity)) { return false; } return name.equals(((Entity) obj).name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return "Entity[name=" + name + "]"; } Output: Objects equal:true Entity[name=One] Entity[name=One] So, I guess the thing about sets not containing duplicates is only true when we deal with immutable entries? But why is the doc not saying anything about it? I was never really aware of this. The problem with this of course is that the entites could contain any number of further fields that are not part of the equality definition; and they might be different in those fields. I'm thinking about something like this: public static void main(String[] args) { Set<Entity> entitySet = new HashSet<>(); Entity e1 = new Entity("Public", true); Entity e2 = new Entity("Secret", false); entitySet.add(e1); entitySet.add(e2); e2.name = "Public"; Iterator<Entity> iterator = entitySet.iterator(); // print only public entity (e1) while (iterator.hasNext()) { Entity e = iterator.next(); if (e.equals(e1)) { System.out.println(e); } } } static class Entity { String name; boolean mayBeDisplayedToUser; Entity(String name, boolean mayBeDisplayedToUser) { this.name = name; this.mayBeDisplayedToUser = mayBeDisplayedToUser; } @Override public boolean equals(Object obj) { if (!(obj instanceof Entity)) { return false; } return name.equals(((Entity) obj).name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return "Entity[name=" + name + ", may be displayed:" + mayBeDisplayedToUser + "]"; } } Output: Entity[name=Public, may be displayed:false] Entity[name=Public, may be displayed:true] So.. I'm quite puzzled right now. Am I the only one that was not aware of this? A: You are adding the items to the HashSet while they are unique and then mutating the items after the fact. The containing HashSet has no idea that you broke the set contract by changing obj.name.
{ "pile_set_name": "StackExchange" }
Q: Changing the user object for the current user in Symfony logs me out I have the following code: public function editAction(Request $request) { $user = $this->get('security.context')->getToken()->getUser(); // Get the user $user2 = $this->getDoctrine() ->getRepository('OpinionsUserBundle:User') ->findOneById($user->id); echo $user->email . '<br>'; // Echo [email protected] echo $user2->email . '<br>'; // Echo [email protected] $user2->email = 'blah'; echo $user->email; // Echoes blah die(); } So I know that Doctrine must be doing something with references. The problem is I have a form where the user can change their name and email, but if the email is already in use I want to show an error. However, Symfony binds data to the user object when I check validation, so somehow the session is being updated with the new user object, logging me out or changing my user. How can I avoid this? A: The solution I ended up using was refreshing the user model (returning it to it's original state) if my form validation failed. // Reset to default values or else it will get saved to the session $em = $this->getDoctrine()->getManager(); $em->refresh($user);
{ "pile_set_name": "StackExchange" }
Q: PHP use getResults to filter and echo response based on the results I did a search through to see if I could find my answer, but it's entirely i'm not using the correct terminology so feel free to smack me on the back of the head and link me to the correct page if I missed it :) What I am doing is searching a table for a specific item, in this case a MAC address. if it's not found, I want to echo "not found"; If it is found, I want to check another row for the date of that MAC. if the date is older than specified, then echo "recall"; If the MAC is newer than the date, echo "MAC okay"; Here is a sample of what the able looks like: | mac | date | | 00-00-00-00-00-00 | 2014/10/17 | My form is written well, it's giving the correct info to the PHP, but here it is anyway: <form action="results.php"> mac id <input type="text" name="mac"> <input type="submit"> </form> and here is the PHP from results.php. It's connecting the table no issue. I think the core of the issue is my query: <?PHP $mac= $_POST[‘mac’]; include "connect.php"; $query = mysql_query(“SELECT mac,date FROM units WHERE mac='$mac'"); $results = $query->getResults(); if( sizeof($results) > 0 ){ // look up the documentation for date_diff, DateTime, and DateInterval. $interval = date_diff( $results[0]->date_built, new DateTime('2014/10/19') ); if( $interval->invert = 1 ){ // i think this is how to test for before/after, but double-check me. echo "recall"; } else { echo "unit okay"; } } else { echo "not found"; } ?> A: Assuming that you want to check against the current date, here is my attempt: include "connect.php"; $mac= $_POST[‘mac’]; $result = mysql_query("SELECT * FROM units WHERE mac='".$mac."'"); // query // no results if (!$result) { echo 'not found'; } else { $mac_date = $result[0]->date; // check if its newer if( strtotime($mac_date) > strtotime('now') ) { echo 'MAC ok'; } // check if its older if( strtotime($mac_date) < strtotime('now') ) { echo 'recall'; } }
{ "pile_set_name": "StackExchange" }
Q: OS X Mavericks lost my mail folders! After loading Mavericks it appears one of my mail folders, a key folder holding tax data has become completely borked. As you can see from the attached image I have duplicate home folders. I have already tried to rebuild this folder with no luck. Any other ideas? Posted @ Apple: https://discussions.apple.com/thread/5494468 A: Rule of thumb, use Time Capsule = Problem Solved. I ended up migrated to Fastmail.fm => Away from Google.
{ "pile_set_name": "StackExchange" }
Q: Java object assignment behaviour not consistent? According to this answer https://stackoverflow.com/a/12020435/562222 , assigning an object to another is just copying references, but let's see this code snippet: public class TestJava { public static void main(String[] args) throws IOException { { Integer x; Integer y = 223432; x = y; x += 23; System.out.println(x); System.out.println(y); } { Integer[] x; Integer[] y = {1,2, 3, 4, 5}; x = y; x[0] += 10; printArray(x); printArray(y); } } public static <T> void printArray(T[] inputArray) { for(T element : inputArray) { System.out.printf("%s ", element); } System.out.println(); } } Running it gives: 223455 223432 11 2 3 4 5 11 2 3 4 5 A: The behavior is consistent. This line: x += 23; actually assigns a different Integer object to x; it does not modify the value represented by x before that statement (which was, in fact, identical to object y). Behind the scenes, the compiler is unboxing x and then boxing the result of adding 23, as if the code were written: x = Integer.valueOf(x.intValue() + 23); You can see exactly this if you examine the bytecode that is generated when you compile (just run javap -c TestJava after compiling). What's going on in the second piece is that this line: x[0] += 10; also assigns a new object to x[0]. But since x and y refer to the same array, this also changes y[0] to be the new object.
{ "pile_set_name": "StackExchange" }
Q: Is there an easy way to remove silicone sealant? Is there an easy way to remove silicone sealant? Having had mouldy sealant have replaced with MicroBan to stop the mould coming back but is there any tips on getting the stuff off for next time? My best tool seemed to be a sharp chisel. A: I've used a craft knife to cut out most of it (being careful not to damage the surface), then a small (2") putty knife to scrape out the rest. Nylon scrubbing pads (the ones made for cleaning non-stick cookware) are great for getting rid of any last traces of the old caulk. A chisel would work, but chisels are supposed to be very sharp, so I'd be very careful not to scratch whatever surface the caulk is applied to. A putty knife isn't as sharp so it would take more work on your part to do any damage.
{ "pile_set_name": "StackExchange" }
Q: Does flock() only apply to the current method? Does the flock() function only work if it is used within the same method that the code is executed? For example, in the following code, the lock is successful: public function run() { $filePointerResource = fopen('/tmp/lock.txt', 'w'); if (flock($filePointerResource, LOCK_EX)) { sleep(10); } else { exit('Could not get lock!'); } } However, in the following code, the lock is unsuccessful: public function run() { if ($this->lockFile()) { sleep(10); } else { exit('Could not get lock!'); } } private function lockFile() { $filePointerResource = fopen('/tmp/lock.txt', 'w'); return flock($filePointerResource, LOCK_EX); } I haven't seen any documentation on this, so I am puzzled by this behavior. I am using php version 5.5.35. A: I think the issue with your class based attempt is that when the lockFile method finishes the $filePointerResource goes out of scope and that is probably what is releasing the lock This works which sort of supports that theory <?php class test { public function run() { $fp = fopen('lock.txt', 'w'); if ($this->lockFile($fp)) { echo 'got a lock'.PHP_EOL; sleep(5); } /* * Not going to do anything as the attempt to lock EX will * block until a lock can be gained else { exit('Could not get lock!'.PHP_EOL); } */ } private function lockFile($fp) { return flock($fp, LOCK_EX); } } $t = new test(); $t->run(); So if you want to lock the file over more than one call to a class method it might be better to keep the filehandle as a class property, then it will remain in scope as long as the class is instantiated and in scope. <?php class test { private $fp; public function run() { $this->fp = fopen('lock.txt', 'w'); if ($this->lockFile()) { echo 'got a lock'.PHP_EOL; sleep(5); } /* * Not going to do anything as the attempt to lock EX will * block until a lock can be gained else { exit('Could not get lock!'.PHP_EOL); } */ } private function lockFile() { return flock($this->fp, LOCK_EX); } } $t = new test(); $t->run();
{ "pile_set_name": "StackExchange" }
Q: implicit declaration of function 'getaddrinfo' on Windows with Mingw I'm trying to create a really basic client application, based on the code on msdn but i get the error in the title. Here is the complete code: #include <tchar.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #pragma comment (lib, "Ws2_32.lib") #define DEBUG 1 #define DEFAULT_BUFLEN 512 #define DEFAULT_PORT "9001" void CreateSocket(); int main(int argc, char* argv[]) { CreateSocket(); return 0; } void CreateSocket() { WSADATA wsaData; SOCKET ConnectSocket = INVALID_SOCKET; struct addrinfo *result = NULL, *ptr = NULL, hints; char *sendbuf = "this is a test"; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result); ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); freeaddrinfo(result); iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 ); closesocket(ConnectSocket); WSACleanup(); } I'm on Windows 10, with MinGW. This the complete compile and error: gcc -Wall -o "test" "test.c" -lws2_32 (nel direttorio: C:\Users\FedericoPonzi\Google Drive\Programmazione\C\ProgrammazioneDiSistema\FedericoPonzi-programmazionedisistema-40c332bcd001\FedericoPonzi-programmazionedisistema-40c332bcd001\Prove) test.c:10:0: warning: ignoring #pragma comment [-Wunknown-pragmas] #pragma comment (lib, "Ws2_32.lib") ^ test.c: In function 'CreateSocket': test.c:46:2: warning: implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration] iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result); ^ test.c:52:2: warning: implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration] freeaddrinfo(result); ^ test.c:35:6: warning: variable 'iResult' set but not used [-Wunused-but-set-variable] int iResult; ^ C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o:test.c:(.text+0xbb): undefined reference to `getaddrinfo' C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o:test.c:(.text+0x11b): undefined reference to `freeaddrinfo' c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o: bad reloc address 0x20 in section `.eh_frame' c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation collect2.exe: error: ld returned 1 exit status Compilazione fallita. I'm using Geany as IDE. Also: why do i get the "ignoring pragma" error? Thanks. A: About warning: ignoring #pragma comment [-Wunknown-pragmas] #pragma comment (lib, "Ws2_32.lib") #pragma comment(lib,"xxx.lib") is microsoft c/c++ compiler specific. GCC does not support it. About implicit declaration of function Simply #define _WIN32_WINNT 0x0501 before your include, due to #if (_WIN32_WINNT >= 0x0501) void WSAAPI freeaddrinfo (struct addrinfo*); int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*, struct addrinfo**); int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD, char*,DWORD,int); #else /* FIXME: Need WS protocol-independent API helpers. */ #endif in ws2tcpip.h file.
{ "pile_set_name": "StackExchange" }
Q: What is the most "space effective" way to store text in MySQL? I have +10 million articles(200 to 1000 words) in a InnoDB table. I only use this type of query when I'm working with article field: SELECT article,title,other_fields from table where id=123; What is the most "space effective" way to store text in MySQL? Now the table size is say 100GB, my objective is to make that as little as possible without causing too much performance tradeoff. A: MyISAM is more space friendly than InnoDB, you can start with that one.
{ "pile_set_name": "StackExchange" }
Q: Meta descriptions for paginated single posts I'm using the popular Wordpress SEO by Yoast plugin. I can use a wildcard (%%page%%) for the title of paginated posts, so that the title becomes: 1st post page: The Title 2nd post page: The Title - Page 2 of 3 3rd post page: The Title - Page 3 of 3 I thought I could do the same with meta description, but no. I could use a filter to change the meta description to show on these pages, as the title does, but I'm not sure if it's a good idea, since this plugin doesn't seem to care about this. This plugin has an option to "noindex" the "next pages", but only works with archive pages (categories, tags, lasts posts), so all pages with a slug like /page/{num} will be "noindex", but not the slug for paginated single posts /a-post-URL/{num}. The question is how should the paginated single post's meta description be treated. "noindex"? Like the example above for titles? Any ideas? A: I would leave everything as is and let SEO by Yoast do the work for you. You should use rel="canonical" on your subsequent pages or rel="prev" and rel="next". Or you can use both. Here is what Google recommends: In cases of paginated content, we recommend either a rel=canonical from component pages to a single-page version of the article, or to use rel=”prev” and rel=”next” pagination markup. Here is an example: <link rel="canonical" href="http://domain.com/article/"> OR (if you are on /article/2/ and etc.) <link rel="prev" href="http://domain.com/article/"> <link rel="next" href="http://domain.com/article/3/"> I would check out this article as well. Indicate paginated content. You can actually use both. Which is what SEO by Yoast is using. From the above mentioned article: rel="next" and rel="prev" are orthogonal concepts to rel="canonical". You can include both declarations. Here is an example (if you were on page 2): <link rel="canonical" href="http://domain.com/article/2/"> <link rel="prev" href="http://domain.com/article/"> <link rel="next" href="http://domain.com/article/3/">
{ "pile_set_name": "StackExchange" }
Q: Maven 3.5 doesn't find $JAVA_HOME despite the env variable was set I am trying to run Maven 3.5 on my Ubuntu 16.04 desktop VM. I installed JDK 8 and set $JAVA_HOME and added the path. Despite this, Maven cannot find it. Here is the output: root@ubuntu:/# echo $JAVA_HOME opt/jdk1.8.0_131/bin/java root@ubuntu:/# echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:opt/jdk1.8.0_131/bin:opt/apache-maven-3.5.0/bin root@ubuntu:/# mvn -v The JAVA_HOME environment variable is not defined correctly This environment variable is needed to run this program NB: JAVA_HOME should point to a JDK not a JRE Any ideas? A: JAVA_HOME should point to the JDK/JRE installation directory rather than to the java executable. In your case, that seems to be /opt/jdk1.8.0_131/ (the leading / is important, in its absence every software will try to access an opt directory in its current working directory) Then you can append $JAVA_HOME/bin to the PATH, which has correctly been done in your case but apparently does not matter to Maven.
{ "pile_set_name": "StackExchange" }
Q: Do Korean sentences always end with a verb-like word? I know Korean grammar usually requires sentences to end in a 'verby' word like an action verb (동사), descriptive verb (형용사), or 되다 (to become) or 이다(to be something). But can correct, full Korean sentences ever end in something else? A: It is reasonable to say that since full, grammatically correct English sentences (besides the usual one word "Yes.", "No.", and "Hello." expressions) always come with some form of verb, the same can be said for Korean. However, comparisons to English might not be so sound since Korean and English are quite different. So, let's jump into something more universal: linguistics! The notion that a sentence needs to have a verb or adjective is slightly incorrect only because several types of sentences exist. Thus, it's only fair to say that in any language, grammatically correct sentences can come in verb-less forms (See "Major and minor sentences" section of the wiki page). But, in terms of simple sentences (sentences that do contain at least one subject and one predicate), it would be against that very definition of a grammatically correct sentence to come in a predicate-less form. TL;DR Yes and no
{ "pile_set_name": "StackExchange" }
Q: Passing dependency to wrapper object via its constructor I have the following test: TestGet(): _interface(), _db(_interface) { _interface.get = mockGet; } which is used when testing this class: class DB: public IDB { public: explicit DB(Interface_T& interface): _interface(interface) { } ... private: Interface_T _interface; }; Interface_T is a C interface implemented in a struct and passed to me from a C api. I wish to use the DB class as a wrapper around the C interface. Notice however that DB copies the interface object to its member _interface. Therefore the line: _interface.get = mockGet; has no effect from the DB objects point of view although this was the intention when I wrote the test class. How would you rewrite TestGet() to remedy this error? How would you present to the client of the DB class that it copies the value passed to it? A: Presuming that your intention is for TestGet to set a member on the Interface_T object used by DB, you can: A. Defer construction of DB: TestGet(): _interface(), _db(NULL) { _interface.get = mockGet; // Using a raw pointer here for minimalism, but in practice // you should prefer a smart pointer type. _db = new DB(_interface); } B. If you have control over the Interface_T class, you could add a constructor that initializes Interface_T::get directly. Then you could do: TestGet(): _interface(mockGet), _db(_interface) { } C. If you have control over the DB class, you could change it to share ownership of the supplied Interface_T (e.g. through boost::shared_ptr), add a constructor as in B, or add an accessor to its internal Interface_T member.
{ "pile_set_name": "StackExchange" }
Q: Check for null in my LINQ query Afternoon, I cant seem to work out how to ignore if the following line is null where ((double)t.twePrice >= priceFrom && (double)t.twePrice <= (priceTo)) As you can see in my code below i am able to do this when its a string. But I am having issues with the prices one. Could someone please shed some light for me? from a in dc.aboProducts join t in dc.tweProducts on a.sku equals t.sku where (string.IsNullOrEmpty(productSku) || productSku == t.sku) where (string.IsNullOrEmpty(productAsin) || productAsin == a.asin) where (string.IsNullOrEmpty(productName) || t.title.Contains(productName)) where (string.IsNullOrEmpty(productBrand) || t.brand.Contains(productBrand)) where ((double)t.twePrice >= priceFrom && (double)t.twePrice <= (priceTo)) select new GetProducts UPDATE: I am basically sending over a load of items to search my MS SQL Database, Some of these may be NULL as per the strings. The prices may also be null as are not needed all the time. So if the prices are null, i dont need to use them. Many thanks. A: Maybe the following might be enough: where ((priceFrom == null || (double)t.twePrice >= priceFrom) && (priceTo == null || (double)t.twePrice <= priceTo)) For readability it might break in two: where (priceFrom == null || (double)t.twePrice >= priceFrom) where (priceTo == null || (double)t.twePrice <= priceTo)
{ "pile_set_name": "StackExchange" }
Q: Creating a Dropdown Menu with CSS Not Working The dropdown menu (sub) does not appear right below the element it is supposed to when I hover on the navbar. How can I get it to appear below it instead of to the right of it? Also, how can I get the extra spacing on the left side of each menu to disappear? I tried setting the padding to 0, but that did not change anything. a { text-decoration: none; color: #000; } .navbar { background-color: #f2f2f2; position: fixed; top: 0; width: 100%; text-align: center; font-family: "Raleway"; font-size: 93%; border-width:1px 0; list-style:none; margin:0; padding:0; left: 0; } .navbar > li{ display:inline-block; } .navbar li { list-style-type: none; padding-left: none; } .navbar a { float: center; display:inline-block; color: #000000; text-align: center; padding: 14px 16px; text-decoration: none; } .navbar a:hover { background-color: #ddd; } .navbar li:hover ul.sub { display: inline-block; } .dropdown { position: relative; display: inline-block; } ul.sub { padding-left: none; position: absolute; background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } ul.sub a { color: #000000; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } <ul class = "navbar"> <!--add dropdown menu links for everything except collaboration--> <li class = "dropdown"> <li><a href ="project.html">About FRES(H)</a> <ul class = "sub"> <li><a href = "safety.html">Safety</a></li> <li><a href = "sense.html">Sense</a></li> <li><a href = "express.html">Express</a></li> <li><a href = "fresh.html">Keep Fresh</a></li> <li><a href = "notebook.html">Notebook</a></li> <li><a href = "interlab.html">Interlab</a></li> <li><a href = "protocols.html">Protocols</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="modelling.html">Models</a> <ul class = "sub"> <li><a href = "etnr1.html">Protein Modelling Etnr1</a></li> <li><a href = "etnr2.html">Protein Modelling Etnr2</a></li> <li><a href = "internal.html">Internal Cellular Model</a></li> <li><a href = "diffusion.html">Macroscopic Diffusion Model</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="software.html">Technology</a> <ul class = "sub"> <li><a href = "primer.html">Primer Design App</a></li> <li><a href = "smartphone.html">SmartPhone App</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="humanpractices.html">Human-Centered Design</a> <ul class = "sub"> <li><a href = "human.html">Integrated Human Practices</a></li> <li><a href = "outreach.html">Outreach</a></li> <li><a href = "knowledgetheory.html">Theory of Knowledge</a></li> </ul> </li> </li> <li><a href ="http://2016.igem.org/Team:Sydney_Australia/Collaboration">Engagement</a></li> <li class = "dropdown"> <li><a href ="team.html">Meet the Team</a> <ul class = "sub"> <li><a href = "about.html">About Us</a></li> <li><a href = "attributions.html">Attributions</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="achievements.html">Awards</a> <ul class = "sub"> <li><a href = "parts.html">Parts</a></li> <li><a href = "medals.html">Medals</a></li> </ul> </li> </li> </ul> A: You were almost there! You just added the :hover to the wrong div. Make the following changes: display:none to ul.sub and .navbar li:hover ul.sub instead of .navbar:hover ul.sub UPDATE: to centre the ul.sub, use display: block. To remove padding, assign value of 0, instead of 'none'. See example below: a { text-decoration: none; color: #000; } .navbar { background-color: #f2f2f2; position: fixed; top: 0; width: 100%; text-align: center; font-family: "Raleway"; font-size: 93%; border-width:1px 0; list-style:none; margin:0; padding:0; left: 0; } .navbar > li{ display:inline-block; } .navbar li { list-style-type: none; padding-left: none; } .navbar a { float: center; display:inline-block; color: #000000; text-align: center; padding: 14px 16px; text-decoration: none; } .navbar a:hover { background-color: #ddd; } .navbar li:hover ul.sub { display: block; } .dropdown { position: relative; display: inline-block; } ul.sub { padding-left: 0; position: absolute; background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; display:none; } ul.sub a { color: #000000; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } <ul class = "navbar"> <!--add dropdown menu links for everything except collaboration--> <li class = "dropdown"> <li><a href ="project.html">About FRES(H)</a> <ul class = "sub"> <li><a href = "safety.html">Safety</a></li> <li><a href = "sense.html">Sense</a></li> <li><a href = "express.html">Express</a></li> <li><a href = "fresh.html">Keep Fresh</a></li> <li><a href = "notebook.html">Notebook</a></li> <li><a href = "interlab.html">Interlab</a></li> <li><a href = "protocols.html">Protocols</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="modelling.html">Models</a> <ul class = "sub"> <li><a href = "etnr1.html">Protein Modelling Etnr1</a></li> <li><a href = "etnr2.html">Protein Modelling Etnr2</a></li> <li><a href = "internal.html">Internal Cellular Model</a></li> <li><a href = "diffusion.html">Macroscopic Diffusion Model</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="software.html">Technology</a> <ul class = "sub"> <li><a href = "primer.html">Primer Design App</a></li> <li><a href = "smartphone.html">SmartPhone App</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="humanpractices.html">Human-Centered Design</a> <ul class = "sub"> <li><a href = "human.html">Integrated Human Practices</a></li> <li><a href = "outreach.html">Outreach</a></li> <li><a href = "knowledgetheory.html">Theory of Knowledge</a></li> </ul> </li> </li> <li><a href ="http://2016.igem.org/Team:Sydney_Australia/Collaboration">Engagement</a></li> <li class = "dropdown"> <li><a href ="team.html">Meet the Team</a> <ul class = "sub"> <li><a href = "about.html">About Us</a></li> <li><a href = "attributions.html">Attributions</a></li> </ul> </li> </li> <li class = "dropdown"> <li><a href ="achievements.html">Awards</a> <ul class = "sub"> <li><a href = "parts.html">Parts</a></li> <li><a href = "medals.html">Medals</a></li> </ul> </li> </li> </ul>
{ "pile_set_name": "StackExchange" }
Q: How can i intersection two ActiveRecord Relation objects by rails? I need to find the intersection result of two ActiveRecord Relation objects. This is my Controller if params.has_key?(:car_insurance_type_id) car_insurance_type = CarInsuranceType.find_by(id: params[:car_insurance_type_id]) else car_insurance_type = CarInsuranceType.find_by(id: 1) end @breadcrumb_title = car_insurance_type.title car_insurance_objects_private = car_insurance_type.car_insurance_objects if params.has_key?(:car_model_id) car_model_search = CarModel.find_by(id: params[:car_model_id]) if car_model_search car_insurance_objects_from_model = car_model_search.car_insurance_objects end end car_insurance_objects_private = car_insurance_objects_private & car_insurance_objects_from_model But "&" method didn't work for ActiveRecord object This is my model class CarInsuranceType < ActiveRecord::Base has_many :car_insurance_objects ,dependent: :destroy end class CarInsuranceObject < ActiveRecord::Base belongs_to :insurance_company belongs_to :car_insurance_type has_and_belongs_to_many :car_models end class CarModel < ActiveRecord::Base belongs_to :car_brand has_and_belongs_to_many :car_insurance_objects ,dependent: :destroy end So how can i find the intersection result between two CarInsuranceObject that one belongs_to car_insurance_type and another one that has_and_belongs_to_many car_models? Thanks! A: As far as I understand, you need to query DB for CarInsuranceObject's of specified CarInsuranceType and CarModel. Why not to simplify all this stuff: car_insurance_type_id = params[:car_insurance_type_id] || 1 car_insurance_objects_private = car_model_search.car_insurance_objects.where(car_insurance_type_id: car_insurance_type_id) Btw, there is really long names for variables.
{ "pile_set_name": "StackExchange" }
Q: Search Builder is broken (Civi 5.4.0 / Drupal 7.59) Search Builder is broken : I don't have any "Select field", but only "Select Record Type" and "Operator" (sorry for the image in french) : You can reproduce this bug on the demo configuration (civicrm.demo.civihosting.com, in 5.0.0), this way : Search Builder > Select "Individual", then go to Support > About CiviCRM, and then back : "Select Field" has disappeared : on my configuration, I have the same situation, but directly, without this forth and back operation. A: best to compare with dmaster.demo.civicrm.org/civicrm/contact/search/builder?reset=1 i think as that will be running on latest code for certain (to avoid reporting a bug that has already been fixed)
{ "pile_set_name": "StackExchange" }
Q: Reuse custom UITableViewCell, how to get text of each cell's textfield to save? I have a custom UITableViewCell whose Nib has a label, a seperator and a textfield (very much like the contact app phone number cell). I have a detail tableview which uses this custom cell for a lot of rows. I do a switch case through sections and rows to set the cell's label and textfield place holder programatically. I want to set the textfields text to my NSManagedObject properties in the ViewWillDisappear. What's the best way to capture the text in the textfields of the custom cells in different rows/sections? A: for(int i = 0; i < [tableView numberOfRowsInSection:0]; i++) { NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0]; customTableCell *cell = (customTableCell *)[tableView cellForRowAtIndexPath:index]; NSString *textFieldVal = [cell.textLabel text]; } A: Set the controller as delegate of the textfields and set different tag on each field, I was then able to set the text value of the fields to my NSMangedObjects attributes via the textFieldDidEndEditing protocol.
{ "pile_set_name": "StackExchange" }
Q: How to resolve Oracle RemoteOperationException: Error reading error from command I have recently been receiving the following error whenever I am asked to supply the host username and password in Oracle DataGuard's Enterprise Manager (EM) tool: RemoteOperationException: Error reading error from command. Any configuration or management that needs to be performed and requires the host credentials is throwing this error. This is one of the most unhelpful errors I have seen in a long time. I have checked all of the log files I can think of and I can't find any error logs or indications to the problem. I verified that I can log into the servers with the credentials that I was trying in EM, I verified the connection configuration through EM using the built in test tools, and I verified that all of the saved passwords in EM were correct. This was working on the initial installation. Sometime over the last couple of weeks it stopped working and I'm not sure why. The hosts are running Linux Red Hat 4 Enterprise and Oracle 10g. A: Reinstalling the OEM agents fixed this issue. Somehow, all of the agents seemed to be corrupt.
{ "pile_set_name": "StackExchange" }
Q: JSF:Javascript google maps API - markers get the same title Im probably doing something dumb here but I can't figure out why both of my markers end up with the same title. Both markers end up with the correct location from the geocoder and are displayed in separate places. Before render function gMapInitialize() { var myLocs = [<ui:repeat value = "#{LocationBean.locations.address}" var = "loc" varStatus = "loop"> [ "#{loc.name}","#{loc.street}","#{loc.city}","#{loc.state}", "#{loc.zipCode}"]#{!loop.last ? ',' : ''} </ui:repeat>]; //<![CDATA[ var myOptions = { center: new google.maps.LatLng(37.212832,-76.750488), zoom: 8, mapTypeId: google.maps.MapTypeId.HYBRID }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var geocoder = new google.maps.Geocoder(); for(var i = 0; i < myLocs.length; i++){ var myLoc = myLocs[i]; var geoOptions = { address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4], } geocoder.geocode( geoOptions ,function(results, status){ if(status == google.maps.GeocoderStatus.OK){ var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: myLoc[0], zIndex: i }); } }); } } // ]]> After Render: function gMapInitialize() { var myLocs = [ [ "Richmond","9 North 3rd Street","Richmond","VA", "23219"], [ "Hampton Roads","632 North Witchduck Road","Virginia Beach","VA", "23462"] ]; //<![CDATA[ var myOptions = { center: new google.maps.LatLng(37.212832,-76.750488), zoom: 8, mapTypeId: google.maps.MapTypeId.HYBRID }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var geocoder = new google.maps.Geocoder(); for(var i = 0; i < myLocs.length; i++){ var myLoc = myLocs[i]; var geoOptions = { address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4], } geocoder.geocode( geoOptions ,function(results, status){ if(status == google.maps.GeocoderStatus.OK){ var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: myLoc[0], zIndex: i }); } }); } } // ]]> Am I trying to do too much in one loop? I keep hearing something about closure but am new to javascript and know nothing about it. Ohh yeah: I get the second of the two names on each marker. The markers are in the right position but both are titled "Hampton Roads". So, the right info is being passed to the title, but its as if title of the first is being overwritten with the title of the second. UPDATE Well, I fixed it and I think I understand a bit more about closure. So mainly the loop keeps looping and by the time the function is called its already at the end. So even in the below, each marker will probably have the same zIndex and I should pass the "i" as well. for(var i = 0; i < myLocs.length; i++){ var myLoc = myLocs[i]; var geoOptions = { address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4], } geocoder.geocode( geoOptions ,addMarkers(myLoc[0])); } function addMarkers(myTitle){ return function(results,status){ if(status == google.maps.GeocoderStatus.OK){ var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: myTitle, zIndex: i }); } }; } A: It's a simple closure issue. myLoc[i] refers to the same entity after the loop ends in both cases. Just wrap it in a function to create a new scope: for(var i = 0; i < myLocs.length; i++){ (function(num) { var myLoc = myLocs[num]; var geoOptions = { address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4], } geocoder.geocode( geoOptions ,function(results, status){ if(status == google.maps.GeocoderStatus.OK){ var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: myLoc[0], zIndex: num }); }(i)); }
{ "pile_set_name": "StackExchange" }
Q: SSRS Dynamic Borders I have the following output which is bound to a SSRS table: ID Name Value 1 Assets 100 2 Liabilities 200 3 Expenses 300 4 Loans 400 5 TOTAL 1000 For the last row (TOTAL), which is the grand total of the above rows, and also a part of the result, I want to set the border conditionally as follows: Top border: Dotted Bottom border: Double-dashed The last row in the report must look something like this: ---------------- TOTAL 1000 ================ Appreciate your inputs. A: Unfortunately, SSRS does not have a double-dashed option, but you can use conditional formatting on the textbox to control the border. With your data: I have a simple table: For the detail row, I have set the Top and Bottom border style to be expression-based, based on the value of Name: Top: =IIf(Fields!Name.Value = "TOTAL", "Dashed", "None") Bottom: =IIf(Fields!Name.Value = "TOTAL", "Double", "None") This gives (very close to) the desired result: However, be aware that you might run into a few issues, as identified in this MSDN thread: Double Line border turn to be single in Reporting Service I had to make sure the Bottom border was 3pt in width and that there was a table footer row to get it to look correct in Preview. Excel works fine whatever.
{ "pile_set_name": "StackExchange" }
Q: How to retrieve a recent list of trashed files using Google Drive API I have recently deleted quite a number of files in Google Drive, and they were moved to the trash. I would like to permanently delete them, but the files in the Trash can't be sorted by Deleted Date, but only Modified Date (which is not updated upon delete). Therefore, I would like to leverage the Google Drive API to enumerate the trash and determine the date it was trashed, to find the set of files I would like to subsequently permanently delete. From what I can gather, there is a file property which indicates if it has been trashed, but not the date. I tried searching for this answer, but it's not easy to find, if it is possible. Is anyone familiar with this area of the API? Is there a better strategy than what I am attempting? A: Using Todd's detailed answer, I wrote a Python script to achieve this. It's published on GitHub (cfbao/google-drive-trash-cleaner). E.g. to view items trashed in the last 30 days, run python cleaner.py -v -d 30 or cleaner.exe -v -d 30 on Windows Edit: Oops! big mistake! clean -v -d 30 shows you files trashed more than 30 days ago. If you want to see files trashed in the last 30 days, run clean -v -d 0 and see all trashed files sorted by their trash date. Or you can modify my script so -d 30 means "in the last 30 days". Shouldn't be too big a modification. A: Directly using https://developers.google.com/drive/v3/reference/changes/list, you can retrieve your most recent file/folder changes. This would seem to list those changes for folder movements as well as trashed files. Getting the data: Get a page token from - https://developers.google.com/drive/v3/reference/changes/getStartPageToken Put that token into - https://developers.google.com/drive/v3/reference/changes/list, with page size of 500, includeRemoved on true, and select all fields with the fields editor link button. You will see no results, because you are using the most recent page token. You need to manually reduce the page token until the returned changes.time is before the desired date range. (There is no filter for this in the query). Once you have established the correct page token, continue with the steps below. Before Executing, open the Developer Tools (I was using Chrome) and view the Network section Look for a transfer name staring with "changes?pageToken=...", and select it, copy the Response to Notepad++ Note the nextPageToken field, and update the requested page token, repeating step 5 until the nextPageToken not longer advances. I used http://www.jsonquerytool.com/ to paste the data from notepad++ and to query out and find the relevant fileids. Querying the data for IDs (for each of the results returned): Paste the JSON into the JSON section Select JSPath Query Type Use this query to double-check document name ".changes{.file.trashed === true}.file.name" Use this query to get ID list to keep ".changes{.file.trashed === true}.file.id" Copy Results to Notepad++ Permanent Deleting If you have a small amount of FileIDs (< 100), you may wish to manually run them through https://developers.google.com/drive/v3/reference/files/delete, and optionally check them with https://developers.google.com/drive/v3/reference/files/get on each manual iteration. Automation Obviously, if you're dealing with more data it would make sense to write a Script or App to accomplish the above. But at least you can see it's possible.
{ "pile_set_name": "StackExchange" }
Q: RAML 1.0 ciclical nested includes I have this issue, I have created two libraries to define two different types, here they are: Category.raml #%RAML 1.0 Library uses: - Event: !include Event.raml - Tournament: !include Tournament.raml types: ############################################################################# base: usage: The base type for a category properties: min_age: description: The minimum age to participate in the category required: true type: number max_age: description: The maximum age to participate in the category required: true type: number name: description: The name of the category required: true type: string gender: description: The gender of the category required: true enum: - male - female - mix tournament: description: The tournament of the category required: true type: Tournament.base ############################################################################# full: usage: A category with all of its events type: base properties: events: description: The events that the category contains required: true type: Event.base[] Tournament.raml #%RAML 1.0 Library uses: - ClubInscription: !include Club.raml - Category: !include Category.raml types: ############################################################################# base: usage: The base type for the tournament properties: name: description: The name of the tournament required: true type: string date: description: Date of the tournament required: true type: string available_lanes: description: Maximum number of lanes in a serie required: true type: number max_swimmer_inscriptions: description: Maximum number of events a swimmer may be inscripted required: true type: number award_type: description: The type of awarding used in the competition required: true enum: - points - medals - none state: description: The current state of the tournament required: true enum: - closed - open - finished ############################################################################# full: usage: A tournament with all its categories and club inscriptions type: base properties: club_inscriptions: description: The clubs inscripted in the tournament required: true type: ClubInscription.base[] categories: description: The categories the tournament has required: true type: Category.base[] Having this, it makes sense having a conflict. I am pretty knew at RAML, so I read somewhere that "uses" should only be used when using something as a parent, but then what should I do to not re-write everything in everywhere in my project (because this happens everywhere in it). I have thought of defining the base of the types in one file, but it would be just a mix of information that should not be together, I want to know if there is an alternative to "uses" to re-use the types in another file. Thanks in advance. A: The simplest solution is make: TournamentBase.raml TournamentFull.raml CategoryBase.raml CategoryFull.raml You will not have circular dependencies.
{ "pile_set_name": "StackExchange" }
Q: Safari - Content not displaying correctly, CSS position error? In safari and some other browsers, my footer isnt sticking correctly. It looks to me like it must be something todo with either positioning or float. Would someone mind taking a look please? Have been pulling my hair out trying to solve this. http://r.adamtoms.co.uk Many Thanks! Adam A: I found another error that makes the footer stick correctly.. You got /* W3C */ display: inline-flex; Fix /* Safari, Opera, and Chrome */ display: -webkit-inline-box; For moz /* Firefox */ display: -moz-inline-box; Did test it and it works.
{ "pile_set_name": "StackExchange" }
Q: When does the helicopter homie respawn? Related: How can I speed up the cooldown for the helicopter homie? I called in a helicopter homie to bring some hurt during a police assault, but the homie never appeared. Now, it's been almost a half hour of real-time gameplay and the option is still grayed out in my phone menu. If it makes a difference, I'm playing on PC. Is my game bugged or does it just take an eternity to whistle up new helicopters? A: After about 35 minutes. Here're my notes: "1 minute and 46.2 seconds to land the chopper (split at when I saw him begin to leave the chopper). He was caught for a bit and my walking a bit finally made him move again. For a little over 21 seconds later, he stayed on screen, walking, before going beyond a corner and out of my line of sight. Timer started when I sent the command to confirm calling the homie. I'm not touching the chopper. I'm afraid that the existence of the chopper will mean that the helicopter homie won't respawn. I'll check at 5 minutes. As I tried to get a car to stand beside for the radio, the chopper despawned. I stay on foot in case it's similar to survival calls. Helicopter homie hasn't respawned after five minutes. About 5 seconds lost in phone. Checking again at 6 minutes (timer, not adjusted). 4.8 seconds lost from the second check. I'll check again at 10 minutes. I think chopper despawned at 3 minutes, approximately. I called the chopper just outside of the first crib (apartment of Shaundi's ex). 5.8 seconds lost on 10 minute check. About 3 seconds lost on minimum bandwidth warning. Empty 15:20, lost maybe another 3-4 seconds. Lost 5.6 seconds at 20:10. 4 seconds off from 25:00 check. 4 seconds off from 30:10 check. 4.8 seconds off from 35:20 check. Ooh, respawned a little before 40:05.3. Math: 60*40+5.3-(60+46.2)-21-5-4.8-5.8-3-3.5-5.6-4-4-4.8 = 2237.6 seconds = 37.29¯3 minutes. The number changes depending on stuff like if cooldown only begins when chopper despawns, cut around 3 minutes, if cooldown only begins when homie despawns, cut about 10 seconds, if cooldown only begins when homie leaves chopper, if cooldown begins right after phone closes from call, etc.." In terms of fixing the homie if it's glitched such that they never respawn, you must have another player call the homie for you. Otherwise, the Homie article on the Saints Row Wiki suggests altering the game files.
{ "pile_set_name": "StackExchange" }
Q: Find all like attributes in document, and change output based on value I've been working on this list that will provide information from an xml file. The markup I'm working with is as follows: <?php $xml_file = '/path'; $xml = simplexml_load_file($xml_file); foreach($xml->Continent as $continent) { echo "<div class='continent'>".$continent['Name']."<span class='status'>".$continent['Status']."</span>"; foreach($continent->Country as $country) { echo "<div class='country'>".$country['Name']."<span class='status'>".$country['Status']."</span>"; foreach($country->City as $city) { echo "<div class='city'>".$city['Name']."<span class='status'>".$city['Status']."</span></div>"; } echo "</div>"; // close Country div } echo "</div>"; // close Continent div } ?> What I'm trying to accomplish is changing the 'Status'. Regardless of the element, the 'Status' only has two values and will always be either "Red" or "Blue". What I'm trying to do is go through the whole document, find the "Status" attribute, see if the value is "Red", then display an icon or some text, but if it's blue, display nothing. I've come across different examples, but none that show this type of generality. Most of the examples were for locating a specific node and then displaying it's attributes. I'm also trying to avoid, if possible, having to create this rule within each loop, but instead applying it to the whole document (if this seems like the best method.) A: Use css selectors instead of javascript. That will make your code lighter and simple! For example: <?php $xml_file = '/path'; $xml = simplexml_load_file($xml_file); foreach($xml->Continent as $continent) { echo "<div class='continent'>".$continent['Name']."<span class='status ". cssForStatus($continent['Status'])."'></span>"; foreach($continent->Country as $country) { echo "<div class='country'>".$country['Name']."<span class='status ". cssForStatus($country['Status'])."'></span>"; foreach($country->City as $city) { echo "<div class='city'>".$city['Name']."<span class='status ". cssForStatus($city['Status'])."'></span></div>"; } echo "</div>"; // close Country div } echo "</div>"; // close Continent div } function cssForStatus($status='') { switch ($status) { case 'red': $css = "red"; break; default: $css = "blue"; break; } return $css; } while your css can be: span.status { height: 10px; width: 10px; } span.status.red { background-color: "red"; } span.status.blue { background-color: "blue"; } we are using the concept of multiple css classes
{ "pile_set_name": "StackExchange" }
Q: QComboBox в заголовке QTableWidget Как поместить QComboBox в заголовок таблицы QTableWidget? A: Задача отнюдь не тривиальна, несмотря на кажущуюся на первый взгляд простоту. Начать нужно с того, что в заголовок QTableWidget (да и любого другого аналогичного виджета) совсем не просто вставить что-либо, отличное от того, что там обычно присутствует. Связано это с тем, что заголовок - это не просто надпись, а множество элементов, соединённых вместе, каждый из которых имеет своё функциональное назначение, будь то стрелочка сортировки или границы для подгонки размера колонки. Нельзя не упомянуть и о различии стилей рисования. Всё это приводит к тому, что если разработчик желает серьёзных изменений взамен стандартному поведению, то ему придётся "рисовать" заголовок с нуля, включая упомянутые составные части и, разумеется, опираясь на стиль, используемый в приложении. Для того, чтобы хотя бы начать, можно обратиться к QTableView, так как именно от него наследуется QTableWidget. В этом классе имеется возможность установки собственного горизонтального заголовка посредством вызова метода setHorizontalHeader(). Его аргументом является указатель на объект QHeaderView, в котором в свою очередь нужно унаследовать и переопределить метод QHeaderView::paintSection(). Например так: class MyHeaderView : public QHeaderView { Q_OBJECT public: explicit MyHeaderView(Qt::Orientation orientation , QWidget *parent = Q_NULLPTR) : QHeaderView(orientation, parent) {} protected: virtual void paintSection(QPainter *painter , const QRect &rect, int logicalIndex) const; }; void MyHeaderView::paintSection(QPainter *painter , const QRect &rect, int logicalIndex) const { QStyleOptionComboBox cbox_opt; cbox_opt.rect = rect; cbox_opt.state = QStyle::State_Active | QStyle::State_Enabled; cbox_opt.currentText = "tra-ta-ta"; QApplication::style() ->drawComplexControl(QStyle::CC_ComboBox, &cbox_opt, painter); QApplication::style() ->drawControl(QStyle::CE_ComboBoxLabel, &cbox_opt, painter); } QTableWidget tbl_wdg; tbl_wdg.setHorizontalHeader(new MyHeaderView(Qt::Horizontal,&tbl_wdg)); tbl_wdg.setWindowTitle("QTableWidget"); tbl_wdg.setEditTriggers(QAbstractItemView::AllEditTriggers); tbl_wdg.insertColumn(0); tbl_wdg.insertRow(0); tbl_wdg.show(); Получилось вот такое: Всё бы хорошо, но как бы мы не щёлкали по заголовку, список не раскроется - это всего лишь статичная картинка. Чтобы её оживить, придётся обратиться к исходникам QComboxBox, где довольно внушительного размера код отвечает за раскрытие списка элементов в одном методе (showPopup()) и скрытие в другом (hidePopup()). Приводить весь этот код нет никакого смысла, поскольку он легко доступен и к большому сожалению нужен весь целиком, частями не обойтись. Если нет желания заниматься рисованием и переносом кода из исходников Qt, то можно пойти на компромисс и вместо переопределения заголовка заняться подменой первой строки виджета таблицы или дерева. В конце концов, это большая экономия времени и сил в сравнении с тем, сколько придётся возиться с подменой заголовка, а затем, как вполне закономерное следствие, ещё и пытаться хоть как-то совместить часть стандартной функциональности с новоявленным внедрением. Хотя бы ту же сортировку, осуществляемую щелчком по заголовку. Почему бы не создать второй заголовок из первой строки таблицы. Это относительно легко делается при помощи делегата: #include <QtWidgets/QStyledItemDelegate> class Delegate : public QStyledItemDelegate { Q_OBJECT public: //! Constructor. explicit Delegate(QObject *parent = Q_NULLPTR) : QStyledItemDelegate(parent) {} virtual void paint(QPainter *painter , const QStyleOptionViewItem &option , const QModelIndex &index) const; virtual QWidget *createEditor(QWidget *parent , const QStyleOptionViewItem &option , const QModelIndex &index) const; }; void Delegate::paint(QPainter *painter , const QStyleOptionViewItem &option , const QModelIndex &index) const { QStyleOptionComboBox cbox_opt; cbox_opt.rect = option.rect; cbox_opt.state = QStyle::State_Active | QStyle::State_Enabled; cbox_opt.currentText = index.model()->data(index).toString(); QApplication::style() ->drawComplexControl(QStyle::CC_ComboBox, &cbox_opt, painter); QApplication::style() ->drawControl(QStyle::CE_ComboBoxLabel, &cbox_opt, painter); } QWidget *Delegate::createEditor(QWidget *parent , const QStyleOptionViewItem &option , const QModelIndex &index) const { QComboBox *cbox = new QComboBox(parent); cbox->setGeometry(option.rect); cbox->addItem("my text"); cbox->addItem("1"); cbox->addItem("2"); cbox->addItem("3"); return cbox; } Подключать просто: QTableWidget tbl_wdg; tbl_wdg.setWindowTitle("QTableWidget"); tbl_wdg.setEditTriggers(QAbstractItemView::AllEditTriggers); tbl_wdg.insertColumn(0); tbl_wdg.insertRow(0); tbl_wdg.setItem(0,0,new QTableWidgetItem("my text")); tbl_wdg.setItemDelegateForRow(0, new ADelegate(&tbl_wdg)); tbl_wdg.show(); Получается вполне себе работоспособный виджет:
{ "pile_set_name": "StackExchange" }
Q: This code always give an error of duplicate insertion - How to solve that? I am trying to create an insertion in some tables with random data but i have a problem with the duplicates. I wrote an insertion of random records in postgresql b but it returns duplicates detection and there should be no duplicates i am using every name for exactly 2680 times and the names are 22 for 58960 records total of table play_in please check and tell what's wrong with it and how does produce a duplicate. import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Random; public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; Statement stmt = null; int year; int year1; int num_rating; int num_ratingAvg; String[] round = new String[5]; round[0] = "32nd"; round[1] = "16th"; round[2] = "quarter_final"; round[3] = "SemiFinal"; round[4] = "FInal"; String[] name1 = new String[22]; name1[0] = "ahmed"; name1[1] = "mohamed"; name1[2] = "mai"; name1[3] = "salma"; name1[4] = "walid"; name1[5] = "wael"; name1[6] = "fadwa"; name1[7] = "nada"; name1[8] = "nahla"; name1[9] = "mustafa"; name1[10] = "ola"; name1[11] = "omar"; name1[12] = "amr"; name1[13] = "beshoy"; name1[14] = "marina"; name1[15] = "gerges"; name1[16] = "botros"; name1[17] = "mina"; name1[18] = "menna"; name1[19] = "feasal"; name1[20] = "youssef"; name1[21] = "moussa"; Random id = new Random(); Random roundc = new Random(); String round1; int idc; String name; Random namec = new Random(); int namecounter = 0; Random belle = new Random(); int belec = 0; Random yearc = new Random(); Random num_ratingsc = new Random(); int num_ratingSum = 0; // roundc.nextInt(4); try { Class.forName("org.postgresql.Driver"); c = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/a2", "mohamed", "1234"); System.out.println("Opened database successfully"); String sql3; String sql4; stmt = c.createStatement(); String sql = "CREATE TABLE cup_matches " + "(MID INT PRIMARY KEY NOT NULL," + " ROUND TEXT NOT NULL, " + " YEAR INT NOT NULL, " + " NUM_RATINGS INT NOT NULL, " + " RATING INT NOT NULL)"; String sql1 = "CREATE TABLE played_in " + "(MID INT NOT NULL," + " NAME TEXT NOT NULL, " + " YEAR INT NOT NULL, " + " POSITION INT NOT NULL, " + "CONSTRAINT pk_played_in PRIMARY KEY (MID, NAME));"; String sql2 = "ALTER TABLE played_in ADD CONSTRAINT ref FOREIGN KEY (MID) REFERENCES cup_matches (MID);"; stmt.executeUpdate(sql); stmt.executeUpdate(sql1); stmt.executeUpdate(sql2); for (int i = 0; i < 2680; i++) { year = yearc.nextInt(2014 - 1900) + 1900; num_rating = num_ratingsc.nextInt(1000); num_ratingSum += num_rating; num_ratingAvg = num_ratingSum / (i + 1); round1 = "\'" + round[roundc.nextInt(4)] + "\'"; sql3 = "INSERT INTO cup_matches (MID, ROUND, YEAR, NUM_RATINGS, RATING) " + "VALUES (" + i + ", " + round1 + ", " + year + ", " + num_rating + ", " + num_ratingAvg + ");"; stmt.executeUpdate(sql3); System.out.println(sql3); } for (int j = 0; j < 58960; j++) { idc = j; idc = (idc >= 2679) ? 0 : idc; year1 = yearc.nextInt(2014 - 1900) + 1900; num_rating = num_ratingsc.nextInt(1000); if ((belle.nextInt(2 - 1) + 1) == 1 && belec < 118) { name = "\'" + name1[namecounter] + "belle" + "\'"; sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) " + "VALUES (" + idc + ", " + name + ", " + year1 + ", " + num_rating + ");"; stmt.executeUpdate(sql4); belec++; idc++; System.out.println(idc + " " + namecounter); namecounter++; } else { name = "\'" + name1[namecounter] + "\'"; sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) " + "VALUES (" + idc + ", " + name + ", " + year1 + ", " + num_rating + ");"; stmt.executeUpdate(sql4); namecounter++; idc++; System.out.println(idc + " " + namecounter); } namecounter = (namecounter < 22) ? namecounter : 0; } // stmt.executeUpdate(sql); // stmt.executeUpdate(); // stmt.executeUpdate(sql2); stmt.close(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } System.out.println("Table created successfully"); } } A: This line makes idc = 0 for each j value above 2679. idc = j; idc = (idc >= 2679) ? 0 : idc; The first time, it will insert in the table played_in with idc = 0 and will insert that value for each name, when the name counter starts again with 0: namecounter = (namecounter < 22) ? namecounter : 0; It will try to insert the first name with 0 again and it will fail due to duplicate key error
{ "pile_set_name": "StackExchange" }
Q: Saving file data from current position to end of file with fstream I have a situation where I loop through the first 64 lines of a file and save each line into a string. The rest of the file is unknown. It may be a single line or many. I know that there will be 64 lines at the beginning of the file but I do not know their size. How can I save the entirety of the rest of the file to a string? This is what I currently have: std::ifstream signatureFile(fileName); for (int i = 0; i < 64; ++i) { std::string tempString; //read the line signatureFile >> tempString; //do other processing of string } std::string restOfFile; //save the rest of the file into restOfFile Thanks to the responses this is how I got it working: std::ifstream signatureFile(fileName); for (int i = 0; i < 64; ++i) { std::string tempString; //read the line //using getline prevents extra line break when reading the rest of file std::getline(signatureFile, tempString); //do other processing of string } //save the rest of the file into restOfFile std::string restOfFile{ std::istreambuf_iterator<char>{signatureFile}, std::istreambuf_iterator<char>{} }; signatureFile.close(); A: One of std::string's constructors is a template that takes two iterators as parameters, a beginning and an ending iterator, and constructs a string from the sequence defined by the iterators. It just so happens that std::istreambuf_iterator provides a suitable input iterator for iterating over the contents of an input stream: std::string restOfFile{std::istreambuf_iterator<char>{signatureFile}, std::istreambuf_iterator<char>{}};
{ "pile_set_name": "StackExchange" }
Q: scheduling for an exact time with monotonic time I have a scheduling function and a scheduler with a queue of future events ordered by time. I'm using UNIX timestamps and the regular time.time(). One fragment of the scheduler is roughly equivalent to this: # select the nearest event (eventfunc at eventime) sleeptime = eventtime - time.time() # if the sleep gets interrupted, # the whole block will be restarted interruptible_sleep(sleeptime) eventfunc() where the eventtime could be computed either based on a delay: eventtime = time.time() + delay_seconds or based on an exact date and time, e.g.: eventtime = datetime(year,month,day,hour,min).timestamp() Now we have the monotonic time in Python. I'm considering to modify the scheduler to use the monotonic time. Schedulers are supposed to use the monotonic time they say. No problem with delays: sleeptime = eventtime - time.monotonic() where: eventtime = time.monotonic() + delay_seconds But with the exact time I think the best way is to leave the code as it is. Is that correct? If yes, I would need two event queues, one based on monotonic time and one based on regular time. I don't like that idea much. A: As I said in the comment, your code duplicates the functionality of the sched standard module - so you can as well use solving this problem as a convenient excuse to migrate to it. That said, what you're supposed to do if system time jumps forward or backward is task-specific. time.monotonic() is designed for cases when you need to do things with set intervals between them regardless of anything So, if your solution is expected to instead react to time jumps by running scheduled tasks sooner or later than it otherwise would, in accordance with the new system time, you have no reason to use monotonic time. If you wish to do both, then you either need two schedulers, or tasks with timestamps of the two kinds. In the latter case, the scheduler will need to convert one type to the other (every time it calculates how much to wait/whether to run the next task) - for which time provides no means.
{ "pile_set_name": "StackExchange" }
Q: PHP Elastic Search Full Text Search - Sort by Relevance I want to fetch "User" data using the "%LIKE%" condition in Elastic Search. GET user/_search { "query": { "query_string": { "fields": ["firstname", "lastname"], "query": "*a*" } }, "sort": { "_score": "desc" } } It returns the results with "_score": 1 for all the data. The data with name "Kunal Dethe" is first and "Abhijit Pingale" is second. But as expected "Abhijit Pingale" should come first because, the letter "a" occurs twice in this name and not in "Kunal Dethe". Any ideas why? EDIT: Used the "nGram" solution but for a text like "ab", the grams are broken down as "a", "b" then "ab" as the "min_gram" is set to 1 because the result should be returned even when a single character is entered. But I want the search to be done as "ab" only. Of course, can increase the "min_gram" but can it be dynamically set to the length of the text searched? POST /user { "settings": { "analysis": { "filter": { "substring": { "type": "nGram", "min_gram": 1, "max_gram": 15 } }, "analyzer": { "substring_analyzer": { "tokenizer": "standard", "filter": [ "lowercase", "substring" ] } } } }, "mappings": { "user": { "properties": { "id": { "type": "long" }, "firstname": { "type": "string", "analyzer": "substring_analyzer" }, "lastname": { "type": "string", "analyzer": "substring_analyzer" } } } } } //Searching via GET user/_search { "query": { "query_string": { "fields": ["firstname^2", "lastname"], "query": "ab" } } } A: One way of achieving what you want is to specify an analyzer to use (i.e. standard) at search time so your input doesn't get analyzed by the default ngram analyzer. That way you'll only match ab tokens and neither a nor b tokens. GET user/_search { "query": { "query_string": { "fields": ["firstname^2", "lastname"], "query": "ab", "analyzer": "standard" <--- add this } } } A better approach, however, is to set "search_analyzer": "standard" in your mapping instead of using the ngram approach at search time as well, which is the case when only specifying "analyzer": "substring_analyzer". So if you search for ab you'll only match ab tokens as that will not be ngram'ed at search time. "mappings": { "user": { "properties": { "id": { "type": "long" }, "firstname": { "type": "string", "analyzer": "substring_analyzer", "search_analyzer": "standard" <-- add this }, "lastname": { "type": "string", "analyzer": "substring_analyzer", "search_analyzer": "standard" <-- add this } } } }
{ "pile_set_name": "StackExchange" }
Q: $f(X)$ is differentiable at $x=a$ but it is discontinuous I have defined a function such that: $$f(x)=\begin{cases}mx,&(x\le a), \\ mx+c,&(x>a).\end{cases}$$ Here according to the derivative definition : $f '(a) = \lim_{x\to a} [f (x) - f (a) ]/ [x - a] $ we can show that this limit exits by taking the LHS and RHS limits , and showing that they are equal. Since the gradient is the same I think it is trivial . Can anyone please explain ? Thank you ! A: The right hand limit does not exist. Remember, $f(a) = ma$, not $ma + c$, even when you're finding the right hand limit.
{ "pile_set_name": "StackExchange" }
Q: Why is a variable defined outside a fill-slot or define-macro element not visible inside this element? Why is a variable defined outside a fill-slot or define-macro element not visible inside this element? <body tal:define="a string:a"> <metal:content-core fill-slot="content-core"> <metal:content-core define-macro="content-core" tal:define="b string:b"> <div tal:content="a" /> <div tal:content="b" /> <div tal:content="c" /> </metal:content-core> </metal:content-core> </body> The tales-expression with the variable a cannot be evaluated. Of course b is visible. On the other side, if the variable c is defined in the enclosing element of define-slot like the following then it is visible. <div tal:define="c string:c"> <metal:text define-slot="content-core"></metal:text> </div> It looks like the variables are evaluated only after the slot is inserted. A: The context of a TAL macro is only significant if you are viewing the macro in that context. It's interpreted if you're viewing the template containing the macro, but not if you're using the macro. Macros are -- in a sense -- simply copied run time from the template containing the macro to the page using it, then expanded. All the name space comes from the template that uses the macro. To think of it another way: macros are not a scoped language. If they were, you wouldn't be able to see the macro at all from another template. TAL would have to be immensely more complicated, and you'd have to be thinking about closures and functions. "Macro" languages are called that because macros are expanded when used. They are not functions. So, why do containing templates include context for the macros at all? They don't have to. It's usually done so that the macro may be tested in a realistic environment. (Although sometimes macros are inside pages that are independently useful.)
{ "pile_set_name": "StackExchange" }