pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
32,460,593 | 1 | Including the group name in the apply function pandas python <p>Is there away to specify the groupby call to use the group name in the apply lambda function.</p> <p>For instance, if I iterate through groups I can get the group key via the following tuple decomposition:</p> <pre><code>for group_name, subdf in temp_dataframe.groupby(level=0, axis=0): print group_name </code></pre> <p>is there away to get the group name in the apply function, such as:</p> <pre><code>temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf) </code></pre> <p>How can I get the group name as an argument for the apply lambda function?</p> <p>Thanks!</p> |
13,845,157 | 0 | <pre><code>decimal index = SeriesList.SelectMany(p => p.Childs) .FirstOrDefault(c => c.key == "aa").Value; </code></pre> <p>But keep in mind, that child with provided key should exist in list, otherwise you will get an exception. I think better to find child first, and then if child exist, get its value:</p> <pre><code>Childs child = SeriesList.SelectMany(p => p.Childs) .FirstOrDefault(c => c.key == "aa"); if (child != null) index = child.Value; </code></pre> |
23,723,500 | 0 | Using dart to create a javascript library <h1>The problem</h1> <p>I'm currently working on a JavaScript library, and in order to reduce the amount of bugs I thought that my library might benefit from using Dart's static typing mechanism. First, because my lib wasn't doing any interop neither with HTML nor with other JavaScript libraries, only pure javascript object manipulation stuff. However I didn't find any info on the net showing how it is possible to build a JS library using dart. So I've tried to do that myself, created initial dart file:</p> <pre class="lang-dart prettyprint-override"><code>library Repo; class Type { final String name; final TypeCategory category; Type(String name, TypeCategory category) : name = name, category = category { category.types[name] = this; } } class TypeCategory { final String name; final Map<String, Type> types = new Map(); TypeCategory(this.name); } class Branch { } class Descriptor { } class TableDescriptor extends Descriptor { TableDescriptor.ctor() { } } class Repo { Descriptor descriptor(String name) { } Branch branch(String name) { } void Merge() { } } main() { return Repo; } </code></pre> <p>Compiled it to JavaScript using dart2js to see how I'm doing:</p> <pre class="lang-javascript prettyprint-override"><code>// Generated by dart2js, the Dart to JavaScript compiler version: 1.3.6. // The code supports the following hooks: // dartPrint(message): // if this function is defined it is called instead of the Dart [print] // method. // // dartMainRunner(main, args): // if this function is defined, the Dart [main] method will not be invoked // directly. Instead, a closure that will invoke [main], and its arguments // [args] is passed to [dartMainRunner]. (function($) { function dart(){ this.x = 0 }var A = new dart; delete A.x; var B = new dart; delete B.x; var C = new dart; delete C.x; var D = new dart; delete D.x; var E = new dart; delete E.x; var F = new dart; delete F.x; var G = new dart; delete G.x; var H = new dart; delete H.x; var J = new dart; delete J.x; var K = new dart; delete K.x; var L = new dart; delete L.x; var M = new dart; delete M.x; var N = new dart; delete N.x; var O = new dart; delete O.x; var P = new dart; delete P.x; var Q = new dart; delete Q.x; var R = new dart; delete R.x; var S = new dart; delete S.x; var T = new dart; delete T.x; var U = new dart; delete U.x; var V = new dart; delete V.x; var W = new dart; delete W.x; var X = new dart; delete X.x; var Y = new dart; delete Y.x; var Z = new dart; delete Z.x; function Isolate() {} init(); $ = Isolate.$isolateProperties; var $$ = {}; (function (reflectionData) { "use strict"; function map(x){x={x:x};delete x.x;return x} function processStatics(descriptor) { for (var property in descriptor) { if (!hasOwnProperty.call(descriptor, property)) continue; if (property === "^") continue; var element = descriptor[property]; var firstChar = property.substring(0, 1); var previousProperty; if (firstChar === "+") { mangledGlobalNames[previousProperty] = property.substring(1); var flag = descriptor[property]; if (flag > 0) descriptor[previousProperty].$reflectable = flag; if (element && element.length) init.typeInformation[previousProperty] = element; } else if (firstChar === "@") { property = property.substring(1); $[property]["@"] = element; } else if (firstChar === "*") { globalObject[previousProperty].$defaultValues = element; var optionalMethods = descriptor.$methodsWithOptionalArguments; if (!optionalMethods) { descriptor.$methodsWithOptionalArguments = optionalMethods = {} } optionalMethods[property] = previousProperty; } else if (typeof element === "function") { globalObject[previousProperty = property] = element; functions.push(property); init.globalFunctions[property] = element; } else if (element.constructor === Array) { addStubs(globalObject, element, property, true, descriptor, functions); } else { previousProperty = property; var newDesc = {}; var previousProp; for (var prop in element) { if (!hasOwnProperty.call(element, prop)) continue; firstChar = prop.substring(0, 1); if (prop === "static") { processStatics(init.statics[property] = element[prop]); } else if (firstChar === "+") { mangledNames[previousProp] = prop.substring(1); var flag = element[prop]; if (flag > 0) element[previousProp].$reflectable = flag; } else if (firstChar === "@" && prop !== "@") { newDesc[prop.substring(1)]["@"] = element[prop]; } else if (firstChar === "*") { newDesc[previousProp].$defaultValues = element[prop]; var optionalMethods = newDesc.$methodsWithOptionalArguments; if (!optionalMethods) { newDesc.$methodsWithOptionalArguments = optionalMethods={} } optionalMethods[prop] = previousProp; } else { var elem = element[prop]; if (prop !== "^" && elem != null && elem.constructor === Array && prop !== "<>") { addStubs(newDesc, elem, prop, false, element, []); } else { newDesc[previousProp = prop] = elem; } } } $$[property] = [globalObject, newDesc]; classes.push(property); } } } function addStubs(descriptor, array, name, isStatic, originalDescriptor, functions) { var f, funcs = [originalDescriptor[name] = descriptor[name] = f = array[0]]; f.$stubName = name; functions.push(name); for (var index = 0; index < array.length; index += 2) { f = array[index + 1]; if (typeof f != "function") break; f.$stubName = array[index + 2]; funcs.push(f); if (f.$stubName) { originalDescriptor[f.$stubName] = descriptor[f.$stubName] = f; functions.push(f.$stubName); } } for (var i = 0; i < funcs.length; index++, i++) { funcs[i].$callName = array[index + 1]; } var getterStubName = array[++index]; array = array.slice(++index); var requiredParameterInfo = array[0]; var requiredParameterCount = requiredParameterInfo >> 1; var isAccessor = (requiredParameterInfo & 1) === 1; var isSetter = requiredParameterInfo === 3; var isGetter = requiredParameterInfo === 1; var optionalParameterInfo = array[1]; var optionalParameterCount = optionalParameterInfo >> 1; var optionalParametersAreNamed = (optionalParameterInfo & 1) === 1; var isIntercepted = requiredParameterCount + optionalParameterCount != funcs[0].length; var functionTypeIndex = array[2]; var unmangledNameIndex = 2 * optionalParameterCount + requiredParameterCount + 3; var isReflectable = array.length > unmangledNameIndex; if (getterStubName) { f = tearOff(funcs, array, isStatic, name, isIntercepted); f.getterStub = true; if (isStatic) init.globalFunctions[name] = f; originalDescriptor[getterStubName] = descriptor[getterStubName] = f; funcs.push(f); if (getterStubName) functions.push(getterStubName); f.$stubName = getterStubName; f.$callName = null; if (isIntercepted) init.interceptedNames[getterStubName] = true; } if (isReflectable) { for (var i = 0; i < funcs.length; i++) { funcs[i].$reflectable = 1; funcs[i].$reflectionInfo = array; } var mangledNames = isStatic ? init.mangledGlobalNames : init.mangledNames; var unmangledName = array[unmangledNameIndex]; var reflectionName = unmangledName; if (getterStubName) mangledNames[getterStubName] = reflectionName; if (isSetter) { reflectionName += "="; } else if (!isGetter) { reflectionName += ":" + requiredParameterCount + ":" + optionalParameterCount; } mangledNames[name] = reflectionName; funcs[0].$reflectionName = reflectionName; funcs[0].$metadataIndex = unmangledNameIndex + 1; if (optionalParameterCount) descriptor[unmangledName + "*"] = funcs[0]; } } function tearOffGetterNoCsp(funcs, reflectionInfo, name, isIntercepted) { return isIntercepted ? new Function("funcs", "reflectionInfo", "name", "H", "c", "return function tearOff_" + name + (functionCounter++)+ "(x) {" + "if (c === null) c = H.closureFromTearOff(" + "this, funcs, reflectionInfo, false, [x], name);" + "return new c(this, funcs[0], x, name);" + "}")(funcs, reflectionInfo, name, H, null) : new Function("funcs", "reflectionInfo", "name", "H", "c", "return function tearOff_" + name + (functionCounter++)+ "() {" + "if (c === null) c = H.closureFromTearOff(" + "this, funcs, reflectionInfo, false, [], name);" + "return new c(this, funcs[0], null, name);" + "}")(funcs, reflectionInfo, name, H, null) } function tearOffGetterCsp(funcs, reflectionInfo, name, isIntercepted) { var cache = null; return isIntercepted ? function(x) { if (cache === null) cache = H.closureFromTearOff(this, funcs, reflectionInfo, false, [x], name); return new cache(this, funcs[0], x, name) } : function() { if (cache === null) cache = H.closureFromTearOff(this, funcs, reflectionInfo, false, [], name); return new cache(this, funcs[0], null, name) } } function tearOff(funcs, reflectionInfo, isStatic, name, isIntercepted) { var cache; return isStatic ? function() { if (cache === void 0) cache = H.closureFromTearOff(this, funcs, reflectionInfo, true, [], name).prototype; return cache; } : tearOffGetter(funcs, reflectionInfo, name, isIntercepted); } var functionCounter = 0; var tearOffGetter = (typeof dart_precompiled == "function") ? tearOffGetterCsp : tearOffGetterNoCsp; if (!init.libraries) init.libraries = []; if (!init.mangledNames) init.mangledNames = map(); if (!init.mangledGlobalNames) init.mangledGlobalNames = map(); if (!init.statics) init.statics = map(); if (!init.typeInformation) init.typeInformation = map(); if (!init.globalFunctions) init.globalFunctions = map(); if (!init.interceptedNames) init.interceptedNames = map(); var libraries = init.libraries; var mangledNames = init.mangledNames; var mangledGlobalNames = init.mangledGlobalNames; var hasOwnProperty = Object.prototype.hasOwnProperty; var length = reflectionData.length; for (var i = 0; i < length; i++) { var data = reflectionData[i]; var name = data[0]; var uri = data[1]; var metadata = data[2]; var globalObject = data[3]; var descriptor = data[4]; var isRoot = !!data[5]; var fields = descriptor && descriptor["^"]; var classes = []; var functions = []; processStatics(descriptor); libraries.push([name, uri, classes, functions, metadata, fields, isRoot, globalObject]); } }) ([ ["Repo", "repo.dart", , F, { "^": "", main: function() { return C.Type_Jeh; } }, 1], ["_js_helper", "dart:_js_helper", , H, { "^": "", createRuntimeType: function($name) { return new H.TypeImpl($name, null); }, TypeImpl: { "^": "Object;_typeName,_unmangledName" } }], ["dart.core", "dart:core", , P, { "^": "", Null: { "^": "Object;" }, Object: { "^": ";" } }], ]); Isolate.$finishClasses($$, $, null); $$ = null; // Runtime type support // getInterceptor methods C.Type_Jeh = H.createRuntimeType('Repo'); $.libraries_to_load = {}; $.Closure_functionCounter = 0; $.BoundClosure_selfFieldNameCache = null; $.BoundClosure_receiverFieldNameCache = null; init.functionAliases = {}; ; init.metadata = []; $ = null; Isolate = Isolate.$finishIsolateConstructor(Isolate); $ = new Isolate(); function convertToFastObject(properties) { function MyClass() {}; MyClass.prototype = properties; new MyClass(); return properties; } A = convertToFastObject(A); B = convertToFastObject(B); C = convertToFastObject(C); D = convertToFastObject(D); E = convertToFastObject(E); F = convertToFastObject(F); G = convertToFastObject(G); H = convertToFastObject(H); J = convertToFastObject(J); K = convertToFastObject(K); L = convertToFastObject(L); M = convertToFastObject(M); N = convertToFastObject(N); O = convertToFastObject(O); P = convertToFastObject(P); Q = convertToFastObject(Q); R = convertToFastObject(R); S = convertToFastObject(S); T = convertToFastObject(T); U = convertToFastObject(U); V = convertToFastObject(V); W = convertToFastObject(W); X = convertToFastObject(X); Y = convertToFastObject(Y); Z = convertToFastObject(Z); // BEGIN invoke [main]. ;(function (callback) { if (typeof document === "undefined") { callback(null); return; } if (document.currentScript) { callback(document.currentScript); return; } var scripts = document.scripts; function onLoad(event) { for (var i = 0; i < scripts.length; ++i) { scripts[i].removeEventListener("load", onLoad, false); } callback(event.target); } for (var i = 0; i < scripts.length; ++i) { scripts[i].addEventListener("load", onLoad, false); } })(function(currentScript) { init.currentScript = currentScript; if (typeof dartMainRunner === "function") { dartMainRunner(F.main, []); } else { F.main([]); } }); // END invoke [main]. function init() { Isolate.$isolateProperties = {}; function generateAccessor(fieldDescriptor, accessors, cls) { var fieldInformation = fieldDescriptor.split("-"); var field = fieldInformation[0]; var len = field.length; var code = field.charCodeAt(len - 1); var reflectable; if (fieldInformation.length > 1) reflectable = true; else reflectable = false; code = code >= 60 && code <= 64 ? code - 59 : code >= 123 && code <= 126 ? code - 117 : code >= 37 && code <= 43 ? code - 27 : 0; if (code) { var getterCode = code & 3; var setterCode = code >> 2; var accessorName = field = field.substring(0, len - 1); var divider = field.indexOf(":"); if (divider > 0) { accessorName = field.substring(0, divider); field = field.substring(divider + 1); } if (getterCode) { var args = getterCode & 2 ? "receiver" : ""; var receiver = getterCode & 1 ? "this" : "receiver"; var body = "return " + receiver + "." + field; var property = cls + ".prototype.get$" + accessorName + "="; var fn = "function(" + args + "){" + body + "}"; if (reflectable) accessors.push(property + "$reflectable(" + fn + ");\n"); else accessors.push(property + fn + ";\n"); } if (setterCode) { var args = setterCode & 2 ? "receiver, value" : "value"; var receiver = setterCode & 1 ? "this" : "receiver"; var body = receiver + "." + field + " = value"; var property = cls + ".prototype.set$" + accessorName + "="; var fn = "function(" + args + "){" + body + "}"; if (reflectable) accessors.push(property + "$reflectable(" + fn + ");\n"); else accessors.push(property + fn + ";\n"); } } return field; } Isolate.$isolateProperties.$generateAccessor = generateAccessor; function defineClass(name, cls, fields) { var accessors = []; var str = "function " + cls + "("; var body = ""; for (var i = 0; i < fields.length; i++) { if (i != 0) str += ", "; var field = generateAccessor(fields[i], accessors, cls); var parameter = "parameter_" + field; str += parameter; body += "this." + field + " = " + parameter + ";\n"; } str += ") {\n" + body + "}\n"; str += cls + ".builtin$cls=\"" + name + "\";\n"; str += "$desc=$collectedClasses." + cls + ";\n"; str += "if($desc instanceof Array) $desc = $desc[1];\n"; str += cls + ".prototype = $desc;\n"; if (typeof defineClass.name != "string") { str += cls + ".name=\"" + cls + "\";\n"; } str += accessors.join(""); return str; } var inheritFrom = function() { function tmp() { } var hasOwnProperty = Object.prototype.hasOwnProperty; return function(constructor, superConstructor) { tmp.prototype = superConstructor.prototype; var object = new tmp(); var properties = constructor.prototype; for (var member in properties) if (hasOwnProperty.call(properties, member)) object[member] = properties[member]; object.constructor = constructor; constructor.prototype = object; return object; }; }(); Isolate.$finishClasses = function(collectedClasses, isolateProperties, existingIsolateProperties) { var pendingClasses = {}; if (!init.allClasses) init.allClasses = {}; var allClasses = init.allClasses; var hasOwnProperty = Object.prototype.hasOwnProperty; if (typeof dart_precompiled == "function") { var constructors = dart_precompiled(collectedClasses); } else { var combinedConstructorFunction = "function $reflectable(fn){fn.$reflectable=1;return fn};\n" + "var $desc;\n"; var constructorsList = []; } for (var cls in collectedClasses) { if (hasOwnProperty.call(collectedClasses, cls)) { var desc = collectedClasses[cls]; if (desc instanceof Array) desc = desc[1]; var classData = desc["^"], supr, name = cls, fields = classData; if (typeof classData == "string") { var split = classData.split("/"); if (split.length == 2) { name = split[0]; fields = split[1]; } } var s = fields.split(";"); fields = s[1] == "" ? [] : s[1].split(","); supr = s[0]; split = supr.split(":"); if (split.length == 2) { supr = split[0]; var functionSignature = split[1]; if (functionSignature) desc.$signature = function(s) { return function() { return init.metadata[s]; }; }(functionSignature); } if (typeof dart_precompiled != "function") { combinedConstructorFunction += defineClass(name, cls, fields); constructorsList.push(cls); } if (supr) pendingClasses[cls] = supr; } } if (typeof dart_precompiled != "function") { combinedConstructorFunction += "return [\n " + constructorsList.join(",\n ") + "\n]"; var constructors = new Function("$collectedClasses", combinedConstructorFunction)(collectedClasses); combinedConstructorFunction = null; } for (var i = 0; i < constructors.length; i++) { var constructor = constructors[i]; var cls = constructor.name; var desc = collectedClasses[cls]; var globalObject = isolateProperties; if (desc instanceof Array) { globalObject = desc[0] || isolateProperties; desc = desc[1]; } allClasses[cls] = constructor; globalObject[cls] = constructor; } constructors = null; var finishedClasses = {}; init.interceptorsByTag = Object.create(null); init.leafTags = {}; function finishClass(cls) { var hasOwnProperty = Object.prototype.hasOwnProperty; if (hasOwnProperty.call(finishedClasses, cls)) return; finishedClasses[cls] = true; var superclass = pendingClasses[cls]; if (!superclass || typeof superclass != "string") return; finishClass(superclass); var constructor = allClasses[cls]; var superConstructor = allClasses[superclass]; if (!superConstructor) superConstructor = existingIsolateProperties[superclass]; var prototype = inheritFrom(constructor, superConstructor); } for (var cls in pendingClasses) finishClass(cls); }; Isolate.$lazy = function(prototype, staticName, fieldName, getterName, lazyValue) { var sentinelUndefined = {}; var sentinelInProgress = {}; prototype[fieldName] = sentinelUndefined; prototype[getterName] = function() { var result = $[fieldName]; try { if (result === sentinelUndefined) { $[fieldName] = sentinelInProgress; try { result = $[fieldName] = lazyValue(); } finally { if (result === sentinelUndefined) { if ($[fieldName] === sentinelInProgress) { $[fieldName] = null; } } } } else { if (result === sentinelInProgress) H.throwCyclicInit(staticName); } return result; } finally { $[getterName] = function() { return this[fieldName]; }; } }; }; Isolate.$finishIsolateConstructor = function(oldIsolate) { var isolateProperties = oldIsolate.$isolateProperties; function Isolate() { var hasOwnProperty = Object.prototype.hasOwnProperty; for (var staticName in isolateProperties) if (hasOwnProperty.call(isolateProperties, staticName)) this[staticName] = isolateProperties[staticName]; function ForceEfficientMap() { } ForceEfficientMap.prototype = this; new ForceEfficientMap(); } Isolate.prototype = oldIsolate.prototype; Isolate.prototype.constructor = Isolate; Isolate.$isolateProperties = isolateProperties; Isolate.$finishClasses = oldIsolate.$finishClasses; return Isolate; }; } })() //# sourceMappingURL=out.js.map //@ sourceMappingURL=out.js.map </code></pre> <p>And that's it, I've thrown away Dart because I didn't knew what to do with generated JS file, also I was frightened of potentially high amount of time required for keeping the resulting library interface clean and similar to one I'm using with JavaScript.</p> <h1>The question(s)</h1> <ol> <li>How do I expose class definitions created in Dart and later use them in JavaScript?</li> <li>Do you think it's worth it going into Dart when nearly all potential library users will be using JS version instead? (Using dart is already not good for me due to difference in community sizes, this means that less people will find it easy to contribute to my library)</li> <li>In your opinion, what should I do?</li> </ol> |
18,147,465 | 0 | <p>This would be a comment but I don't have the necessary reputation.</p> <p>See this <a href="https://github.com/mbostock/d3/issues/1410" rel="nofollow">d3 issue on github</a>. Is this what you're looking for?</p> <p>It's in the 3.3 milestone and the current version is 3.2.8. So, hopefully it won't be too much longer.</p> |
15,329,446 | 0 | <p>The global <code>cansend()</code> function is generic and can be called from anywhere so I'd probably leave this function as-is unless every invocation of <code>cansend()</code> is from a node class.</p> <p>You could add a <code>cansend()</code> method to your class which uses the stored instance variables as input, rather than having them set as parameters. Furthermore, if you're interested in using properties you could have the <code>operatingMode</code> configured as a property as you suggested.</p> <p>Here's an example refactor:</p> <pre><code>def cansend(nodeID,busID,value): '''sends a CAN frame with a particular value to a specific node''' class node(object): def __init__(self,nodeID,busID,operatingMode): self.nodeID = nodeID self.busID = busID self._operatingMode = operatingMode self.send_can_mode() def send_can_mode(self): """Send current operating mode to node on CAN bus.""" cansend(self.nodeID, self.busID, self._operatingMode) @property def operatingMode(self): """Return current operating mode.""" return self._operatingMode @operatingMode.setter def operatingMode(self, value): """Modify operating mode. Update remote node if mode changes.""" if value == self._operatingMode: return self._operatingMode = value self.send_can_mode() </code></pre> <p>When you want to change modes, you can do <code>node.operatingMode = newMode</code> and if the mode has changed from the previous state, the new mode will be automatically sent.</p> <p>The global <code>cansend()</code> is only called from the <code>send_can_mode()</code> method so you could integrate the global <code>cansend()</code> into your class if desired.</p> |
2,759,655 | 0 | <p>You could use a wrapper class:</p> <pre><code>Class ABWrapper { private AB m_AB; ABWrapper( AB ab ) { m_AB = new AB(); } public void execute() { // Do your stuff, then call original method m_AB.execute(); } } </code></pre> <p>This is a good approach when <code>AB</code> implements an <em>interface</em> (you did not mention that, though). In this case <code>ABWrapper</code> should implement the same interface. When you use a <em>factory</em> or even <em>dependency injection</em> to create your <code>AB</code> instances you can replace them there easily with your wrapper.</p> |
9,795,194 | 0 | <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.contextmenustrip.aspx" rel="nofollow">MSDN</a> has information on how to add items to a <code>contextmenustrip</code></p> <p>Sample Code:</p> <pre><code>// Declare the ContextMenuStrip control. private ContextMenuStrip fruitContextMenuStrip; public Form3() { // Create a new ContextMenuStrip control. fruitContextMenuStrip = new ContextMenuStrip(); // Attach an event handler for the // ContextMenuStrip control's Opening event. fruitContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(cms_Opening); // Create a new ToolStrip control. ToolStrip ts = new ToolStrip(); // Create a ToolStripDropDownButton control and add it // to the ToolStrip control's Items collections. ToolStripDropDownButton fruitToolStripDropDownButton = new ToolStripDropDownButton("Fruit", null, null, "Fruit"); ts.Items.Add(fruitToolStripDropDownButton); // Dock the ToolStrip control to the top of the form. ts.Dock = DockStyle.Top; // Assign the ContextMenuStrip control as the // ToolStripDropDownButton control's DropDown menu. fruitToolStripDropDownButton.DropDown = fruitContextMenuStrip; // Create a new MenuStrip control and add a ToolStripMenuItem. MenuStrip ms = new MenuStrip(); ToolStripMenuItem fruitToolStripMenuItem = new ToolStripMenuItem("Fruit", null, null, "Fruit"); ms.Items.Add(fruitToolStripMenuItem); // Dock the MenuStrip control to the top of the form. ms.Dock = DockStyle.Top; // Assign the MenuStrip control as the // ToolStripMenuItem's DropDown menu. fruitToolStripMenuItem.DropDown = fruitContextMenuStrip; // Assign the ContextMenuStrip to the form's // ContextMenuStrip property. this.ContextMenuStrip = fruitContextMenuStrip; // Add the ToolStrip control to the Controls collection. this.Controls.Add(ts); //Add a button to the form and assign its ContextMenuStrip. Button b = new Button(); b.Location = new System.Drawing.Point(60, 60); this.Controls.Add(b); b.ContextMenuStrip = fruitContextMenuStrip; // Add the MenuStrip control last. // This is important for correct placement in the z-order. this.Controls.Add(ms); } </code></pre> <p>Or another link to <a href="http://www.c-sharpcorner.com/UploadFile/mahesh/context-menu-in-C-Sharp/" rel="nofollow">ContextMenuStrip in C#</a></p> |
14,683,370 | 0 | <p>No, it is not possible. <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx" rel="nofollow">The Stack Is An Implementation Detail</a>. Moreover, the ability to manipulate the stack will bring a LOT of security/consistency issues. This is why manipulating the stack is a bad practice/a security bug even when you can do it (in C, for example). For example,the infamous "buffer overflow" category of security issues spring exactly from this: the ability to insert a "goto", a new stack frame, into the code, so that upon return a malicious payload is executed instead of the legitimate calling function.</p> <p>But then, why would you like to do it? Given a real goal, we could better reason how to do that, and suggest good alternatives</p> |
463,439 | 0 | <p>The standard pattern for implementing events is to use a virtual "OnXxx" method, like this:</p> <pre><code>public event EventHandler OkClick; protected virtual void OnOkClick(EventArgs e) { if (OkClick != null) OkClick(this, e); } </code></pre> <p>Now any time your base control wants to fire the "OkClick" event, it simply calls:</p> <pre><code>OnOkClick(EventArgs.Empty); </code></pre> <p>This means that descendants of your base control can override OnOkClick like this:</p> <pre><code>protected override void OnOkClick(EventArgs e) { // do some stuff before the event is fired base.OnOkClick(e); // do some stuff after the event is fired } </code></pre> <p>Note that the framework design guidelines actually state that you should implement the "OnXxx" method in such a way that the event is fired even if the descendant classes forget to call the base method. I don't really know a good way to do that, and I'm sure most people ignore this guideline.</p> |
2,377,631 | 0 | <p>Is "element" the id of your element? If so try making it <code>element = $("element")</code></p> |
31,237,262 | 0 | <p>on namespace Corpus.$cmd failed: ns doesn't exist</p> <p>It means you don't have collection named 'tweets' or 'via_count' in Corpus.</p> <p>Not like a raw query in mongodb, map_reduce function doesn't make a new collection if it's not exist.</p> |
29,009,915 | 0 | How to fetch page title name if document.title is not present <p>I want to fetch page title name but document.title is not present. Instead of document.title the logic is written below:-</p> <pre><code><title ng-bind="page.title()" class="ng-binding"></title> </code></pre> <p>I want to use javascript to get page title. </p> |
29,937,278 | 0 | Design patterns: exposing notifications using a protocol <p>I have got several types of a logic controller class that handle the communication with a remote resource. To do so each class uses an instance of a network controller class that deals with the connection details: connects to a resource, sends data, receives data. The logic controller classes are notified of data changes from the network controller class using notifications. So in my current solution <strong>each logic controller class registers for the notifications and implements specific functions to deal with them differently</strong>.</p> <p>However, if I want to do proper code engineering, I wonder whether it would be <strong>more robust</strong> to use <strong>protocols</strong> and <strong>delegation</strong>.</p> <p>I wonder if I could define which methods the logical controller classes need to implement in order to receive the notification. However I am not sure if this makes sense and is correct because <strong>I do not want inheritance here</strong>. </p> <p>Any suggestion?</p> |
36,108,966 | 0 | <p>You need to put things together differently to accomplish your goal. You can't just replace <code>++</code> with <code>:</code>. Try this:</p> <pre><code>toList t = toListPlus t [] toListPlus :: Tree a -> [a] -> [a] </code></pre> <p><code>toListPlus t xs</code> should produce <code>toList t ++ xs</code>, but implemented with recursive calls to <code>toListPlus</code>, not using <code>++</code> or <code>toList</code>. Let's work through it. The base case is easy:</p> <pre><code>toListPlus Empty xs = xs </code></pre> <p>The recursive case isn't too bad either. We want to convert the left subtree to a list, sticking other stuff on after:</p> <pre><code>toListPlus (Node v l r) xs = toListPlus l ??? </code></pre> <p>What comes after? The root, and then the result of converting the right subtree, and then whatever gets tacked on:</p> <pre><code>toListPlus (Node v l r) xs = toListPlus l (v : toListPlus r xs) </code></pre> <p>This function uses an implicit stack to keep track of the remaining work. This is probably the most efficient way to do it. If you wanted, you could use a zipper-style representation to make the stack explicit.</p> <hr> <p>How does this solution relate to the one leftaroundabout described? Well, they're actually the same. We can see that by shifting the list argument over:</p> <pre><code>toListPlus Empty = \xs -> xs toListPlus (Node v l r) = \xs -> toListPlus l (v : toListPlus r xs) = toListPlus l . (v :) . toListPlus r </code></pre> |
12,620,845 | 0 | <p>The issue was that we were not putting www. infront of the URL. The older version of Django CMS didn't like it.</p> |
13,937,783 | 0 | <p>Derp. This works. </p> <pre><code>$address->setData('firstname', $this->getRequest()->getPost('billing_firstname')); $address->setData('lastname', $this->getRequest()->getPost('billing_lastname')); $address->setData('fax', $this->getRequest()->getPost('billing_fax')); </code></pre> <p>Anyone else needing this? </p> <p>Add form fields into <code>your/theme/template/persistent/forms/register.phtml</code><br> override <code>Mage_Customer_AccountController</code><br> <code>setData('key', 'value')</code> in <code>yourmodule/customer/controller/accountController.php :: createPostAction()</code> </p> |
33,523,366 | 0 | <pre><code> @Override public void onClick(View v) { Intent intent=SecondActivity.newIntent(FirstActivity.this, targetActivity.class); startActivity(intent); } </code></pre> |
13,258,472 | 0 | Find Record based on the associated attributes <p>I am trying to find a record based on two associated attributes. The Record should be selected, if its association contains those two records.</p> <p>So far, I tried following - Which seemed to me a very bad practice and I want to avoid using it.</p> <pre><code>@size = Spree::OptionValue.find(params[:size]) @color = Spree::OptionValue.find(params[:color]) vari = Spree::Variant.all vari.each do |va| if va.option_values.include?(@size && @color) @variant = va end end </code></pre> <p>So far, I also tried </p> <pre><code>@variant = Spree::Variant.all(:include => :option_values, :conditions => ['option_value.id = ?', params[:color]) </code></pre> <p>This seems to be the way to go, but I can't seem to figure out the right way to get the result. The return error I keep on getting is following:</p> <blockquote> <p>ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table "option_values" LINE 1: ..._option_values_variants"."option_value_id" WHERE (option_val...</p> </blockquote> <p>EDIT:</p> <p>I got it working due to the great help given in the accepted answer:</p> <pre><code>Spree::Variant.joins(:option_values).where("spree_option_values.id in (?)", [size, color]) </code></pre> |
12,900,581 | 0 | <p>If I understand your question rightly, it's fairly straightforward.</p> <p>First, 'flatten' the list using a generator expression: <code>(item for sublist in combs for item in sublist)</code>.</p> <p>Then, iterate over the flattened list. For each item, you either add an entry to the dict (if it doesn't already exist), or add one to the value.</p> <pre><code>d = {} for key in (item for sublist in combs for item in sublist): try: d[key] += 1 except KeyError: # I'm not certain that KeyError is the right one, you might get TypeError. You should check this d[key] = 1 </code></pre> <p>This technique assumes all the elements of the sublists are hashable and can be used as keys.</p> |
8,473,056 | 0 | How do I plot a circle with points inside it in R? <p>I need to plot a circle centered at <code>(0,0)</code> in R. Then I would like to plot points in that circle specified in radius and degrees. Could anyone point me in the right direction for this task?</p> |
28,474,434 | 0 | <p>Your code only keeps the first encountered value for a given key. You can use <code>defaultdict</code> from the <code>collections</code> module to initialize <code>result</code> with a fresh <code>dict</code> and then set the key to the value as encountered in your list of tuples.</p> <pre><code>#all_tuples = [(...), (...), ...] from collections import defaultdict result = defaultdict(dict) for uid, k, v in all_tuples : result[uid][k] = v dict(result) </code></pre> <p>Output:</p> <pre><code>{1: {1: 2, 3344: 1, 756735: 1}, 4: {23: 1}, 23: {4: 1, 534: 1, 899979879: 1}, 534: {23: 1}, 3344: {1: 1}, 9977: {980898: 1}, 756735: {1: 1, 980898: 1}, 980898: {9977: 1, 756735: 1, 98789797: 1}, 98789797: {980898: 1}, 899979879: {23: 1}} </code></pre> |
30,083,732 | 0 | <p><a href="http://flask.pocoo.org/snippets/117/" rel="nofollow">This snippet</a> can be modified to present the data that you want. -- <a href="http://stackoverflow.com/users/3478217/esdes">Esdes</a></p> |
9,142,514 | 0 | Is it possible to create a storage provider for user data on a Windows Phone device? <p>The <a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.userdata.storagekind%28v=vs.92%29.aspx" rel="nofollow"><code>Microsoft.Phone.UserData.StorageKind</code> enumeration</a> <em>implies</em> that "other" storage locations can exist for storing use data, such as appointments and contact details. Is it possible to create a provider that can be installed as part of an App (such that the data becomes aggregated in a similar manner to that from Twitter, LinkedIn, Facebook, etc.)?</p> |
11,845,308 | 0 | <p>To use <code>ActionBarSherlock</code> with <code>MapActivity</code> you have to extend your <code>Activity</code> class from <code>com.actionbarsherlock.app.SherlockMapActivity</code> which you can download from <a href="https://github.com/JakeWharton/ActionBarSherlock-Plugin-Maps" rel="nofollow">ActionBarSherlock-Plugin-Maps</a>.</p> <p>This class is a plugin for ActionBarSherlock to support <code>MapActivity</code> link to mentioned github project you can also find in <a href="http://actionbarsherlock.com/download.html" rel="nofollow">ActionBarSherlock download section</a>.</p> |
6,169,651 | 0 | <p>There is no problem with what you are doing, no performance degradation. If you had a more complicated program with a large number of threads, you could look for utility classes in <code>java.util.concurrent</code>.</p> |
7,027,669 | 0 | <p>This should be able to be done in 2007 with a SharePoint Data Source. The SPDataSource control creates a dataset that you can then bind to your list control. </p> <p>Chris O'Brien has a great tutorial regarding SPDataSource and binding to controls. </p> <p><a href="http://www.sharepointnutsandbolts.com/2008/07/spdatasource-every-developer-friend.html" rel="nofollow">http://www.sharepointnutsandbolts.com/2008/07/spdatasource-every-developer-friend.html</a></p> |
29,006,161 | 0 | <p>I found the answer: </p> <pre><code>{{for bugs}} {{:status}} </br> {{/for}} </code></pre> |
34,358,789 | 0 | <p>You can use a CursorLoader for this. It assumes also that you have a ContentProvider as your data source for the application, which I will not discuss here but you can learn about them in <a href="http://www.vogella.com/tutorials/AndroidSQLite/article.html#contentprovider" rel="nofollow">this post</a> if you want.</p> <p>To sync the database data to your ListView, you will have to do two things:</p> <ul> <li>Create a custom Adapter that implements CursorAdapter</li> <li>Implement a LoaderManager in your Fragment</li> </ul> <p>To implement the LoaderManager just override the three required methods. One is used to setup your Cursor, one will feed the results to your Adapter. From then on, assuming your ContentProvider properly notifies any URIs of changes, you will notice those changes in the Adapter. Here is a snippet of the Loader code:</p> <pre><code>public class AccountsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{ private static final int MY_LOADER = 0; @Override public void onActivityCreated() { super.onActivityCreated(); getLoaderManager.initLoader(MY_LOADER, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch(id){ case MY_LOADER: return new CursorLoader( getActivity(), MY_URI, MY_COLUMNS, null, null, null ); default: throw new UnsupportedOperationException("Unknown loader id: " + id); } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch(loader.getId()){ case MY_LOADER: mAdapter.swapCursor(datA); default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } } @Override public void onLoaderReset(Loader<Cursor> loader) { switch(loader.getId()){ case MY_LOADER: mAdapter.swapCursor(null); break; default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } } } </code></pre> <p>I learned much of this from a <a href="https://www.udacity.com/course/developing-android-apps--ud853" rel="nofollow">Udacity course</a> that teaches you a lot about Android from the bottom up, and if you are looking for a complete overview I think it is very much worth your time.</p> |
19,449,750 | 0 | <p>Well I ran into the same problem few months back and the way I fixed this was by presenting mmvc as modal view controller. Please try replacing your else with something like this:</p> <pre><code>[presentingViewController dismissModalViewControllerAnimated:NO]; GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease]; request.minPlayers = minPlayers; request.maxPlayers = maxPlayers; request.playersToInvite = pendingPlayersToInvite; GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease]; mmvc.matchmakerDelegate = self; [presentingViewController presentModalViewController:mmvc animated:YES]; self.pendingInvite = nil; self.pendingPlayersToInvite = nil; </code></pre> <p>Also, there seem to be an issue with your authentication. Your method should use new mechanism for player authentication like:</p> <pre><code>- (void)authenticateLocalUser { if (!gameCenterAvailable) return; NSLog(@"Authenticating local user..."); if ([GKLocalPlayer localPlayer].authenticated == NO) { // Use new authentication mechanism if the iOS version is 6.0 or above if ([[UIDevice currentDevice].systemVersion compare:@"6.0" options:NSNumericSearch] != NSOrderedAscending) { [[GKLocalPlayer localPlayer] setAuthenticateHandler:^(UIViewController *vc, NSError *error) { if (error) NSLog(@"Error in authenticating User - %@", [error localizedDescription]); else if (vc) { AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDel.navigationController presentModalViewController:vc animated:YES]; } }]; } else [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:nil]; } else { NSLog(@"Already authenticated!"); } } </code></pre> |
31,813,486 | 0 | <p>You actually need to include a fragment (NOT the Relative Layout) to your layout like so:</p> <pre><code><fragment android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment" /> </code></pre> |
33,288,914 | 0 | <p>We could use <code>cSplit</code></p> <pre><code>library(splitstackshape) cSplit(dat, 'to', ',') </code></pre> |
14,612,625 | 0 | How to copy txt file online, put into server ssh or ftp? <p>I'm in the process of installing Django on a GoDaddy server, (i know i know), and i need to copy this script, <a href="https://raw.github.com/pypa/virtualenv/master/virtualenv.py" rel="nofollow">https://raw.github.com/pypa/virtualenv/master/virtualenv.py</a>, into a directory on the server. I have ssh access but I'm not quite sure what the right syntax would be to actually copy the file. I tried <code>cp</code> and <code>scp</code> but apparently I'm not doing it right. I'm on a mac terminal, fwiw. </p> |
24,009,426 | 0 | Source code file paths in Jenkins Violations plugin not working (when using StyleCop) <p>I'm facing an issue with the Jenkins Violations plug-in when trying to access my source code files from the UI. The paths are relative to the root of the volume :S. So, if my .cs file is in <code>C:\CMSRootFolder\MySolution\MyProject\Namespace\SourceCode.cs</code>, then the link in Jenkins is: <code>http://<jenkins_server>/job/<job_name>/violations/file/CMSRootFolder/MySolution/Namespace/SourceCode.cs/</code></p> <p>This happens even after setting the faux project path to "C:\CMSRootFolder\MySolution", and no matter what I try to set in the source code patterns. I think this might be a bug in the plug-in, but I would like to know if there is any workaround.</p> <p>Thanks.</p> |
32,852,407 | 0 | <p>It should be as simple as adding the name of the view to your return statement:</p> <pre><code>return View(viewName); </code></pre> <p>or with the model:</p> <pre><code>return View(viewName, modelName); </code></pre> |
25,477,450 | 0 | <p>You need to assign your fields actual objects. If you look at <code>Quiz.theContentManager</code>, you'll notice that you never actually assign it a value. You can fix this by passing the ones in from <code>Game1</code>. For instance, Game1 should look like this:</p> <pre><code>public class Game1 : Microsoft.Xna.Framework.Game { Quiz quiz; protected override void LoadContent() { quiz.LoadContent(Content); } protected override void Update(GameTime gameTime) { quiz.Update(gameTime); } protected override void Draw(GameTime gameTime) { quiz.Draw(spriteBatch, gameTime); } } </code></pre> <p>Then your Quiz class should look like this (note that you don't need class fields for any of the XNA stuff with this approach):</p> <pre><code>public class Quiz { QuizQuestion no1 = new QuizQuestion(); public void LoadContent(ContentManager content) { no1.LoadContent(content); } public void Update(GameTime gameTime) { // Perform whatever updates are required. } public void Draw(SpriteBatch spriteBatch, GameTime gameTime) { // Draw whatever } } </code></pre> |
25,013,093 | 0 | <p>You should go check the Sprite Kit Docs. <a href="https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html" rel="nofollow">https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html</a>. It's VERY helpful for beginners. A very good site to a few sprite kit tutorials might be raywenderlich.com.</p> <p>To your question:</p> <p>Go check sprite kits update method.</p> |
22,127,990 | 0 | <p>You can create a backend and use it as a target for your task. Backends do not have a time limit.</p> <p>Just remember to mark users you already processed. When a task fails (for any reason), it retries itself - you want to skip users you already processed during the previous attempt.</p> |
37,501,763 | 0 | How to pass an Object List in the Body of a Web Api C # <p>I'm a following problem I'm currently developing a web Api, with the database Cassandra, and I have an object that is a SortedDictionary , which is a text and a column object, thereby generating a list with a name and data as the model code below:</p> <p>Class People:</p> <pre><code>public class People{ public Guid UsersId { get; set; } public string Name { get; set; } public string UserName { get; set; } public string UserPassword { get; set; } public int Status { get; set; } public SortedDictionary<string, contacts> Contacts { get; set; } } </code></pre> <p>Class contacts:</p> <pre><code>public class contacts { public string Address { get; set; } public long Number { get; set; } public string District { get; set; } public string Postalcode { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public IDictionary<string, string> Phone { get; set; } } </code></pre> <p>The People class represents my column family Cassandra and also to facilitate my table, and contacts represents a UDT (user definided type), and the column which is the value is named list in the database is thus :</p> <pre><code>{ "Home" : { "address" : "Street Giovanna Barros Lobato", "number" : 392, "district" : "District Giovanna Barros Lobato", "postalcode" : null, "city" : "Paragominas", "state" : "Pará", "country" : "Brasil", "phone" : { } }, "Work" : { "address" : "Street Giovanna Barros Lobato", "number" : 392, "district" : "District Giovanna Barros Lobato", "postalcode" : null, "city" : "Paragominas", "state" : "Pará", "country" : "Brazil", "phone" : { } } } </code></pre> <p>The point is that when my transponho this data model for my action through the insert method below:</p> <pre><code>[HttpPost] [Route("PostClients/{clientid}")] [ResponseType(typeof(Models.Clients))] public async Task<IHttpActionResult> PostClients(Guid clientid, [FromBody] Models.Clients clients) { try { var response = await new UsersBll().AddUsersAsync(new Users { UsersId = clientid, Name = clients.Name, UserName = clients.UserName, UserPassword = clients.UserPassword, OpeningDate = clients.OpeningDate, Status = 1, Contacts = clients.Contacts}); return Ok(response); } }catch (Exception ex) { return BadRequest(ex.Message); } } </code></pre> <p>All areas of my body it takes the values, only the field that is the SortedList I can not put it ends up reset,all areas of my body it takes the values, only the field that is the SortedList I can not put it ends up reset, as the image of the visual studio and the example of my body the postman.</p> <p><a href="http://i.stack.imgur.com/Fdi77.png" rel="nofollow">Visual Studio Debug ilustration of case</a></p> <p><a href="http://i.stack.imgur.com/ttpiH.png" rel="nofollow">Postman Body send</a></p> |
24,108,041 | 0 | Perl query and get column name <p>I need to make a query where I will be looking for a specific string through several columns and I need to know which column (name) contains the value that I need.</p> <p>In the example below I need a query where I can ask which column contains the value 1000000000002101214 and that it returns f1. DB is MySQL and I need the programming to be done in Perl.</p> <pre><code>+---------------------+---------------------+---------------------+ | f1 | f2 | f3 | +---------------------+---------------------+---------------------+ | 1000000000002101214 | 1000000000001989129 | 1000000000001881637 | | 1000000000002080453 | 1000000000001968481 | 1000000000001862284 | | 1000000000002085919 | 1000000000001973677 | 1000000000001866854 | | 1000000000002075076 | 1000000000001963189 | 1000000000001857288 | +---------------------+---------------------+---------------------+ </code></pre> <p>I was able to find an almost-answer to my question from another site where I could get the column names of the fields in the table with the following:</p> <pre><code>my @cols = @{$sth->{NAME}}; # or NAME_lc if needed while (@row = $sth->fetchrow_array) { print "@row\n"; } $sth->finish; foreach ( @cols ) { printf( "Note: col : %s\n", $_ ); } </code></pre> <p>The problem is partially resolved. In the example table I provided in the original question I needed to know on which column my answer resides, the query contains several OR statemens:</p> <pre><code>SELECT * FROM table WHERE (f1='1000000000002101214' OR f2='1000000000002101214' OR f3='1000000000002101214') </code></pre> <p>And I need the result to show that the column name where the number is located is f1. So....</p> <p>Any thoughts?</p> |
13,992,196 | 0 | <p>In a imagePath , set location of your image. Like here its showing test.jpg file is stored in images folder.</p> <pre><code> String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString(); String imagePath = "file://"+ base + "/images/test.jpg"; String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>"; mWebView.loadDataWithBaseURL("", html, "text/html","utf-8", ""); </code></pre> |
23,275,183 | 0 | <p>Your <code>alert</code> call is using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#-_.28Unary_Plus.29" rel="nofollow">unary <code>+</code> arithmetic operator</a>, which attempts to convert its operand (in this case <code>cityname</code>) to a number. Since <code>cityname</code> is a string, the unary <code>+</code> cannot convert it and returns <code>NaN</code> instead.</p> |
14,257,872 | 0 | PHP Mail using Google <p>I'm new to PHP. Can anyone help me to figure out how to send mail in PHP using Google as host? I tried many links! Dint help me! PHP mailer program proper?</p> |
30,226,002 | 0 | <p>This code solves the problem you are talking about (specifically for issues with Chrome ios not liking "pop ups"), but in reference to Paypal Adaptive Payments where it opens a "pop up" and redirects to Paypal page for payment.</p> <p>The key is that you have to:</p> <ol> <li>Initiate the window.open directly from a button/link click</li> <li>You must use the _blank as the window "name" (and not choose your own)</li> </ol> <p>The main thing you want/need is:</p> <pre><code>var win; //VERY IMPORTANT - You must use '_blank' and NOT name the window if you want it to work with chrome ios on iphone //See this bug report from google explaining the issue: https://code.google.com/p/chromium/issues/detail?id=136610 win = window.open(paypalURL,'_blank'); //Initiate returnFromPayPal function if the pop up window is closed if (win && win.closed) { returnFromPayPal(); } </code></pre> <p>Here is the full code that you can follow (ignore anything that doesn't apply to what you are doing).</p> <pre><code><div> <?php $payUrl = 'https://www.paypal.com/webapps/adaptivepayment/flow/pay?expType=mini&paykey=' . $payKey ?> <button onclick="loadPayPalPage('<?php echo $payUrl; ?>')" title="Pay online with PayPal">PayPal</button> </div> <script> function loadPayPalPage(paypalURL) { var ua = navigator.userAgent; var pollingInterval = 0; var win; // mobile device if (ua.match(/iPhone|iPod|Android|Blackberry.*WebKit/i)) { //VERY IMPORTANT - You must use '_blank' and NOT name the window if you want it to work with chrome ios on iphone //See this bug report from google explaining the issue: https://code.google.com/p/chromium/issues/detail?id=136610 win = window.open(paypalURL,'_blank'); pollingInterval = setInterval(function() { if (win && win.closed) { clearInterval(pollingInterval); returnFromPayPal(); } } , 1000); } else { //Desktop device var width = 400, height = 550, left, top; if (window.outerWidth) { left = Math.round((window.outerWidth - width) / 2) + window.screenX; top = Math.round((window.outerHeight - height) / 2) + window.screenY; } else if (window.screen.width) { left = Math.round((window.screen.width - width) / 2); top = Math.round((window.screen.height - height) / 2); } //VERY IMPORTANT - You must use '_blank' and NOT name the window if you want it to work with chrome ios on iphone //See this bug report from google explaining the issue: https://code.google.com/p/chromium/issues/detail?id=136610 win = window.open(paypalURL,'_blank','top=' + top + ', left=' + left + ', width=' + width + ', height=' + height + ', location=0, status=0, toolbar=0, menubar=0, resizable=0, scrollbars=1'); pollingInterval = setInterval(function() { if (win && win.closed) { clearInterval(pollingInterval); returnFromPayPal(); } } , 1000); } } var returnFromPayPal = function() { location.replace("www.yourdomain.com/paypalStatusCheck.php"); // Here you would need to pass on the payKey to your server side handle (use session variable) to call the PaymentDetails API to make sure Payment has been successful // based on the payment status- redirect to your success or cancel/failed page } </script> </code></pre> |
18,326,319 | 0 | <p>Unfortunately I cannot provide a sample at the current moment, but you should definitely look into <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/plaf/basic/BasicScrollBarUI.html" rel="nofollow">this</a></p> <p>The <code>BasicScrollBarUI</code> class allows you to modify different features of a typical <code>JScrollBar</code>, such as various different colors, sizes, and shadow effects. This should be what you are looking for. Basically the idea is that you are supposed to override the <code>installDefaults</code> method and just modify the protected fields to your liking.</p> <p>But, if you want to get fancy, I would highly suggest looking into <a href="http://docs.oracle.com/javafx/" rel="nofollow">JavaFX</a> due to the amount of customizability it supports, one being CSS styling (which should be very helpful to you).</p> |
7,896,946 | 0 | <p>Taghrid, It looks like you're getting a Stackoverflow error. This indicates that somewhere in your code you have <a href="http://en.wikipedia.org/wiki/Infinite_loop#Infinite_recursion" rel="nofollow">Infinite recursion</a>. It looks like it's VoiceAlert and ReadyToSpeak functions that keep calling one another. Are you sure the package your using, org.androiddev.android.test is of good quality? Are you using a release version of it?</p> |
30,963,615 | 0 | How do I update a column based on other columns in the same row <p>Lets say I have a table called User. It has three columns called <code>Score1</code>, <code>Score2</code> and <code>Score3</code>.</p> <p><code>Score1</code> and <code>Score2</code> rely on the user inputting data but I want <code>Score3</code> to be the sum of <code>Score1</code> and <code>Score2</code>. How do I implement this? Is the logic for this rendered in the model. If so what does it look like? Or is it something that gets set up in during a migration when specifying the database structure?</p> |
257,969 | 0 | <p>Using shared memory is tougher because you'll have to manage the size of the shared memory buffer (or just pre-allocate enough). You'll also have to manually manage the data structures that you put in there. Once you have it tested and working though, it will be easier to use and test because of its simplicity.</p> <p>If you go the remoting route, you can use the IpcChannel instead of the TCP or HTTP channels for a single system communication using Named Pipes. <a href="http://msdn.microsoft.com/en-us/library/4b3scst2.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/4b3scst2.aspx</a>. The problem with this solution is that you'll need to come up with a registry type solution (either in shared memory or some other persistent store) that processes can register their endpoints with. That way, when you're looking for them, you can find a way to query for all the endpoints that are running on the system and you can find what you're looking for. The benefits of going with Remoting are that the serialization and method calling are all pretty straightforward. Also, if you decide to move to multiple machines on a network, you could just flip the switch to use the networking channels instead. The cons are that Remoting can get frustrating unless you clearly separate what are "Remote" calls from what are "Local" calls.</p> <p>I don't know much about WCF, but that also might be worth looking into. Spider sense says that it probably has a more elegant solution to this problem... maybe.</p> <p>Alternatively, you can create a "server" process that is separate from all the other processes and that gets launched (use a system Mutex to make sure more than one isn't launched) to act as a go-between and registration hub for all the other processes.</p> <p>One more thing to look into the Publish-Subscribe model for events (Pub/Sub). This technique helps when you have a listener that is launched before the event source is available, but you don't want to wait to register for the event. The "server" process will handle the event registry to link up the publishers and subscribers.</p> |
4,821,017 | 0 | EDMX new column generates error on ToList() call <p>We've added a new column to a database table. The column is defined as follows:</p> <pre><code>Name: DisplayAsSoldOut Type: Boolean NOT NULLABLE Default Value: 0 </code></pre> <p>We've refreshed our EDMX data model and the new column appears just fine. We are on an ASP.NET 4.0 platform using C#.</p> <p>We have a class defined as PagedList which inherits from List and implenents an interface IPagedList</p> <p>Within the PagedList we have the following method:</p> <pre><code>protected void Initialize(IQueryable<T> source, int index, int pageSize, int? totalCount) { if (index < 0) { throw new ArgumentOutOfRangeException("PageIndex cannot be below 0."); } if (pageSize < 1) { throw new ArgumentOutOfRangeException("PageSize cannot be less than 1."); } if (source == null) { source = new List<T>().AsQueryable(); } if (!totalCount.HasValue) { TotalItemCount = source.Count(); } PageSize = pageSize; PageIndex = index; if (TotalItemCount > 0) { PageCount = (int)Math.Ceiling(TotalItemCount / (double)PageSize); } else { PageCount = 0; } HasPreviousPage = (PageIndex > 0); HasNextPage = (PageIndex < (PageCount - 1)); IsFirstPage = (PageIndex <= 0); IsLastPage = (PageIndex >= (PageCount - 1)); if (TotalItemCount > 0) { AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); } } </code></pre> <p>When we reach the following line:</p> <pre><code>{ AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); } </code></pre> <p>we receive the following Exception ...</p> <pre><code>Type: System.Data.EntityCommandExecutionException Inner Exception: "Invalid column name 'DisplayAsSoldOut'." </code></pre> <p>I've tried searching for this type of exception but to no avail. The column appears in the EDMX dataset just fine. I even created a small throwaway program and imported the EDMX to do a simple read from the database and it worked fine. Has anyone run across something similar?</p> <p>I apologize for the lengthy post but wanted to present as much info as I could.</p> |
34,023,604 | 1 | Open Tkinter multiple Windows with delay (Python) <p>I've been trying to open several Tkinter windows with a delay of couple seconds between each Tkinter window.</p> <p>My Script so far : </p> <pre><code>import Tkinter as tk import os from PIL import Image, ImageTk from win32api import GetSystemMetrics from time import sleep from random import uniform root = tk.Tk() tk.Label(root, text="this is the root window").pack() root.geometry("10x10") l = [] def showPic(i): if(i<5): loc = os.getcwd() + '\pictures\pic%s.jpg' % i img = Image.open(loc) img.load() photoImg = ImageTk.PhotoImage(img) l.append(photoImg) window = tk.Toplevel() window.geometry("750x750+%d+%d" % (uniform(0, GetSystemMetrics(0) - 750), uniform(0, GetSystemMetrics(1) - 750))) tk.Label(window, text="this is window %s" % i).pack() tk.Label(window, image=photoImg).pack() root.after(1000, showPic(i+1)) else: return root.after(0, showPic(1)) root.mainloop() </code></pre> <p>I also tried using the sleep() and after() functions with no success. It waits the time before preparing the window, but shows them all together, simultaniously, after the time I set</p> |
11,321,205 | 0 | Vectorizing Dot Product Calculation using SSE4 <p>I am trying to improve this code with the SSE4 dot product but I am having a hard time finding a solution. This function gets the parameters qi and tj which contain float arrays with 80 cell each and then calculate the dot product. The return value is a vector with four dot products. So I what I'm trying to do is calculating four dot products of twenty values in parallel. </p> <p>Have you any idea how to improve this code?</p> <pre><code>inline __m128 ScalarProd20Vec(__m128* qi, __m128* tj) { __m128 res=_mm_add_ps(_mm_mul_ps(tj[0],qi[0]),_mm_mul_ps(tj[1],qi[1])); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[2],qi[2]),_mm_mul_ps(tj[3],qi[3]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[4],qi[4]),_mm_mul_ps(tj[5],qi[5]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[6],qi[6]),_mm_mul_ps(tj[7],qi[7]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[8],qi[8]),_mm_mul_ps(tj[9],qi[9]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[10],qi[10]),_mm_mul_ps(tj[11],qi[11]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[12],qi[12]),_mm_mul_ps(tj[13],qi[13]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[14],qi[14]),_mm_mul_ps(tj[15],qi[15]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[16],qi[16]),_mm_mul_ps(tj[17],qi[17]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[18],qi[18]),_mm_mul_ps(tj[19],qi[19]))); return res; } </code></pre> |
15,911,970 | 0 | <p>the variable countn should be accessable from both functions. i put everything in an anonymous function, so only both click event handler can access the variable.</p> <pre><code>(function () { var countn=0; $('#gallery').on('click', '.gon', function() { // increment countn }); $('.teaserbox').click(function() { // reset countn }); })(); </code></pre> |
21,618,767 | 0 | looping a CSS3 animation with multiple keyframes <p>I managed to make multiple key-frames in an animation play one after another </p> <p><a href="http://jsfiddle.net/NuMjW/" rel="nofollow">http://jsfiddle.net/NuMjW/</a></p> <p>but can't make the whole loop, so currently it plays the sequence once and then its done, is there a way to make it loop without using jquery or javascript to restart it after n seconds have passed.</p> <pre><code>.hi { width: 48px; height: 48px; background-image: url("http://s30.postimg.org/k4qce9z1r/warp.png"); -webkit-animation: play1 0.3s 0s steps(5) forwards, play2 0.3s 0.3s steps(5) forwards, play3 0.3s 0.6s steps(5) forwards; } @-webkit-keyframes play1 { from { background-position-y: 0px; background-position-x: 0px; } to { background-position-y: 0px; background-position-x: -240px; } } @-webkit-keyframes play2 { from { background-position-y: -48px; background-position-x: 0px; } to { background-position-y: -48px; background-position-x: -240px; } } @-webkit-keyframes play3 { from { background-position-y: -96px; background-position-x: 0px; } to { background-position-y: -96px; background-position-x: -240px; } } </code></pre> |
14,766,568 | 0 | Getting Data fom Server into Sqlite DB <p>In my application I have a <code>Sqlite database</code> locally. When application starts, I am running a <code>Thread</code> and getting <code>Json</code> data from Server. After parsing these json data, I am creating a <code>Sqlite</code> db in my app. It is in terms long running process and lots of code is written. Everything working fine,</p> <p><strong>But, I am just looking if there is another way around to directly populate my local db with this server db? basically a more robust solution.</strong></p> |
18,283,850 | 0 | Why does this provide me with a stack overflow error? <p>The following code yields a stack overflow error, can someone tell me why? (I know how to fix the error, if I reference 'super' instead of 'this' in the <code>add</code> method, but I am not sure why that works.)</p> <pre><code>package subclassingVector; import java.util.Vector; public class MyVectorSubclass extends Vector<MyModelClass> { public MyVectorSubclass(){ MyModelClass m = new MyModelClass(); m.setId(2); this.add(m); if(this.contains(m)){ System.out.println("contains is true"); } } public boolean add(MyModelClass o){ this.add(o); return true; } public boolean contains(Object o){ for(subclassingVector.MyModelClass mmc: this){ if(mmc.equals((MyModelClass) o)){ return true; } } return false; } public static void main(String[] args) { String s = new String("SSEE"); MyVectorSubclass m = new MyVectorSubclass(); } public class MyModelClass { private Integer id = null; public MyModelClass() { // TODO Auto-generated constructor stub } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } } </code></pre> |
29,910,521 | 0 | <p>Before version 7,</p> <p><code>osv</code> is a class and an OpenERP descriptor class and all the class( model) must inherit it for OpenERP module deployment.</p> <p><code>osv</code> class inside in OSV module in OpenERP server , which content all the OpenERP properties like you can see _column, _defaults and other many things there such as nameetc so we must inherit in our openerp model (class)</p> <p>In version 7, </p> <p>The ORM, short for Object-Relational Mapping, is a central part of OpenERP.</p> <p>In OpenERP, the data model is described and manipulated through Python classes and objects. It is the ORM job to bridge the gap -- as transparently as possible for the developer -- between Python and the underlying relational database (PostgreSQL), which will provide the persistence we need for our objects.</p> <p><code>osv.osv</code> and <code>orm.Model</code> is deprecated and it still works for backward compatibility. You should use <code>models.Model</code> instead.</p> <p>In version 8+, </p> <p>The model transition was</p> <p><code>osv.osv</code> ---> <code>orm.Model</code> ---> <code>models.Model</code></p> <p><code>osv.TransientModel</code> ---> <code>orm.TransientModel</code> ---> <code>models.TransientModel</code></p> |
38,766,605 | 0 | <p>Try this</p> <pre><code>- (NSString *)convertDate:(NSString *)dateString { NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZ"; NSDate *yourDate = [dateFormatter dateFromString:dateString]; dateFormatter.dateFormat = @"MMM dd, yyyy"; NSLog(@"%@",[dateFormatter stringFromDate:yourDate]); NSString *str = [dateFormatter stringFromDate:yourDate]; return str; } </code></pre> |
33,954,759 | 0 | <p>id_rsa.pub is base64 encoded file, it contains "+" character</p> <p>http post with application/x-www-form-urlencoded, need encode it's content preventing "+" being convert to " " (space key) </p> <p>try </p> <pre><code>curl --data-urlencode "key=$key_pub" --data-urlencode "title=$hostname" \ http://gitlabserver/api/v3/user/keys?private_token=$Token </code></pre> <p>see: <a href="http://stackoverflow.com/a/23152871/719995">this</a></p> |
17,026,940 | 0 | Is there a difference between "and" vs "and then" in an IF statement <p>I'm learning Ada by fixing bugs and reading code. I've noticed some if statements that are ganged with "and" and others with "and then". similarly, there is "or" and other places there is "or else". A co-worker says it's just syntactic sugar and makes no difference. I wonder if he's right?</p> |
23,583,190 | 0 | Echo Canceller Android API level 10 <p>I'm building an android audio app that has to support the API level 10 and I have Larsen effect problems. My android app streams the audio to a java app that outputs the sound.</p> <p>I found the AcousticEchoCanceller of android but it is only available from the API level 16.</p> <p>Is there a way to do that without this class ? Or could I do it on the java app ?</p> <p>Thank's</p> <p>Lukas</p> |
37,533,604 | 0 | Firebase2 Facebook Authentication with iOS Swift (Without FBSDKLoginButton) <p>I am trying to authenticate my login with Firebase 2 without using FBSDKLoginButton. I used the FBSDKLoginManager to get my FB Login token, then when i try to authenticate that with Firebase i get the following error:</p> <p><em>Error Domain=FIRAuthErrorDomain Code=17023 "An invalid API Key was supplied in the request." UserInfo={NSLocalizedDescription=An invalid API Key was supplied in the request., error_name=ERROR_INVALID_API_KEY}</em></p> <pre><code> let mngr = FBSDKLoginManager(); mngr.logInWithReadPermissions(["email"], fromViewController: self) { (result, error) in if FBSDKAccessToken.currentAccessToken() != nil { let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString); FIRAuth.auth()?.signInWithCredential(credential, completion: { (user, error) in if error == nil { print("user: \(user?.displayName)"); } else { print(error.debugDescription); } }) } } </code></pre> <p>I have all the info set in the plist:</p> <pre><code><string>VegFru</string> <key>LSApplicationQueriesSchemes</key> <array> <string>fbauth2</string> <string>fbapi</string> <string>fb-messenger-api</string> <string>fbshareextension</string> <string>fbapi20130214</string> <string>fbapi20130410</string> <string>fbapi20130702</string> <string>fbapi20131010</string> <string>fbapi20131219</string> <string>fbapi20140410</string> <string>fbapi20140116</string> <string>fbapi20150313</string> <string>fbapi20150629</string> <string>fbapi20160328</string> <string>fbauth</string> <string>fb-messenger-api20140430</string> <string>fb-messenger-platform-20150128</string> <string>fb-messenger-platform-20150218</string> <string>fb-messenger-platform-20150305</string> </array> </code></pre> <p>I also checked the API from the facebook app and it matches 100%. I am really clueless why its not working.</p> <p>Thank you in advance.</p> |
99,726 | 0 | <p>I tend to follow the rule pretty strictly, even when it's just my own code. I really like Properties in C# for that reason. It makes it really easy to control what values it's given, but you can still use them as variables. Or make the set private and the get public, etc.</p> |
31,921,647 | 0 | <p>You are asking to fulfill this requirement using crawl rule. But crawl rule is generic for the content source and it will effect all the content source which is not recommended(and also not possible) for excluding some result depending on item values. So I like to solve this using scope which is described below. </p> <p>For excluding that, first of all you need to add new managed property for the column "Active". For that go to search service application-> Managed Property-> New managed property. Give property name and map it to the field "Active". Also select the type of the field "Active". Tick the box for allow this property to be used in scopes.</p> <p>Then go to corresponding scope-> new rule-> choose property query then choose from "Add property restriction" corresponding managed property name(property name given by you during managed property creation) and "=" "No"(please use exact field value of the document library), then choose Exclude and click "ok".</p> <p>Add this scope in the search page and run full crawl in the central admin.</p> <p>I hope this will fulfill your requirement.</p> |
35,787,764 | 0 | <p>Every local object referenced inside a closure will be simply serialized and transfered with corresponding task. Beyond that Spark doesn't apply any special transformations - if you have local in-memory data structure it won't change when you use it inside a task.</p> |
2,320,534 | 0 | <p>There are a number of solutions. You should not assume that everyone has Java installed. You can use web start for instance which will help with the setup. You can find some <a href="http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html" rel="nofollow noreferrer">advice here</a>.</p> <p>More info about <a href="http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp" rel="nofollow noreferrer">web start here</a>.</p> |
21,929,283 | 0 | <p><code>line-height</code> doesn't collapse - every line will be that height, regardless of content before or after, similar to the line height setting in any word processor or DTP.</p> <p>However, if you use <code>margin</code> vertical spaces collapse, so you can use it as the space before and the space after paragraphs.</p> <p>So the following:</p> <pre><code>p { font-size: 20px; line-height: 30px; margin-top: 5px; margin-bottom: 10px; } </code></pre> <p>Will produce:</p> <ul> <li>20px font size</li> <li>1.5 line height</li> <li>5px space before the first paragraph</li> <li>10px space after the last paragraph <em>and</em> between paragraphs</li> </ul> <p>And also:</p> <ul> <li>The first margin will be applied before the outer <code>div</code></li> <li>The last margin will be applied after the outer <code>div</code></li> </ul> |
30,105,334 | 0 | How to save string contains of 1 and 0 to bin file? <p>Hi I have string str="1010101010101010" comes from file.txt which contains exactly 16 signs: 0 and 1.This is only an example and str can have more than 16 signs: 8,16,24,32,40... I want to save it to file.bin. After saving file.bin must have size 2B(in this example). I tried to use </p> <pre><code>File.WriteAllText(path, str); </code></pre> <p>but my file is bigger than i want. Can someone help me?</p> |
31,711,508 | 0 | Advantages of running a CI environment on JavaScript projects <p>I have been recently looking at installing either team city or Jenkins as a CI solution. I am quite aware of the advantages it can bring to my teams c++ projects with nightly builds to test if anything checked into git has broken the project or dependent projects. Also as a way of building and releasing software.</p> <p>However I know people use it on JavaScript projects. These cannot be built as such and can only really be tested at runtime. So what is the real advantage of using a CI solution on a JavaScript project comprising of back end and web front end code.</p> <p>Thanks for any advice.</p> |
9,470,248 | 0 | Stop SAS Program on Error <p>I am using a macro to stop my SAS program on an error, but it always disconnects from the server and then I cannot get back my temporary data sets anymore.</p> <p>I have tried:</p> <pre><code>OPTIONS ERRORABEND; </code></pre> <p>Here is the macro I have tried:</p> <pre><code>%macro errchk; %if &syserr >0 and &syserr ne 4 %then %abort; %mend errchk; </code></pre> <p>This one keeps processing the following data steps after reaching an error.</p> <p>I cannot figure out how to stop the rest of the program from running, but NOT disconnect from the SAS server. Any ideas?</p> |
20,030,774 | 0 | How to get all categories on opencart admin/catalog/product_form.tpl? <p>I'm using opencart 1.5.6 and what I'm trying to do is add a simple select with all the categories and children categories as option on product_form.tpl.</p> <p>I tried add to the follow code at admin/controler/catalog/product.php:</p> <pre><code> $this->load->model('catalog/category'); $results = $this->model_catalog_category->getCategories(0); foreach ($results as $result) { $this->data['categories'][] = array( 'category_id' => $result['category_id'], 'name' => $result['name'] ); } </code></pre> <p>and for the view admin/view/catalog/product_form.tpl:</p> <pre><code><tr> <td>Categories</td> <td><select> <option value="">All Categories</option> <?php foreach ($categories as $category) { ?> <option value="<?php echo $category['name']; ?>"><?php echo $category['name']; ?></option> <?php } ?> </select> </td> </tr> </code></pre> <p>but it's not working. It returns nothing.</p> <p>I wish someone could help me and tell me what I'm missing.</p> |
14,856,091 | 0 | jQuery click event triggered multiple times off one click <p>I am having trouble with multiple clicks being registered in jQuery when only one element has been clicked. I have read some other threads on <a href="http://stackoverflow.com/questions/2024389/jquery-click-event-is-firing-multiple-times-when-using-class-selector">Stack Overflow</a> to try and work it out but I reckon it is the code I have written. The HTML code is not valid, but that is caused by some HTML 5 and the use of YouTube embed code. Nothing that affects the click.</p> <p>The jQuery, triggered on document.ready</p> <pre><code>function setupHorzNav(portalWidth) { $('.next, .prev').each(function(){ $(this).click(function(e){ var target = $(this).attr('href'); initiateScroll(target); console.log("click!"); e.stopPropagation(); e.preventDefault(); return false; }); }); function initiateScroll(target) { var position = $(target).offset(); $('html, body').animate({ scrollLeft: position.left }, 500); } } </code></pre> <p>Example HTML</p> <pre><code><nav class="prev-next"> <a href="#countdown-wrapper" class="prev">Prev</a> <a href="#signup-wrapper" class="next">Next</a> </nav> </code></pre> <p>In Firefox one click can log a "Click!" 16 times! Chrome only sees one, but both browsers have shown problems with the above code.</p> <p>Have I written the code wrongly or is there a bug?</p> <p>-- Some extra info ------------------------------------------</p> <p>setupHorzNav is called by another function in my code. I have tested this and have confirmed it is only called once on initial load.</p> <pre><code>if ( portalWidth >= 1248 ) { wrapperWidth = newWidth * 4; setupHorzNav(newWidth); } else { wrapperWidth = '100%'; } </code></pre> <p>There are mutiple instances of nav 'prev-next'. All target different anchors. All are within the same html page.</p> <pre><code><nav class="prev-next"> <a href="#video-wrapper" class="prev">Prev</a> </nav> </code></pre> |
13,171,436 | 0 | <p>put this in you viewDidLoad, and i think you will get what you need.</p> <pre><code>UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"yourTitle" style:UIBarButtonItemStylePlain target:nil action:nil]; self.navigationItem.backBarButtonItem = backBarButtonItem; [backBarButtonItem release]; </code></pre> |
14,377,350 | 0 | Draw Graphics on JPanel as insert opertaion on JTextArea are made <p>Hello Everyone and thx in advance. So my problem is I want to draw on a JPanel something on condition on what's been inserted in the JtextArea is this correct? : DocumentListener to check on the insert operation :</p> <pre><code>protected class MyDocumentListener extends JPanel implements javax.swing.event.DocumentListener { @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { // text has been altered in the textarea } @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { // text has been added to the textarea try { //if not prompt Line if (!Traffic.getText(Traffic.getLineStartOffset(Traffic.getLineCount()-1), Traffic.getLineEndOffset(Traffic.getLineCount()-1)- Traffic.getLineStartOffset(Traffic.getLineCount()-1)).contains(">>")) {//if a line after a replace has been inserted if (Traffic.getLineCount() == (lastreplace + 2) ) { System.err.println(Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); PortArchitecture (Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); lastreplace +=1; } else//last line when it's not detected by the previous condition it'll be consumed here { System.err.println(Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); PortArchitecture (Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); } } Traffic.setCaretPosition(Traffic.getDocument().getLength()); } catch (BadLocationException ex) { Logger.getLogger(TrafficSerialPort.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { // text has been removed from the textarea } } </code></pre> <p>Methode to check the condition and draw on the JPanel :</p> <pre><code>public void PortArchitecture (String line) throws BadLocationException { Graphics2D gfx = (Graphics2D)graphicPanel.getGraphics(); String [] valuesId = new String [2]; valuesId = line.split(":"); /**switch (valuesId[0]) { case "Port Number" : draw(); }*/ if(valuesId[0].contains("Port number")) { gfx.drawString("(PN)", 30, 10); gfx.drawString(valuesId[1],30, 140); } if(valuesId[0].contains("Port Extension")) { gfx.drawString("(EXT)", 100, 10); gfx.drawString(valuesId[1], 100, 140); // draw(g); } if(valuesId[0].contains("Forward Extension")) { gfx.drawLine(140,80,140,110); // draw(g); } if(valuesId[0].contains("ON-HOOK")) { // draw(g); } if(valuesId[0].contains("OFF-HOOK")) { // draw(g); } if(valuesId[0].contains("Forward status")) { if(valuesId[1].contains("FORWARDED")) { // draw(g); } else { // draw(g); } } if(valuesId[0].contains("Dialing")) { //get dialed number //draw(g); } } </code></pre> <p>And another thing : I have some result concerning Showing some drawings but when I minimize the application all the graphics are gone.I know I need to call the repaint() but I don't know when and how. Help please!</p> |
24,920,553 | 0 | <p>Create a public bool variable and check against it for if the analytics have been sent previously.</p> |
2,829,829 | 0 | <p>You should be able to use the <a href="http://www.techonthenet.com/oracle/functions/case.php" rel="nofollow noreferrer"><code>CASE</code></a> construct, and it would look something like this:</p> <pre><code>select order.foo, case when sale.argle is null then 'N' else 'Y' end from order left join sale on order.product_number = sale.product_number; </code></pre> |
2,497,710 | 0 | <p>Assuming you have interop, it would be like the below. Note <code>xlValidateWholeNumber</code>, that can be changed to <code>xlValidateDecimal</code> (and the subsequent Formula1 below would need to be a decimal) for decimals).</p> <pre><code>private void SetValidationBetweenNumbers() { Microsoft.Office.Tools.Excel.NamedRange cellThatNeedsValidating = this.Controls.AddNamedRange(this.Range[""A1"", missing], "cellThatNeedsValidating"); cellThatNeedsValidating.Validation.Add( Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, "1", "=B1"); } </code></pre> |
37,053,732 | 0 | <p>In adition to the <code>break</code> statement to exit a <code>for</code> or [<code>do</code>] <code>while</code> loop, the use of <code>goto</code> is permitted to break out nested loops, e.g.:</p> <pre><code> for (i=0; i<k; i++) { for (j=0; j<l; j++) { if (someCondition) { goto end_i; } } } end_i: </code></pre> |
35,564,970 | 0 | How to format a time stamp in C <p>I'm trying to figure out how to get the current timestamp using the function below but I want to format it so that it displays the time like 4:30:23 on output. Eventually I want to subtract the time stamps before and after I run an algorithm.</p> <pre><code>struct timeval FindTime() { struct timeval tv; gettimeofday(&tv,NULL); return tv; } int main() { printf("%ld\n",FindTime()); return0; } </code></pre> <p>Current output format: 1456178100</p> |
13,290,350 | 0 | <p>You can manage privileges at the column-level: <a href="http://dev.mysql.com/doc/refman/5.1/en/grant.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/grant.html</a>.</p> |
24,779,303 | 0 | <p>You should read some basic CI first:</p> <pre><code>function index() { $this->load->model('setting/model_setting'); //load model if( $this->input->post(null) ){ //detect if form is submitted if(null !==($this->input->post('config_template'))) { $data['config_template'] = $this->input->post('config_template'); } else { $data['config_template'] = $this->theme->get('value'); // Auto loaded Library Theme } if($this->form_validation->run()) { $this->model_setting->updateTheme(); } redirect('setting/store'); }else{ // load view only $data['templates'] = array(); $directories = glob(DIR_CATALOG . 'views/theme/*', GLOB_ONLYDIR); foreach ($directories as $directory) { $data['templates'][] = basename($directory); } $this->form_validation->set_rules('config_template', '', 'callback_validate'); $this->lang->load('setting/setting', 'english'); $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->lang->line('text_home'), 'href' => site_url('common/dashboard') ); $data['breadcrumbs'][] = array( 'text' => $this->lang->line('heading_title'), 'href' => site_url('setting/setting') ); $data['action'] = site_url('setting/setting'); $data['title'] = "Settings"; $data['entry_template'] = $this->lang->line('entry_template'); $data['header'] = $this->header($data); $data['footer'] = $this->footer($data); $this->load->view('setting/setting', $data); } } </code></pre> <p>You should first check if there is any post request, if there is update and redirect else show the form.</p> |
13,425,698 | 0 | <p>The signature of <code>foo1</code> is <code>void(int)</code>, not <code>void()</code>. This is why it isn't convertible to <code>void(*)()</code>.</p> <p>You are confusing default arguments with overloading.</p> |
29,276,798 | 0 | Read microsoft office files with out Office installed for a site hosted on GoDadday <p>Is it possible to read and open files through c# without MS Office installed. I have a site hosted in godaddy that particular code which reads word Works locally but not in live site. This is the m,ethod that im using to read the content of the uploaded file (both doc or docx) but its not working in GoDaddy</p> <pre><code>public static string ReadResume(string path) { try { string contentOfResume = string.Empty; Application application = new Application(); Document doc = application.Documents.Open(path, Type.Missing, true); application.Selection.WholeStory(); application.Selection.Copy(); contentOfResume = application.Selection.Range.Text; application.Quit(false, false, false); return contentOfResume; } } </code></pre> <p>I have tried </p> <blockquote> <p>NetOffice</p> </blockquote> <p>But it didnt worked as i noticed that internally it uses word interop and they mentioned it is not a replacement.</p> <p>So I would like to know if there are any Free C# Libraries available.</p> |
40,761,667 | 0 | Regenerate location pop up even after it's denied - Browser <p>Using JavaScript, is it possible to clear location preferences stored in the browser so that even if I've denied the location permission once, the pop up can be regenerated. Alternatively, if the above cannot be achieved then can I generate a link that allows a user to navigate to the location settings option?</p> |
21,630,727 | 0 | <p>You are not allowed to use block level elements like <code><div></code> inside of a <code><p></code>. Your browser fixes this mistake for you by ending the <code><p></code> before openeing the <code><div></code> - and Firebug displayes the fixed HTML.</p> <p>It would be wise to change your <code><p></code> to <code><div class="something"></code>.</p> |
8,843,176 | 0 | <p>You might be interested in looking at <a href="http://nrabinowitz.github.com/pjscrape/" rel="nofollow">Pjscrape</a> (disclaimer: this is my project). It's a web-scraping tool built on PhantomJS, giving you full jQuery access to the page in a headless Webkit browser context. It makes it very easy to pull semi-structured data from webpages via the command line, particularly if the page you're scraping has a consistent structure for new elements.</p> <p>For example, you can pull all the course titles from <a href="http://www.ischool.berkeley.edu/courses/catalog" rel="nofollow">this course catalog</a> with the following code:</p> <pre><code>pjs.addScraper( // the page you're scraping 'http://www.ischool.berkeley.edu/courses/catalog', // selector for elements you want to pull text from '.views-row .views-field-title' ); // suppress STDOUT logging pjs.config('log', 'none'); </code></pre> <p>Running this from the command line gives you JSON to STDOUT by default:</p> <pre><code>~> phantomjs /path/to/pjscrape.js my_script.js ["W10. Introduction to Information","24. Freshman Seminar", ...] </code></pre> <p>So it would be pretty simple to run this script on a regular basis, capture the output in a file, and then alert you when the new output doesn't match the previous scrape. You can also write your own scraper functions, so there's a lot of flexibility for more complex scraping if a simple selector won't do the trick.</p> |
18,054,847 | 0 | Doing operations in a while loop until a key combination is invoked c++ <p>I have the following issue. I want to do some certain operations in a Linux terminal until the key combination CTRL+D is invoked. I have found a C++ library function for Windows that can do this, but no easy solution for Linux. The code skeleton will be something like this:</p> <pre><code>while(!invoked){ //Until CTRL+D is pressed //Do something } //Continue when CTRL+D is invoked </code></pre> <p>Is this possible?</p> |
14,869,717 | 0 | <p>Here is code to drop an outside element into a canvas and report the drop coordinates:</p> <pre><code><!DOCTYPE HTML> <html> <head> <style type="text/css"> #dragMe{border:3px solid blue; width:60px; background-color:cyan; line-height:30px;} canvas{border:3px solid red;} </style> <script> function allowDrop(ev){ ev.preventDefault(); } function drag(ev){ ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev){ ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); alert("You dropped [#"+data+"] in the canvas at: X="+ev.clientX+" and Y="+ev.clientY); } </script> </head> <body> <p>Drag the text to the red canvas</p> <canvas id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></canvas> <br> <p id="dragMe" src="house-icon.png" draggable="true" ondragstart="drag(event)">Drag Me</p> </body> </html> </code></pre> |
6,201,656 | 0 | <p>You might want to use GhostDoc to do all the heavy lifting for you (like the parameters documentation for example) so that you can concentrate on providing meaningful information for the remaining elements (the summary in that case).</p> |
2,801,350 | 0 | <p>There are <a href="http://nmaven.codeplex.com" rel="nofollow noreferrer">NMaven</a> and <a href="http://incubator.apache.org/npanday/" rel="nofollow noreferrer">NPanday</a>, and they both have the same origin. They are a collection of Maven plugins that enable a Maven-like built of C# and VB.NET projects.</p> <p>NMaven seems dead, this is why I use NPanday. I recently joined the team, and it is quite active. The current release is 1.1. Version 1.2 is coming soon, and we are also working on the next major release.</p> <p><strong>You should use it...</strong></p> <ul> <li>When you like Maven</li> </ul> <p><strong>You shouldn't use it...</strong></p> <ul> <li>When you like MSBuild (this will become better in 2.0)</li> <li>When you need localized resource assemblies (will be fixed in 1.2)</li> </ul> |
39,547,641 | 0 | <ol> <li>Interfaces do not have fields. That should make the memory layout a lot easier.</li> <li>The memory layouts will have each of the vtables in separate locations in memory. Remember that vtables do not have the method implementations themselves, but a reference to where in memory the method starts. That allows all methods to be at the correct place relative to the start of the vtable.</li> </ol> |
29,372,496 | 0 | <p>We use a simular approach. We use an Oracle database as primary datastore. </p> <p>We use PLSQL to flatten/convert data. For initial load we add data(records) to a "oneshot" table. Updates of the data will be flatten/converted and result in records in an "update" table. The oneshot and update table will be mapped to a single index in Elasticsearch.</p> <p>Initial load of ES:</p> <p>[Oracle DB]--->flatten data (pl sql)-->[records to animal_oneshot_river table, records to user_oneshot_river table]</p> <p>The data will be pulled by the river to for example <a href="http://localhost/9200/zoo/animal" rel="nofollow">http://localhost/9200/zoo/animal</a> and <a href="http://localhost/9200/zoo/user" rel="nofollow">http://localhost/9200/zoo/user</a>)</p> <p>Updates</p> <p>[Software]---->Change data--->[Oracle DB]--->flatten data (pl sql)-->[records to animal_update_river table, records to user_update_river table]</p> <p>The update tables also contains a type of change (insert, update or delete).</p> <p>The river wil poll the update_river tables for updates and mutates the data in Elasticsearch (we use a pull). The records will be deleted after processing by the river.</p> <p>Data changes to Elasticsearch won't be send to Oracle. All changes on the primary datastore will be done by our own bussiness logic software.</p> <p>We also write data to _spare tables (animal_oneshot_river_spare) because that makes it possible to reload the Elasticsearch without downtime and without synchronisation issues (we switch aliasses after reloading Elasticsearch). </p> |
1,896,233 | 0 | <p>See <a href="http://www.jakpsatweb.cz/css/css-vertical-center-solution.html" rel="nofollow noreferrer">Vertical Centering in CSS</a>.</p> <blockquote> <pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>Universal vertical center with CSS</title> <style> .greenBorder {border: 1px solid green;} /* just borders to ser it */ </style> </head> <body> <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;"> <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;"> <div class="greenBorder" style=" #position: relative; #top: -50%"> any text<br> any height<br> any content, for example generated from DB<br> everything is vertically centered </div> </div> </div> </body> </html> </code></pre> </blockquote> |
12,190,522 | 0 | FtpWebRequest Trying to insert all filenames in folder into sql table? <p>Using the following program I'm trying to insert all the filenames listed in a folder on ftp server into a SQL table.</p> <p>While Writing to table I'm getting an error </p> <blockquote> <p>c# cannot access a disposed object. object name 'system.net.sockets.networkstream'</p> </blockquote> <p><strong>reader.ReadToEnd()</strong> Writing the whole stream where I want one by one filename.</p> <pre><code>namespace Examples.System.Net { public class WebRequestGetExample { public static void Main() { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myftpaddress.com/0708/"); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential("vish10", "MyPasswd"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); Console.WriteLine(reader.ReadToEnd()); SqlConnection sqlConnection1 = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DMSTG;Data Source=."); SqlCommand cmd = new SqlCommand(); cmd.CommandText = @"Insert into FTPfileList0708Folder values('" + reader.ReadToEnd().ToString() + "')"; cmd.Connection = sqlConnection1; sqlConnection1.Open(); cmd.ExecuteNonQuery(); sqlConnection1.Close(); Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription); reader.Close(); response.Close(); } } } </code></pre> |
25,518,385 | 0 | <p>I guess this is just the way of thinking in general. When you really think about a deep if statement, you think if that statement is true, not the other point of view. It's not wrong, but in my head naming it inverse, would annoy me and make me lose concentration about the statement. So I would say it's just the way people think :D.</p> |
13,559,794 | 0 | MYSQL Insert...on duplicate value insert again with increment <p>I have 5 columns a, b, c, d and e. I want to insert values into first 4 columns and have kept default value as 1 in last column. I have kept the first 4 columns as primary keys. If duplicate values are inserted in the first 4 columns, then I want to insert the same values again but with increment in the 5th column. Eg: if 1,2,3,4 are values for the first 4 columns. then when 1,2,3,4 comes again they need to be inserted as 1,2,3,4 but with fifth column as 2.</p> |
37,471,579 | 0 | What is the function of the "loginName = "Friend"" below? <p>The loginName here is input for username. I assume that the "loginName = "Friend" will display "Friend" as default username if there is no input, but it's not right. So what is the meaning of that code and if I want to display "Friend" as default, How can I do?</p> <pre><code>package com.example.rubit.interactivestory.ui; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.example.rubit.interactivestory.R; public class Story extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_story); Intent intent = getIntent(); String loginName = intent.getStringExtra(getString(R.string.login_name)); if (loginName == null) { loginName = "Friend"; } Toast.makeText(this,loginName,Toast.LENGTH_LONG).show(); } } </code></pre> |
9,622,744 | 0 | <p>Let me provide you a better way to do it, without using .DocumentText and having to parse all those strings, erk.</p> <p>If wbMain is your WebBrowser1 control, do the following.</p> <p>First, you need to get a ref to your element, lets say you want to access the first <code><A></code> link, on your page, you can loop through all if you want.</p> <p>This is in VB, but its the same sort of thing in C#, just different syntax.</p> <pre><code>Dim i As Integer Dim aElement As HTMLAnchorElement = wbMain.Document.All.getElementByTagName("A")(0) For i = 0 To aElement.attributes.length - 1 MsgBox aElement.attributes.item(i).name & "=" & aElement.attributes.item(i).value Next i </code></pre> <p>This will loop through all attributes and display it in a MSGBOX in a <code>name=value</code> format.</p> <p>If you want to retreive it by name (attributes name) just call using <code>aElement.getAttribute("target")</code> to retreive the target attributes value from the a Link.</p> <p>If you want to confirm you got the right object/element, just do a <code>aElement.outerHTML</code> to get the full HTML code for that element only.</p> <p>Since I am using a pre.NET version, feel free to change the declaration from HTMLAnchorElement to IHTMLAnchorElement if it gives you trouble, of course, you can just use IHTMLElement if you want to go through all elements on a page, then all you'll need to do is wbMain.Document.All(0) for first element on a page, or loop until .All.length - 1 to go through all. Remember if you are using nested For loops, don't use i twice, use j for one of them :).</p> <p>Let me know if this answers your question or if there is more I can do to help you with your issue.</p> |
6,695,398 | 0 | <p>In the current standard, tokenization is greedy, so <code>>></code> will be processed as a single token, in the same way that <code>a +++ b</code> will be parsed as <code>a ++ + b</code>. This has changed and the new standard. While it requires more work from the compiler implementors, it was deemed that overall it is worth it (and some mayor compilers already implement that as an extension anyway).</p> |
2,232,131 | 0 | <p>there is not [yet] a version of numpy that has been ported to Python 3. </p> <p>the last update I heard from the people on the project was this: <a href="http://blog.jarrodmillman.com/2009/01/when-will-numpy-and-scipy-migrate-to.html" rel="nofollow noreferrer">http://blog.jarrodmillman.com/2009/01/when-will-numpy-and-scipy-migrate-to.html</a></p> <p>for now, if you need Numpy, you are stuck with Python 2.x</p> |
8,568,429 | 0 | Better approach for displaying two php var with jquery ajax <p>I'm getting two random values from a table. The values are in the same row.</p> <pre><code><?php $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection); $row = mysql_fetch_array($result); echo $row["name"]; echo $row["surname"]; ?> </code></pre> <p>And I want to display these two values at different div's on my html page by using jquery ajax functions.</p> <pre><code>$(function() { $("#sentence-form").submit(function() { $.ajax( { type : "GET", url : "newperson.php", success : function(response) { $("#top-container").append(response); /* Both name and surname */ } }); }); }); </code></pre> <p>The problem is seperating two values to display different in div's. I tried to use two ajax calls and I sended a boolean data to php to use with an if statement. So one of the ajax calls displays name and the other one displays surname. But because of randomization its a bit complicated to find surname of a name. </p> <p>Could you advise me a better approach?</p> |
12,384,526 | 0 | <p>I may have misinterpreted your question as your terminology is unclear.</p> <blockquote> <p>Entity E contains two kinds of entries: publicly visible entries... and private entries.</p> </blockquote> <p>Do you mean that your "entity E" (a CRM entity definition) contains publicly accessible <em>attributes</em> and private <em>attributes</em> (<strong>this is what I have assumed</strong>) or do you mean that some of the <em>records</em> that are of type "Entity E" are public and some private?</p> <hr> <p>I would recommend that you investigate the CRM 2011 "<a href="http://msdn.microsoft.com/en-us/library/gg309608.aspx" rel="nofollow">Field Level Security</a>" (FLS) concept. This allows you to secure a subset of fields and make them only available to specific users (i.e. it is <strong>not</strong> tied to a role). This security is applied to CRM views as well as forms so it should fit your scenario of having all web-based requests coming via an impersonated user.</p> <p>FLS does have a performance impact. In a high-volume scenario, you might consider moving your "private" attributes to a new entity, relating it to your original public entity and securing access to the private entity separately.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.