id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23528100
function myfunction(){ eval("return;"); echo 'this line has to not show up'; } For technical reasons, the decision to return (or not) from the function, has to be made in the eval instruction, but the above approach doesn't work. How can I make this work? A: You can't. The contents of the eval are considered their own context, so "return" is interpreted as exiting the eval'd string, and returning control to the function. A few alternatives to consider: * *Return a value from the eval string determining the action to take, e.g. if ( eval('return true;') ) { return; } *Throw an Exception inside the eval'd string, and catch it wherever you call this function. *Don't use eval in the first place. There is pretty much always a better approach than using eval. Without knowing what you're using this code for, I can't be more specific, but I would strongly recommend changing your design rather than continuing down this route.
doc_23528101
I am trying to login to a site and download a file using VBA and an InternetExplorer object. The problem is that once the code clicks on the hyperlink I get a prompt from Internet Explorer (version 10 in my case): "Do you want to open or save "file.xls"? What do I do now? Here is what I have tried: * *URLDownloadToFile. This doesn't work because the file is not accessible without logging in. *Disabling the open/save prompt in Internet Explorer. Also no go. This prompt is designed as a security "feature" and is designed not to be disabled. Some people have mentioned that manually putting in registry keys could do the trick, but it has not worked for me. (Maybe I am not doing the right registry keys? *Is there an download manager add in for Internet Explorer that disables the prompt? I have not found one yet. *SendKeys ("%o") '(Alt + o). This should 'click' Open file. Why not use it? Because it's not reliable. The user sometimes switches the active window away. (Is there a way to "SendKeys" to a specific window?) *Using WinHttpRequest. This should probably work, but it seems like it is a lot of work to learn how to use the WinHttpRequest, and to rewrite all of my code. (Maybe lazy people have more work) Besides, debugging WinHttpRequest would seem to be much more difficult as the actions are not visible while in IE I can watch what is happening. *iMacros. Theoretically, once I enter the fields in the web site I can use iMacros to download the file. The problem with iMacros is that it takes time to load and close. It would have to load FireFox with the iMacro, then load the Web site and then close Firefox. My VBA program is designed to download hundreds of files. Help! Thank you. A: The solution is to use cURL rather than trying to enlist the "help" of Explorer. You can find details of how to do this at Equivalent cURL in VBA? . But instead of sending the response to a MsgBox you would open a file and write to it. Of course this is really using WinHTTPRequest and you already said in your question "that seems like a crazy amount of work" - so I'm not sure you will be happy with the solution. Note - there is a tricky use of the Options property - you can find details of how to use it at http://msdn.microsoft.com/en-us/library/windows/desktop/aa384108(v=vs.85).aspx . In the example given, the option SslErrorIgnoreFlags is set to 13056 - that is 0x3300 which means "ignore any and all errors" since it's the sum of Unknown certification authority (CA) or untrusted root 0x0100 Wrong usage 0x0200 Invalid common name (CN) 0x1000 Invalid date or certificate expired 0x2000 I hope this is enough - given the detail of your question, I have little doubt! Another suggestion (not sure if this is practical) - use a platform other than VBA. There are many advanced languages with toolboxes just for this purpose. My personal favorite is cURL in PHP, but there are some really good options in Python as well. But whether that makes any sense depends really on what you are trying to connect this into.
doc_23528102
Steps to reproduce my issue: * *User open a new HOME tab in firefox. *He/she visits my app -> app stores some data in session storage *He/she clicks move back button. -> user again is on the home tab. *He/she clicks move forward -> again user visits my app. At this point, session storage is empty (checked it through developer tool and from javascript code) My problem happens only on windows 10 machines with firefox version 78.15.0esr. When I change 'open a new tab as' option in firefox from Home Tab to Blank Tab, session storage is not wiped and I have an access to my data. I've checked the same flow on different browsers, system(ubuntu) and machines and it was the same - problem was only on windows 10 using firefox. As a side note, I cannot use local storage since I need to handle users sessions per different tabs. My question is what will be the best solution for it? should I somehow detect that user is trying to access firefox home tab and prevent it? EDIT: Just to prove that my app does not make any issues, I've checked it directly from the browser console and the result is the same. Looks like it's probably a firefox bug. But my question is still active since my app requires to be fully compatible. Thanks
doc_23528103
scala version: 2_10_6 code example trait Service { def process(s: String) } object ServiceImpl extends Service{ override def process(s: String): Unit = { println(s) } } object Register { var serviceInst : Service = ServiceImpl } object Client1 { def process1(l: List[String]): Unit ={ l.foreach(x => Register.serviceInst.process(x)) } } object Client2 { def process1(l: List[String]): Unit ={ l.foreach(Register.serviceInst.process) } } I assume that process1 and process2 should have the similar behaviour. However, after comilation / decom public final class Client1$$anonfun$process$1$$anonfun$apply$1 extends AbstractFunction1<String, BoxedUnit> implements Serializable { public static final long serialVersionUID = 0L; public final void apply(final String x$1) { Register$.MODULE$.serviceInst().process(x$1); } } public static final class Client2$$anonfun$process$1 extends AbstractFunction1<String, BoxedUnit> implements Serializable { public static final long serialVersionUID = 0L; private final Service eta$0$1$1; public final void apply(final String s) { this.eta$0$1$1.process(s); } } A: It's because Scala compiler performs eta-expansion on method given in Client2, which works by generating Function that calls process directly on a concrete Service instance. Here is an example how these functions look like before they are turned into bytecode: object Client1 { def process1(l: List[String]): Unit = { l.foreach(new Function1[String, Unit] { def apply(x: String) = Register.serviceInst.process(x) }) } } object Client2 { def process1(l: List[String]): Unit = { l.foreach(new Function1[String, Unit] { val eta = Register.serviceInst def apply(x: String) = eta.process(x) }) } } A: It's become more interesting if we rewrite serviceInst a bit: object Register { def serviceInst : Service = { println("get service instance!!!") ServiceImpl } } And then execute: Client1.process1(List("a","b")) Client2.process1(List("a","b")) Obviously results are different: 1. get service instance!!! a get service instance!!! b res0: Unit = () 2. get service instance!!! a b res1: Unit = () Explanation is behind parameter of foreach function: Client1 contains function as below, that executes each invocation x => Register.serviceInst.process(x) Client2 has function process that's going to be executed, but firstly serviceInst is about to be initialized. A: The line below l.foreach(x => Register.serviceInst.process(x)) is operationally equivalent to l.foreach(Register.serviceInst.process) The first one is called "point-ful style" while the second is "point-free style", or more specifically "eta-conversion", with the term "point" referring to the named argument which doesn't exist in the second case. They are two different concepts and thus compile differently. You can write code in point-free style and the Scala compiler is eta-expanding it internally, which is what you're seeing in the decompiled code for Client2. eta conversion is a term from Lambda Calculus. If the sole purpose of a lambda abstraction is to pass its argument to another function, then the lambda is redundant and can be stripped via eta conversion/reduction. Java's Lambda Expressions vs Method References is another example.
doc_23528104
Second, here is my AndoidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.Alan.Gym_Rat" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".GymRatActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="mainmenu" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Does that look right? Because When I run the emulator, it shows two icons, so im not sure if I set things up right. The only addition I have made really is to get rid of the title bar. Third and last, how do you specify the name of the app icon so its not the default name of the AVD? A: Yes, you do have to create a new activity entry in the manifest file for each activity. The reason why you see two icons is because you marked them both with android.intent.category.LAUNCHER. That should be reserved for things you want to show up in the launcher. Likewise, the MAIN action should only be used for the main entry point of your app. By the way, what are the class names of your activities? I'll assume it's not mainmenu, so you need to adjust the name to the actual class name. Also, you should prepend a dot (so if the class name is MainMenu, write .MainMenu). And the name should be what you specify in the label. A: I would like to comment above but my reputation still not enough. The name that appears in the icon label is determined by app_name which is defined in strings.xml. A: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.Alan.Gym_Rat" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".GymRatActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainMenu" android:screenOrientation="portrait" /*In case you want to set orientation of screen.In similar you can use other properties according to requirement*/ > </activity> </application> </manifest>
doc_23528105
when I assign setCharacters(arrayOfObj); export type CharacterItem = { filepath: string; group: string; id: string; isClicked: boolean; } export type Character = { name: string; items: CharacterItem[] } xxxxxx const [characters, setCharacters] = useState([]); xxxxxx setCharacters(arrayOfObj); # the error is here so a lint error is highlighted underneath arrayOfObj saying const arrayOfObj: unknown[] Argument of type 'unknown[]' is not assignable to parameter of type 'SetStateAction<never[]>'. Type 'unknown[]' is not assignable to type 'never[]'. Type 'unknown' is not assignable to type 'never'. A: You are using it wrong I guess. Character type is not an array already and also your useState hook does not use your type as well. This may fix it: export type Character = { name: string; items: CharacterItem[] }[] const [characters, setCharacters] = useState<Character>([]);
doc_23528106
I have abstract state "course", and if I resolve the data just in that abstract state, the data didn't refreshed when routing between sub views. state('course', { url: '/course/:courseId', abstract: true, resolve: { courseId : ['$stateParams', function($stateParams){ return $stateParams.courseId; }], editions : ['courseId', 'ApiSvc', function(courseId, api){ return api.editionsList(courseId); }] }, now, i want the editions to resolve (and be updated) in state 'course.answers','course.questionnaire.questions' and in 'course.questionnaire.editions', so i can repeat this resolve in their state, but how can I resolve same data in multiple states, so it will be updated, and without long duplication of code? thanks!
doc_23528107
* *If the desired temperature is higher than the current temperature, this popup message should show: "Turn the heater on?". *If the desired temperature is lower than the current temperature, this popup message should show: "Turn the cooler on?" I have tried to produce this but my code doesn't seem to be producing anything upon clicking the "Set" button. Any help would be much appreciated! class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label1=ttk.Label(self,text="Smart Thermostat",font=LARGE_FONT) label1.pack(pady=10, padx=10) label2 = ttk.Label(self, text="Current Temperature:",font=MEDIUM_FONT) label2.pack(pady=10, padx=10) slider1 = tk.Scale(self, from_=10, to = 30, orient=HORIZONTAL) slider1.pack() label3 = ttk.Label(self, text="Set to:",font=MEDIUM_FONT) label3.pack(pady=10, padx=10) slider2 = tk.Scale(self, from_=18, to = 25, orient=HORIZONTAL) slider2.pack() def popupmsg1(msg): popup1=tk.Tk() popup1.wm_title("!") label4 = ttk.Label(popup1, text="Turn heater on?", font = MEDIUM_FONT) label4.pack(side = "top", fill = "x", pady=10) button2=ttk.Button(popup1, text="Okay", command = popup1.destroy) button2.pack() popup1.mainloop() def popupmsg2(msg): popup2=tk.Tk() popup2.wm_title("!") label5 = ttk.Label(popup2, text="Turn cooler on?", font = MEDIUM_FONT) label5.pack(side = "top", fill = "x", pady=10) button3=ttk.Button(popup2, text="Okay", command = popup2.destroy) button3.pack() popup2.mainloop() def popupmsg(): temp=int(slider2.get()) need=int(slider1.get()) if temp<need: popup1=tk.Tk() else: popup2=tk.Tk() button1=tk.Button(self, text="Set", command= lambda: popupmsg) button1.pack(pady=10, padx=10) A: You should be able to create your messages / dialog using the info below: # Python 3 from tkinter import messagebox # Python 2 import tkMessageBox as messagebox if case 1: messagebox.showinfo("title 1", "message 1") else: messagebox.showinfo("title 2", "message 2") You typically only spawn custom windows for really custom info boxes / windows that do their own logic. For simple messages it suffices to use the built in message box. Even then you should just use Toplevel instead of spawning entirely new tk.Tk instances. Tk is just one big mainloop (hence using .mainloop()....) which processes events within it. How you choose to display messages to a user is really open-ended you could even make a label that updates the text and shows / hides it appropriately etcetera. If you want to do custom fonts etcetera which it looks like... without digging through all of your code... you'd actually have to go the Toplevel / widget route.
doc_23528108
I have a basic grid where the 2 columns should be taking up 50% each but it looks like the gap is throwing this off. How would I account for that and maintain body margins? .grid-container { display: grid; grid-template-columns: 50% 50%; grid-template-rows: 200px 200px; grid-gap: 20px; margin: 40px; } .grid-item { background-color: red; justify-content: center; } .g1 { grid-column-start: 1; grid-column-end: 3; } <div class="grid-container"> <div class="grid-item g1"> foo </div> <div class="grid-item"> </div> <div class="grid-item"> </div> <div class="grid-item"> </div> </div> A: For the columns, try doing box-sizing: border-box; and remove the grid-gap property. The box-sizing makes the CSS take into account padding and borders.
doc_23528109
The code I have so far is below: Private Function RunScript(ByVal scriptText As String) As String ' create Powershell runspace Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace() MyRunSpace.Open() ' create a pipeline and feed it the script text Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline() MyPipeline.Commands.AddScript(scriptText) MyPipeline.Commands.Add("Out-String") ' execute the script Dim PSOut As Collection(Of PSObject) = MyPipeline.Invoke() ' close the runspace MyRunSpace.Close() For Each Id In PSOut CheckList1.BeginUpdate() CheckList1.Items.Add(Id) CheckList1.EndUpdate() Next End Function All this does is display the first line of the PowerShell output and nothing else. What am I missing? I thought maybe it needs to be told to loop through the collection, but I cant find anything like that in my searches thus far... Any help will be appreciated. Phill A: Your problem is in this line: MyPipeline.Commands.Add("Out-String") Just remove it. It's causing your output to be formatted as a string. Meaning after that you need to parse it back to a list of string, and then potentially do even more parsing. You don't need all that, because it's much easier to work with a list of PSObject, when each of them is actually a PSObject, and not a string wrapper. Also regarding process format, you may consider using this instead of just Id: Id.Properties("Name").Value.ToString() This will populate your checklist control with a list of process names. Also consider changing your variable name, i.e. Id to psProcess, to reflect what it really is.
doc_23528110
Does ES have to do anything with it? A: Take a look at Suggesters "The suggest feature suggests similar looking terms based on a provided text by using a suggester. Parts of the suggest feature are still under development." A: you can use this:http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html using term suggest,it can fix you wrong word from it's dictionary.
doc_23528111
I have encoded ransom note from Locky(the pkt2 below). And I have decompiled C code to decode the ransom note(in comments). I tried to translate the C code to Python. Below is what I have: # v29 = 0; # v30 = -1342924972; # while ( v29 < v62 ) # { # v31 = (int *)v60; # v32 = __ROL4__(v30, 3); # v33 = *((_BYTE *)v31 + v29) - v29 - v32; # v34 = (int *)v60; # *((_BYTE *)v34 + v29) = v33; # v35 = __ROR4__(v33, 11); # v36 = __ROL4__(v30, 5); # v30 = v30 + (v29++ ^ v36 ^ v35) - 1204489519; # } def decode_msg(dstr, str_len): bstr = list(dstr) v29 = 0 v32 = 0 v33 = 0 v35 = 0 v30 = 0xAFF49754 while(v29 < str_len): v32 = ((v30 & 0xffffffff) << 3) & 0xffffffff v33 = ((ord(bstr[v29]) & 0xff) - v29 - v32) & 0xff bstr[v29] = chr(v33 & 0xff) v35 = ((v33 & 0xffffffff) >> 11) & 0xffffffff v36 = ((v30 & 0xffffffff) << 5) & 0xffffffff v29 = v29 + 1 v30 = (v30 & 0xffffffff) + (v29 ^ v36 ^ v35) - 1204489519 return ''.join(bstr) print decode_msg(str(pkt2), len(str(pkt2))) Run above code I couldn't get meaningful result. The result should be mostly English text. So where is wrong? The Python code doesn't match the C code? The pkt2 is: pkt2 = bytearray([ 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x0d, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x6e, 0x67, 0x69, 0x6e, 0x78, 0x0d, 0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x32, 0x35, 0x20, 0x46, 0x65, 0x62, 0x20, 0x32, 0x30, 0x31, 0x36, 0x20, 0x30, 0x33, 0x3a, 0x30, 0x34, 0x3a, 0x33, 0x38, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3b, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x55, 0x54, 0x46, 0x2d, 0x38, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x31, 0x30, 0x38, 0x39, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6b, 0x65, 0x65, 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x0d, 0x0a, 0x56, 0x61, 0x72, 0x79, 0x3a, 0x20, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x45, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x0d, 0x0a, 0x0d, 0x0a, 0xb1, 0x8a, 0x5d, 0x46, 0xb3, 0x6f, 0x9c, 0xf9, 0x50, 0x02, 0x3b, 0x04, 0x7b, 0x60, 0xf7, 0x50, 0x39, 0x5d, 0x97, 0xc5, 0x13, 0xe2, 0x81, 0xe1, 0x55, 0x56, 0x57, 0x48, 0x2f, 0x45, 0xb4, 0x5f, 0xf1, 0x86, 0xa2, 0x6b, 0xdd, 0x06, 0x9e, 0x3c, 0x1e, 0xb0, 0xcc, 0x2e, 0x32, 0x9b, 0xf3, 0xf0, 0x92, 0x06, 0x6d, 0x2c, 0x65, 0xe6, 0x2d, 0x65, 0x61, 0xd4, 0xeb, 0x37, 0x6d, 0xd6, 0xcb, 0xe7, 0xfd, 0x1f, 0x8a, 0xa9, 0x3e, 0x79, 0x83, 0x90, 0x8f, 0xa4, 0xf9, 0x89, 0x97, 0x6a, 0x89, 0x51, 0x71, 0x1f, 0x40, 0x63, 0x60, 0xc7, 0x1a, 0x1b, 0xef, 0x5a, 0xfb, 0xb4, 0x12, 0xd1, 0x2b, 0xa9, 0x17, 0xd1, 0x88, 0xb8, 0x66, 0x05, 0xe9, 0x81, 0xc5, 0x10, 0xa0, 0xfd, 0x8c, 0x11, 0x7c, 0xe6, 0x2e, 0x43, 0xdf, 0xa8, 0x40, 0x2c, 0xc8, 0x56, 0x4f, 0x50, 0xf9, 0xfb, 0xf1, 0xf3, 0x92, 0x80, 0x84, 0x59, 0x3e, 0x6a, 0x33, 0x8d, 0x8f, 0x85, 0xaf, 0x02, 0x4b, 0x36, 0xa9, 0xc1, 0x1f, 0x23, 0x20, 0x18, 0x84, 0xd0, 0x9d, 0x9c, 0xa2, 0x07, 0x0d, 0x97, 0x0d, 0x5d, 0xc7, 0x40, 0x48, 0xc8, 0x61, 0xd5, 0x6c, 0x0a, 0xb7, 0xc4, 0x53, 0xb3, 0x12, 0x05, 0x37, 0x8e, 0x87, 0x7c, 0xb9, 0xc5, 0x2e, 0xc1, 0x01, 0x36, 0xe5, 0x58, 0x38, 0xed, 0x16, 0xe5, 0xbe, 0x75, 0xcd, 0xa4, 0x3b, 0xa4, 0xd7, 0x41, 0xde, 0xf0, 0x68, 0xaa, 0x51, 0x96, 0xa6, 0xe3, 0x8c, 0x7b, 0x38, 0x20, 0xb1, 0x18, 0x10, 0xbe, 0x63, 0x88, 0xa4, 0x65, 0x2b, 0xa7, 0x6a, 0x9c, 0x0d, 0xab, 0x6c, 0xab, 0x8f, 0x3b, 0x18, 0xee, 0xd8, 0xc6, 0xc1, 0xee, 0xcc, 0xb1, 0x76, 0xe5, 0x39, 0xdc, 0x69, 0x33, 0x85, 0xfa, 0x07, 0x72, 0xcc, 0xdb, 0x4d, 0x38, 0x8b, 0x1c, 0xa8, 0x58, 0x22, 0xf0, 0x5c, 0xa5, 0x56, 0xa6, 0x4c, 0xc6, 0xef, 0xb8, 0x06, 0xa4, 0xd3, 0x0a, 0xda, 0x47, 0xd6, 0x89, 0xd1, 0x25, 0xf2, 0xa3, 0xbc, 0xa9, 0xd4, 0x06, 0x12, 0x73, 0x63, 0x3a, 0x2d, 0xbb, 0x49, 0xb9, 0xfc, 0x04, 0x1b, 0xb9, 0xb2, 0xb9, 0xf8, 0x0e, 0xde, 0xcd, 0xed, 0x71, 0x53, 0xb7, 0xda, 0x69, 0xf5, 0xf2, 0xfb, 0xda, 0xa7, 0x52, 0xb0, 0xd6, 0x20, 0xd5, 0xff, 0x1d, 0x05, 0x4d, 0xa3, 0xc6, 0x4a, 0x7c, 0x51, 0x8b, 0x8c, 0x1b, 0xd8, 0x65, 0x0a, 0xc8, 0x00, 0xdf, 0xf0, 0x17, 0x51, 0xe4, 0xc9, 0x5b, 0x61, 0x2a, 0x3b, 0x22, 0xaa, 0x0a, 0xf3, 0x5e, 0xce, 0xdd, 0x0f, 0x4d, 0x20, 0x00, 0xf4, 0x5a, 0x83, 0xb4, 0xa9, 0x2a, 0x4a, 0xfd, 0x1d, 0xf9, 0xe5, 0x9f, 0x1a, 0x0e, 0xee, 0x34, 0x36, 0x37, 0xf2, 0x92, 0x57, 0x79, 0x80, 0xcb, 0x02, 0x4a, 0xbb, 0xfb, 0xf0, 0x8d, 0xda, 0xe4, 0x88, 0xd0, 0x57, 0x47, 0x33, 0xff, 0x30, 0x7d, 0x7d, 0x65, 0x2d, 0x3e, 0xfc, 0x6d, 0xf0, 0x78, 0x0f, 0x15, 0x68, 0xe2, 0x70, 0x59, 0x1a, 0xeb, 0x45, 0x7a, 0xab, 0x86, 0xc8, 0x9c, 0x15, 0xf7, 0x9b, 0x10, 0x87, 0x3a, 0xf2, 0x76, 0x5c, 0x98, 0x00, 0x95, 0xa8, 0xcc, 0xa9, 0x58, 0x0a, 0xd4, 0x5e, 0xac, 0x47, 0xb4, 0x9a, 0x46, 0xb8, 0xf8, 0x45, 0x0b, 0xae, 0x23, 0xb5, 0xf4, 0x00, 0xb4, 0x83, 0x0d, 0xde, 0x4a, 0x98, 0x1c, 0x43, 0xe5, 0x2c, 0xbb, 0x82, 0x0d, 0xc4, 0x27, 0x7d, 0xf9, 0x2d, 0x90, 0x9b, 0xdd, 0x8b, 0x51, 0x7b, 0xf0, 0xbb, 0xd6, 0x39, 0x94, 0x80, 0x58, 0x00, 0x3b, 0xe8, 0x6c, 0x32, 0xf1, 0x98, 0x91, 0xb2, 0x95, 0x39, 0x51, 0x81, 0x59, 0x54, 0xfe, 0x23, 0x71, 0x8f, 0x9f, 0xcf, 0x6c, 0xf2, 0x64, 0x39, 0xa4, 0xe4, 0xd6, 0x8c, 0x3a, 0x27, 0x83, 0x9a, 0xcc, 0xe3, 0x77, 0x31, 0x13, 0xd4, 0x85, 0xae, 0x47, 0xcc, 0x5b, 0x4b, 0x6f, 0xf4, 0x2b, 0xc9, 0xff, 0x71, 0x09, 0x1d, 0x1d, 0xb6, 0x51, 0xf3, 0x39, 0x80, 0x38, 0x8c, 0xee, 0x5c, 0xa2, 0xcf, 0x56, 0x1d, 0xcd, 0x51, 0x5e, 0x87, 0xd7, 0x21, 0x8d, 0x5b, 0xc6, 0x20, 0x4c, 0xaf, 0xdf, 0x83, 0xfe, 0x8c, 0xac, 0xa7, 0xa5, 0x66, 0x45, 0x97, 0xc1, 0x5a, 0x6b, 0x13, 0xba, 0xaf, 0x11, 0x5e, 0xcc, 0x01, 0x90, 0x6d, 0x97, 0x11, 0xdb, 0xf3, 0x88, 0xcb, 0x20, 0x81, 0xd4, 0x05, 0x18, 0x69, 0xfa, 0x3c, 0x3b, 0xde, 0xd5, 0x11, 0xef, 0x17, 0xa2, 0xe6, 0xd6, 0x6a, 0x99, 0x11, 0x44, 0xd1, 0xd4, 0x5a, 0xff, 0x30, 0x85, 0x9d, 0xf1, 0xcc, 0xb3, 0xd3, 0x99, 0xa6, 0x05, 0x64, 0x1c, 0x46, 0xb4, 0xe5, 0x64, 0xb7, 0x9d, 0x8a, 0xf4, 0xcf, 0x33, 0xb4, 0x86, 0x6b, 0x3c, 0xac, 0x0a, 0x80, 0x30, 0xcf, 0xff, 0x0d, 0x2b, 0x08, 0x3c, 0x08, 0xdc, 0xc3, 0xec, 0x0b, 0xea, 0xcc, 0xa0, 0xdc, 0x70, 0x09, 0xf7, 0xd0, 0x3a, 0x50, 0xfb, 0xb3, 0xef, 0x22, 0x33, 0xf9, 0xf1, 0x67, 0x0f, 0x1a, 0xba, 0x50, 0xd6, 0x62, 0xa6, 0x15, 0x3a, 0x4a, 0x50, 0x81, 0xc5, 0x90, 0xd3, 0x9d, 0x8e, 0x9b, 0xc0, 0xb5, 0xf4, 0x65, 0x33, 0xbd, 0xad, 0x3c, 0x4f, 0xf1, 0xc5, 0x35, 0x73, 0x48, 0xe1, 0xb2, 0xb2, 0x40, 0x58, 0xec, 0xbe, 0xab, 0x12, 0xf5, 0x5b, 0x34, 0x3e, 0x3d, 0x07, 0x41, 0xe4, 0xdf, 0x9a, 0x44, 0x37, 0x9f, 0xc1, 0xc0, 0x2f, 0xad, 0x8f, 0x8e, 0xfe, 0xbd, 0x17, 0x66, 0x46, 0x32, 0x93, 0xe5, 0x47, 0x8c, 0xef, 0x88, 0xc1, 0x8b, 0x49, 0xd0, 0x90, 0xc0, 0x5a, 0x5d, 0x1e, 0x70, 0x2f, 0xbd, 0xd9, 0x69, 0xb7, 0x14, 0x1d, 0x99, 0x1e, 0xb5, 0xf7, 0xff, 0x81, 0x5f, 0x35, 0x85, 0xf9, 0xa3, 0x14, 0xf0, 0xdd, 0xa3, 0x3b, 0x61, 0xdd, 0x3d, 0x4d, 0x18, 0x21, 0xc5, 0xe5, 0x95, 0xee, 0x40, 0x3d, 0x44, 0x03, 0x5c, 0xc0, 0xa6, 0xfc, 0x50, 0xc1, 0x96, 0x2f, 0x90, 0xf2, 0x15, 0x77, 0x3a, 0x09, 0x9a, 0x7d, 0xff, 0xc1, 0xdd, 0xea, 0x4c, 0x3d, 0x02, 0xce, 0x99, 0x27, 0xef, 0xf0, 0xeb, 0x25, 0x5a, 0x9b, 0x9a, 0xf2, 0xc3, 0x8f, 0x97, 0xfa, 0x06, 0x64, 0x0f, 0x1e, 0x66, 0x35, 0x41, 0x13, 0xdd, 0xb8, 0xcc, 0x08, 0x87, 0xfc, 0x1c, 0xf5, 0x07, 0xe1, 0x30, 0x6b, 0xac, 0x03, 0x81, 0x49, 0x65, 0xd0, 0x02, 0x97, 0xc2, 0x06, 0xcc, 0xa9, 0x9a, 0xb2, 0x7a, 0x04, 0xab, 0x87, 0xda, 0x03, 0xd3, 0x78, 0x5b, 0xc6, 0x49, 0x70, 0x10, 0x37, 0x81, 0xc2, 0xa0, 0x0f, 0x6a, 0x84, 0xc0, 0x10, 0x78, 0x89, 0xf8, 0x76, 0x64, 0xa1, 0xb5, 0xf5, 0x7b, 0x5d, 0xeb, 0x1b, 0x5d, 0xd6, 0xca, 0x58, 0x66, 0x23, 0x48, 0x15, 0x1a, 0x22, 0x60, 0x42, 0xe0, 0x7e, 0x6f, 0x98, 0x36, 0xe7, 0x69, 0x43, 0x19, 0x39, 0x42, 0x96, 0x3d, 0xaa, 0xb3, 0x67, 0xff, 0x50, 0x17, 0x9b, 0x9e, 0x06, 0x93, 0x42, 0x92, 0xd7, 0xc3, 0xb0, 0x3f, 0xb8, 0xd5, 0xde, 0xfa, 0xef, 0xc9, 0xde, 0x13, 0x5b, 0x66, 0x50, 0xf3, 0x60, 0x8f, 0x14, 0x87, 0xf8, 0x2c, 0x15, 0x79, 0x70, 0x85, 0xdb, 0x20, 0xa5, 0x53, 0xb1, 0x5e, 0x9d, 0xd7, 0xdf, 0x4d, 0x80, 0x9a, 0xfa, 0x00, 0xdf, 0xf3, 0x09, 0x61, 0xae, 0xdd, 0xc0, 0x4f, 0x90, 0xfa, 0x31, 0x83, 0x30, 0x86, 0x71, 0x34, 0x97, 0xeb, 0x69, 0xca, 0x29, 0xaf, 0xce, 0x91, 0x61, 0xc3, 0x11, 0xd0, 0x97, 0x27, 0x54, 0xc5, 0x5e, 0x23, 0xe3, 0x02, 0x2f, 0xe7, 0x44, 0xb3, 0x8d, 0x11, 0x89, 0x4b, 0xee, 0x4d, 0xbf, 0x7d, 0xe1, 0xa6, 0x49, 0x17, 0x59, 0x65, 0xb3, 0xc5, 0xb0, 0x55, 0x71, 0x6e, 0xa7, 0xe0, 0x3a, 0x06, 0xdc, 0xd7, 0xf6, 0x54, 0x49, 0x9e, 0x7c, 0x6f, 0xe4, 0x1a, 0xca, 0xe8, 0x25, 0x35, 0x21, 0xb3, 0x87, 0x67, 0x58, 0x5c, 0xd7, 0x31, 0xa5, 0xdb, 0x34, 0x23, 0x60, 0x9f, 0x80, 0xb1, 0x42, 0x77, 0x5f, 0x0d, 0xaf, 0x2b, 0x99, 0xd0, 0x4c, 0xb8, 0xb9, 0xbc, 0x5b, 0x15, 0x84, 0xab, 0x7f, 0x0d, 0xfe, 0x14, 0x74, 0x29, 0x45, 0x61, 0x31, 0x33, 0x31, 0x8e ]) A: bytearray holds raw bytes, so you need to do pkt2.decode() to decode them as utf-8 (this is the default, although you could specify the encoding yourself), which gives you a str. In short, just replace str(pkt2) with pkt2.decode().
doc_23528112
I have the sample xml as below: <ns0:Person xmlns:ns0="http://temp.poc"> <name> <value>temp</value> <status>T</status> </name> <age> <value>tempval</value> <status>F</status> </age> <cellNumber> <value>9971760613</value> <status>T</status> </cellNumber> <city> <value>Bangalore</value> <status>F</status> </city> <ApplicationAccess> <value>value_0</value> <status>T</status> </ApplicationAccess> </ns0:Person> Based on the Status , where status = "T" , I need the node names as output. for eg : assistant cellNumber ApplicationAccess A: You can achieve that using XmlDocument and XPath, like this: string xml = @" <ns0:Person xmlns:ns0='http://temp.poc'> <name> <value>temp</value> <status>T</status> </name> <age> <value>tempval</value> <status>F</status> </age> <cellNumber> <value>9971760613</value> <status>T</status> </cellNumber> <city> <value>Bangalore</value> <status>F</status> </city> <ApplicationAccess> <value>value_0</value> <status>T</status> </ApplicationAccess> </ns0:Person>"; var doc = new XmlDocument(); doc.LoadXml(xml); XmlNodeList nodes = doc.SelectNodes("//status[text() ='T']"); foreach (XmlNode node in nodes) { Console.WriteLine(node.ParentNode.Name); } output will be names of those nodes whose child node status has T as innerText. name cellNumber ApplicationAccess A: Using XDocument (which I prefer over XmlDocument): var root = XDocument.Load(...).Root; // the <ns0:Person> XElement var namesOfElementWithStatusT = root.Elements() .Where(e => e.Elements().Any(e1 => e1.Name == "status" && e1.Value == "T")) .Select(e => e.Name.LocalName) .ToList();
doc_23528113
<?php $q = mysql_connect('localhost', 'xxx', 'xxx'); mysql_select_db('xxx', $q); ?> <?php $sth = mysql_query("SELECT inkoop, verkoop FROM prijs WHERE inkoop >= 1 "); $rows = array(); while($r = mysql_fetch_assoc($sth)) { $rows[] = $r; } print json_encode($rows); ?> <?php $sth = mysql_query("SELECT tijd FROM prijs WHERE inkoop >= 1"); $cols = array(); while($c = mysql_fetch_assoc($sth)) { $cols[] = $c; } print json_encode($cols); ?> And it gives me this output: [{"inkoop":"516","verkoop":"484"},{"inkoop":"515","verkoop":"488"},{"inkoop":"515","verkoop":"487"}][{"tijd":"2013-12-17 23:45:00"},{"tijd":"2013-12-17 23:48:00"},{"tijd":"2013-12-17 23:52:00"}] What I need is something like this, to create a line graph: { "cols": [ {"id":"","label":"Topping","pattern":"","type":"string"}, {"id":"","label":"Slices","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]}, {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]} ] } Edit: I need a line graph with 2 lines one for 'inkoop' and one for 'verkoop', if I can use something like this link it would be even better. Thanks in advance! A: I'm not sure I completely understand your question, but it sounds like you already have the object, you just need them formatted a little bit better so you can put them into your charting software? If that's what you're wanting, I think you're already on the right track. I'd create a new object at the beginning of the script with: $json = new stdClass(); and then as you get your $rows and $cols arrays set, assign them to the object: $json->rows = $rows; ... $json->cols = $cols; and when you json_encode($json); it should look something like your example. If you're needing to do additional manipulation to the data from SQL before it's in your ideal form, it should all by doable by creating objects and adding properties to them. I hope this helps!
doc_23528114
Thank you. Here is my code: public class ButtonController implements Initializable{ @FXML private Button bubu; @FXML private Button bb; @FXML private TabPane tp; List<Button> buttonlist = new ArrayList<>(); List<Tab> tablist = new ArrayList<>(); Main parent; public void setParent(Main main) { this.parent=main; } @FXML public void action() { try { Connection conn = bddUtil.dbConnect(); tablist.clear(); buttonlist.clear(); ResultSet rs = conn.createStatement().executeQuery("select nom, prix from produit"); ResultSet res = conn.createStatement().executeQuery("select nom from type_produit"); while (res.next()) { Tab tab = new Tab(res.getString("nom")); FlowPane flowp = new FlowPane(); tablist.add(tab); tab.setContent(flowp); flowp.setAlignment(Pos.BASELINE_CENTER); while (rs.next()) { Button btn = new Button(rs.getString("nom") + "\n" + rs.getInt("prix") + "€"); btn.setPrefSize(200, 100); btn.setTextAlignment(TextAlignment.CENTER); btn.setAlignment(Pos.CENTER); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { String txtBtn = btn.getText(); } }); buttonlist.add(btn); } flowp.getChildren().addAll(buttonlist); } tp.getTabs().addAll(tablist); } catch (Exception e) { System.out.println("err: " + e); e.printStackTrace(); } } class HandlerBtn1 implements EventHandler<ActionEvent>{ public void handle(ActionEvent e) { System.out.println("ok"); } } } A: I finally found a way to do it, it may not be the best way but it works so I leave it here if someone has the same problem! @FXML private TabPane tp; List<Button> buttonlist = new ArrayList<>(); List<Tab> tablist = new ArrayList<>(); Map<String, Tab> map= new HashMap<>(); ArrayList<String> nomProduits = new ArrayList<>(); @FXML public void action() { try { Connection conn = bddUtil.dbConnect(); tablist.clear(); buttonlist.clear(); ResultSet rs = conn.createStatement().executeQuery("select produit.nom, prix, type_produit.nom from produit inner join type_produit on produit.idType=type_produit.idType"); while (rs.next()) { Tab tab = new Tab(rs.getString("type_produit.nom")); map.put(rs.getString("type_produit.nom"), tab); nomProduits.add(rs.getString("produit.nom")); } for (Tab tab : map.values()) { FlowPane fp = new FlowPane(); tab.setOnSelectionChanged(new EventHandler<Event>() { public void handle(Event event) { fp.getChildren().clear(); for (int i = 0; i < nomProduits.size(); i++) { Button btnPlat = new Button(nomProduits.get(i)); fp.getChildren().add(btnPlat); } tab.setContent(fp); } }); } tp.getTabs().addAll(map.values()); } catch (Exception e) { System.out.println("err: " + e); e.printStackTrace(); } }
doc_23528115
<td> <fieldset class="rating"> <input type="radio" id="param1" name="srating" value="5"/> <input type="radio" id="param1" name="srating" value="4"/> <input type="radio" id="param1" name="srating" value="3"/> <input type="radio" id="param1" name="srating" value="2"/> <input type="radio" id="param1" name="srating" value="1"/> </fieldset> </td> <td> <fieldset class="rating"> <input type="radio" id="param2" name="pgrating" value="5"/> <input type="radio" id="param2" name="pgrating" value="4"/> <input type="radio" id="param2" name="pgrating" value="3"/> <input type="radio" id="param2" name="pgrating" value="2"/> <input type="radio" id="param2" name="pgrating" value="1"/> </fieldset> </td> Then I want to pass checked parameters to the controller method which looks like this public void SaveRating(int CompanyId, int param1, int param2) { // ... } So the question is: How to combine all the checked parameters into one method call? I suppose to use jquery or mvc features. Also looking for the most efficient way to do it. UPDATE Can it be a solution? @using (Html.BeginForm("SaveRating", "MyController")) { <td> <input style="display:none" name="CompanyID" value="@Model.ID"/> <fieldset class="rating"> <input type="radio" id="sstar5" name="param1" value="5"/><label class="full" for="sstar5"></label> <input type="radio" id="sstar4" name="param1" value="4"/><label class="full" for="sstar4"></label> <input type="radio" id="sstar3" name="param1" value="3"/><label class="full" for="sstar3"></label> <input type="radio" id="sstar2" name="param1" value="2"/><label class="full" for="sstar2"></label> <input type="radio" id="sstar1" name="param1" value="1"/><label class="full" for="sstar1"></label> </fieldset> </td> <td> <fieldset class="rating"> <input type="radio" id="pgstar5" name="param2" value="5"/><label class="full" for="pgstar5"></label> <input type="radio" id="pgstar4" name="param2" value="4"/><label class="full" for="pgstar4"></label> <input type="radio" id="pgstar3" name="param2" value="3"/><label class="full" for="pgstar3"></label> <input type="radio" id="pgstar2" name="param2" value="2"/><label class="full" for="pgstar2"></label> <input type="radio" id="pgstar1" name="param2" value="1"/><label class="full" for="pgstar1"></label> </fieldset> </td> <input type="submit" value="Save" /> } A: I create a sample (it worked) for your requirement with GET method. Use AJAX get with URL /company/SaveRating?CompanyId=1&param1=3&param2=4 And use jquery method addOrUpdateQueryStringParameter() to build URL parameters <td> <fieldset class="rating"> <input type="radio" id="param1" name="srating" value="5"/> <input type="radio" id="param1" name="srating" value="4"/> <input type="radio" id="param1" name="srating" value="3"/> <input type="radio" id="param1" name="srating" value="2"/> <input type="radio" id="param1" name="srating" value="1"/> </fieldset> </td> <td> <fieldset class="rating"> <input type="radio" id="param2" name="pgrating" value="5"/> <input type="radio" id="param2" name="pgrating" value="4"/> <input type="radio" id="param2" name="pgrating" value="3"/> <input type="radio" id="param2" name="pgrating" value="2"/> <input type="radio" id="param2" name="pgrating" value="1"/> </fieldset> </td> <input type="button" value="rate" onclick="rate();"/> <script> function addOrUpdateQueryStringParameter(uri, key, value) { var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"); var separator = uri.indexOf('?') !== -1 ? "&" : "?"; if (uri.match(re)) { return uri.replace(re, '$1' + key + "=" + value + '$2'); } else { return uri + separator + key + "=" + value; } } function rate() { var url = '/Company/SaveRating'; url = addOrUpdateQueryStringParameter(url, 'CompanyId', 1); url = addOrUpdateQueryStringParameter(url, 'param1', $('input[name="srating"]:checked').val()); url = addOrUpdateQueryStringParameter(url, 'param2', $('input[name="pgrating"]:checked').val()); $.ajax({ url: url, type: 'GET', success: function (html) { //todo }, error: function (error) { // handle } }); } </script> Update: With your update cshtml file, it worked well (i have just tested) if you set input type hidden instead of style="display:none" <input type="hidden" name="CompanyID" value="@Model.ID"/>
doc_23528116
Here's my code: final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; final GoogleSignIn _googlSignIn = new GoogleSignIn(); Future<FirebaseUser> _signIn(BuildContext context) async { Scaffold.of(context).showSnackBar(new SnackBar( content: new Text('Sign in'), )); final GoogleSignInAccount googleUser = await _googlSignIn.signIn(); final GoogleSignInAuthentication googleAuth =await googleUser.authentication; final AuthCredential credential = GoogleAuthProvider.getCredential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); FirebaseUser userDetails = (await _firebaseAuth.signInWithCredential(credential)).user; ProviderDetails providerInfo = new ProviderDetails(userDetails.providerId); List<ProviderDetails> providerData = new List<ProviderDetails>(); providerData.add(providerInfo); UserDetails details = new UserDetails( userDetails.providerId, userDetails.displayName, userDetails.photoUrl, userDetails.email, providerData, ); Navigator.push( context, new MaterialPageRoute( builder: (context) => new Profile(detailsUser: details), ), ); return userDetails; this is my second screens code where im trying to retrieve the user's details in this screen final UserDetails detailsUser; Profile({Key key, @required this.detailsUser}) : super(key: key); @override Widget build(BuildContext context) { final GoogleSignIn _gSignIn = GoogleSignIn(); return Scaffold( appBar: AppBar( title: Text(detailsUser.userName), automaticallyImplyLeading: false, actions: <Widget>[ IconButton( icon: Icon( FontAwesomeIcons.signOutAlt, size: 20.0, color: Colors.white, ), onPressed: (){ _gSignIn.signOut(); print('Signed out'); Navigator.pop(context); }, ), ], ), body:Center(child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CircleAvatar( backgroundImage:NetworkImage(detailsUser.photoUrl), radius: 50.0, ), SizedBox(height:10.0), Text( "Name : " + detailsUser.userName, style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black,fontSize: 20.0), ), SizedBox(height:10.0), Text( "Email : " + detailsUser.userEmail, style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black,fontSize: 20.0), ), SizedBox(height:10.0), Text( "Provider : " + detailsUser.providerDetails, style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black,fontSize: 20.0), ), The error which i was getting whenever i click on the google account is given below: W/Gralloc3( 4066): mapper 3.x is not supported D/FlutterView( 4066): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@46e60ce D/FlutterView( 4066): Already attached to this engine. Doing nothing. W/ActivityThread( 4066): handleWindowVisibility: no activity for token android.os.BinderProxy@7725948 I/flutter ( 4066): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null) W/ActivityThread( 4066): handleWindowVisibility: no activity for token android.os.BinderProxy@70d26c1 I/flutter ( 4066): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null) W/ActivityThread( 4066): handleWindowVisibility: no activity for token android.os.BinderProxy@4acc1c I/flutter ( 4066): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null) D/FlutterView( 4066): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@46e60ce A: ApiException: 10 Certain Google Play services (such as Google Sign-in and App Invites) require you to provide the SHA-1 of your signing certificate so we can create an OAuth2 client and API key for your app How to add SHA-1 into Firebase project: In Android Studio: Double click signingReport: -> get SHA1 Check result in Run window Open project setting Firebase:
doc_23528117
I have used this private void ButtonFilterClick(object sender, EventArgs e) { PixelFormat pxf = PixelFormat.Format24bppRgb; Bitmap bitmap = ((Bitmap)(_smartLabForm.pictureBox1.Image)); Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, pxf); IntPtr ptr = bmpData.Scan0; int numBytes = bmpData.Stride * bitmap.Height; byte[] rgbValues = new byte[numBytes]; Marshal.Copy(ptr, rgbValues, 0, numBytes); for (int counter = 0; counter < rgbValues.Length; counter += 3) { if (rgbValues[counter] < 15 && rgbValues[counter + 1] < 15 && rgbValues[counter + 2] < 15) { rgbValues[counter] = 255; rgbValues[counter + 1] = 255; rgbValues[counter + 2] = 255; } } Marshal.Copy(rgbValues, 0, ptr, numBytes); bitmap.UnlockBits(bmpData); _smartLabForm.Refresh(); } and what I obtain is this: How can I remove the "noise" remaining without damage the green picture and without affecting the performance? Thank you? A: This is actually a quite complex topic in computer vision (image segmentation). Covering the advanced techniques would be way too broad. But here is quick and simple idea that may get the job done: Increase the threshold enough that all background pixels fall below it. When checking if a pixel should be removed, also compare all pixels in a certain neighborhood (e.g. circular radius) with the threshold. Only remove it if they are all below the threshold. That way you remove pixels less agressively when you are near the feature region.
doc_23528118
As in Part 1, I like to sum the values in the second column based on the values in the first column as well, but this time like this: Table Her is my data frame: df <-data.frame('V1' = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'A', 'A', 'B', 'B', 'B', 'C', 'A', 'A', 'A', 'B', 'C', 'A', 'B', 'B', 'B', 'C'),'V2' = c(1, 3, 4, 2, 1, 1, 2, 3, NA, 2, 4, 2, 4, 5, NA, 3, 3, 2, 2, NA, 5, 5, 2, 3, NA)) Observe that the value of C is: C = (Sum(A) -sum(B)). Can you please help me with this too? Thank you very much in advance! A: Here is an option, not very direct, but I think it does what you want! library(tidyverse) # Creating here a unique index "ind" df <- df %>% mutate(ind = with(rle(V1), rep(ave(values, values, FUN = seq_along), lengths)), ind = paste(V1,ind,sep = "_")) # Sum up by group df <- df %>% group_by(ind, V1) %>% summarise(sum = sum(V2)) # Substract A - B # First, get the index back df <- df %>% separate(ind, c(NA, "ind"), sep = "_") # Then, manipulate a bit the dataframe to get B - A df <- df %>% pivot_wider(id_cols = ind, names_from = V1, values_from = sum)%>% mutate(C = A - B) # go back to initial structure df <- df %>% pivot_longer(cols = A:C, names_to = "V1", values_to = "sum") # you can get rid of the index column df %>% select(!ind) Best, Rosalie A: This will work: df <-data.frame('V1' = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'A', 'A', 'B', 'B', 'B', 'C', 'A', 'A', 'A', 'B', 'C', 'A', 'B', 'B', 'B', 'C'),'V2' = c(1, 3, 4, 2, 1, 1, 2, 3, NA, 2, 4, 2, 4, 5, NA, 3, 3, 2, 2, NA, 5, 5, 2, 3, NA)) df$V3<-NA helper=data.frame('H',0,0) names(helper)<-c('V1','V2','V3') df<-rbind(df, helper) c=0 for (i in (1:(length(df$V1)-1))) { if (df$V1[i]==df$V1[i+1]) { c = c+df$V2[i] } else { df$V3[i]<- c+df$V2[i] c=0 next } } df<- head(df,-1) a<-na.omit(df$V3[df$V1=="A"]) b<-na.omit(df$V3[df$V1=="B"]) c=a-b df$V3[df$V1=="C"]<-c Note: This solution will not match the pictured table due to the fact that the provided data frame is not an exact match to the pictured table. Also you will notice that this solution is the same as Part 1 except with the addition of the bottom 4 lines.
doc_23528119
I've used the Standard Assets package from unity on the asset store, but I want to make them myself (the sprites and animations) Are there any good tools for this and if it's something like blender are there any tutorials? It needs to be free. Thanks in advance! PS. It must be 2d sprites. A: It depends on what you want. If you want pixel art, Piskel is a fairly robust free sprite creator. It automatically puts your sprites on an alpha program, and allows you to automatically create sprite sheets, and preview animations. However, if you want something more detailed, some sort of other more advanced program would be advised, such as Paint or Photoshop.
doc_23528120
z = "1.24" x = "3.43" z.to_f x.to_f @check = z/x A: The to_f call does not change the variable itself (but returns a float, roughly speaking). You have at least following options: 1. Assign return value of to_f to a new variable x = "3.43" z = "1.24" x_float = x.to_f z_float = z.to_f @check = z_float/x_float 2. Call when the calculation is done (Like in @Sean s answer) 3. Call on first assignment x = "3.43".to_f z = "1.24".to_f @check = z/x A: Calling to_f does not reassign the value of the variable: z = "1.24" x = "3.43" z.to_f # ^^ z is still a string x.to_f # ^^ x is still a string @check = z/x # Perhaps z.to_f / x.to_f A: You can make it still more simple: z = "1.24" x = "3.43" @check = Float(z)/Float(x)
doc_23528121
const aKeys = []; for (let key of aKeys) { ... } Is transpiled to: var aKeys = []; for (var _i = 0, aKeys_1 = aKeys; _i < aKeys_1.length; _i++) { var key = aKeys_1[_i]; } What's the point of aKeys_1 here? You can also view this live in Typescript playground here. A: Because you could reassign aKeys in the loop body, and it should not affect the iteration. Of course it's not necessary when you don't, but the transpiler doesn't know for sure. And in general, as @Thomas observed in the comments, the expression must be evaluated only once - while it's trivial to see that it won't make a difference for a reference to a const variable, in general it's not that easy.
doc_23528122
I have it working with this Order model: clientId Client @relation(fields: [clientId], references: [id]) clientId Int But wanted to also include the client name. Something like this doesn't work: client Client @relation(fields: [clientName, clientId], references: [name, id]) clientName String clientId Int This gives me the error Error validating: The argument `references` must refer to a unique criteria in the related model `Client`. But it is referencing the following fields that are not a unique criteria: name, id Is this something that is possible within the Prisma schema? I can do it with my controller in NestJS, but ideally I would want to be done in the Prisma layer. A: I solved this by adding a @@unique([name, id]) constraint on the Client model. However, I'm not sure if this is the correct or best way to do this.
doc_23528123
123 1.23 1.23e4 1.23d4 123_txt 1.23_txt 1.23e4_txt The JavaScript code read these data from a file and should math using the rexexp pattern What is the simple regexp pattern to match above data? A: Your regex [+-]?[0-9][0-9_]*\.[0-9de+-]* does not match 123 and 123_txt because these values are not containing a dot \. which is not optional in your regex. You could make the dot optional \.? but then you would have to account for the underscore _ in the last two examples and the missing txt which is not part of the regex. What you could do is update your regex to match one or more digits from the beginning of the string ^[0-9]+ and make the 2 patterns like .23e4 and _txt after the digits optional. Your examples do not contain a leading + or - so you might leave out [+-]? from the beginning. (You can always add it) For your example values you could try: ^[0-9]+(?:\.[0-9]+[de]?[0-9+])?(?:_txt)?$ Explanation * *^ Assert position at the start of the line *[0-9]+ Match one or more digits *(?: Non capturing group * *\.[0-9]+[de]?[0-9+] Match a dot, one or more digits, optional d or e and then one or more digits. *)? Close non capturing group and make it optional *(?:_txt)? Optional non capturing group which matches _txt *$ Assert position at the end of the line
doc_23528124
I used keith ito's implementation of tacotron and I woud like to use TFLite. But I don't know how to change the code. TFLite is about only the Inference? Apparentley, I can't use Session, Variable and other things, righ?
doc_23528125
Using arrays, I have created a system for adding new items to the menu and having them printed in a text file. This all works fine. The issue arises when I need to edit an item, for example, if I have added 3 dishes and use the edit option, only the first line of the text file is edited and the item number returns to 0 when the minimum should always be 1. How can I make this work so if I edit item 3, the edit will be displayed in the text file on line 3 instead of overwriting line 1? I am not sure where the issue lies so I am attaching all the project files as it is not too long. Thank you in advance The .h file: #ifndef RESTAURANTMENU_ITEMS_H #define RESTAURANTMENU_ITEMS_H #define MAX_ITEMS 20 #include <iostream> #include <string> #include <limits> #include <fstream> class Item{ private: int itemNumber; std::string itemCategory; std::string itemDescription; double itemPrice; public: Item(); //setter function void setItemDetails(); void editItemDetails(); //getter function void printItemDetails(); //save to file void save(std::ofstream &outfile); }; #endif //RESTAURANTMENU_ITEMS_H The implementation file: #include "item.h" //constructor Item::Item(){ itemNumber = 0; itemCategory = "Item not categorised."; itemDescription = "No description written."; itemPrice = 0.0; } //setter functions void Item::setItemDetails() { int choice; static int counter = 1; itemNumber = counter++; std::string copyCategory; std::cout << "What category is this item?" << std::endl; std::cout << "1. Meat Dish\n2. Fish Dish\n" "3. Vegetarian Dish\n4. Drink\n"; std::cin >> choice; switch (choice) { case 1: itemCategory = "Meat"; break; case 2: itemCategory = "Fish"; break; case 3: itemCategory = "Vegetarian"; break; case 4: itemCategory = "Drink"; break; default: std::cout << "Error. Please enter a number between 1-4: " << std::endl; std::cin >> choice; } std::cout << "Please enter a short description: " << std::endl; std::cin.ignore(100, '\n'); std::getline(std::cin, itemDescription); std::cout << "Please set the price: " << std::endl; std::cout << "£"; if (!(std::cin >> itemPrice)) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Error. Please enter a number: "; } } void Item::editItemDetails() { int choice; std::string copyCategory; std::cout << "What category is this item?" << std::endl; std::cout << "1. Meat Dish\n2. Fish Dish\n" "3. Vegetarian Dish\n4. Drink\n"; std::cin >> choice; switch (choice) { case 1: itemCategory = "Meat"; break; case 2: itemCategory = "Fish"; break; case 3: itemCategory = "Vegetarian"; break; case 4: itemCategory = "Drink"; break; default: std::cout << "Error. Please enter a number between 1-4: " << std::endl; std::cin >> choice; } std::cout << "Please enter a short description: " << std::endl; std::cin >> itemDescription; //std::cin.ignore(100, '\n'); //std::getline(std::cin, itemDescription); std::cout << "Please set the price: " << std::endl; std::cout << "£"; //if (!(std::cin >> itemPrice)) { //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //std::cout << "Error. Please enter a number: "; std::cin >> itemPrice; //} } //getter functions void Item::printItemDetails(){ std::cout << "\nItem Number: " << itemNumber << "| Category: " << itemCategory << "| Description: " << itemDescription << "| Price: £" << itemPrice; } //save to file void Item::save(std::ofstream &outfile) { outfile << "\nItem Number: " << itemNumber << "| Category: " << itemCategory << "| Description: " << itemDescription << "| Price: £" << itemPrice; } main.cpp #include <iostream> #include "item.h" int main() { Item newDish[MAX_ITEMS]; bool exit = false; int choice; int count = 0; std::ofstream saveFile; saveFile.open("menu.txt", std::ios::in | std::ios::out); while (!exit) { std::cout << "Menu Creation Terminal\n\n" << std::endl; std::cout << "\tWelcome to Wrapid™ Restaurants\n\n\t\tMenu Creation Terminal\n\n" << std::endl; std::cout << "1. Add a new dish\n2. Edit Current Menu\n3. Quit\n" << std::endl; std::cout << "Please select an option: "; std::cin >> choice; switch (choice) { case 1: { int option = true; int i; //create items std::cout << "Item Creation Menu"; for (i = 0; i < MAX_ITEMS; i++) { count += 1; std::cout << "\n\nItem number: " << i+1 << "\n\n"; newDish[i].setItemDetails(); newDish[i].save(saveFile); std::cout << "Would you like to add another item?" << std::endl; std::cout << "1. Yes\n2. No" << std::endl; std::cin >> option; if (option == 2) { break; } std::cout << "You have added the following items: " << std::endl; newDish[i].printItemDetails(); } } break; case 2: { int editOpt; int i; //edit items std::cout << "Edit Current Menu\n\n" << std::endl; for (i = 0; i < count; i++) { newDish[i].printItemDetails(); } std::cout << "\n\nPlease enter the item number of the item you would like to edit: " << std::endl; std::cin >> editOpt; while(editOpt > 20) { std::cout << "Error. Limited to 20 items.\n" "Please try again: "; std::cin >> editOpt; } i = editOpt-1; newDish[i].editItemDetails(); newDish[i].save(saveFile); } break; case 3: { std::cout << "Thanks for using this terminal. Have a nice day." << std::endl; exit = true; } break; default: { std::cout << "Error. Invalid selection. Please select a valid option: " << std::endl; std::cin >> choice; } } } saveFile.close(); return 0; } A: change this line in main because everytime you are overwriting the file so always open a file in append mode std::ofstream saveFile; saveFile.open("menu.txt", std::ios::in | std::ios::out | std::ios_base::app); Hopefully that will solve your problem
doc_23528126
@Override public void deleteNode(Integer nodeId) { SqlParameterSource in = new MapSqlParameterSource() .addValue("nodeId",nodeId) .addValue("user", "DUMMY"); SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(ebDataSource) .withSchemaName("SCHEMA") .withCatalogName("PK_GRAPH_DML") .withProcedureName("DeleteNode"); simpleJdbcCall.execute(in); } And I have to test this method. But I want to rollback all changes after every execution of this test. @Test @Transactional @Rollback public void deleteEBNode_ok() { Integer nodeId = 5714; ebFlowService.deleteEBNode(nodeId.toString()); EBFlowToolSelect nodeModelFromDatabase = ebFlowService.getNodeById(nodeId); Assert.assertNull(nodeModelFromDatabase.getNodeId()); } I tried to annotate my test by @Transactional and @Rollback, but it didn't help. Is it possible to make my test rollback all changes that were made by stored procedure? A: That depends on the stored procedure. * *If the stored procedure contains a COMMIT statement then you will only be able to rollback any actions taken after this statement. *If the stored procedure is an autonomous transaction then it will be independent of your transaction (and contain its own COMMIT statement) and you cannot roll it back. If the stored procedure contains no COMMIT statement and is not autonomous then you should be able to roll it back.
doc_23528127
Could not connect to the debugger I googled for answers and I found out that there is a problem with the gnome-terminal, that it no longer accepts the --disable-factory argument and something about unchecking the "Run on external console". I unchecked that and when I press to run, it closed it immediately. A: Try executing MonoDevelop as sudo $ sudo monodevelop It takes Xterm as output terminal emulator. EDIT Run Monodevelop as root can be a BIG mistake. Best way is to write an script that unsets GNOME desktop session and run monodevelop, as Oskar says. Try this one (copy and paste it on vim/nano and save as monodevelop.sh) #!/bin/bash unset GNOME_DESKTOP_SESSION_ID monodevelop Put it on your home (for example) and give it execution permissions: chmod +x ./monodevelop.sh When you want to run it, execute ./monodevelop.sh. Or you can add it as GNOME shell application following this guide.
doc_23528128
Is there a way to find out all the table dependencies and objects dependent on it? For sybase, DBArtisan gives a really easy way to find dependecies. Is there any such tool for MySQL? A: SHOW CREATE TABLE mytable; It'll show you (along with some other stuff) the foreign key relationships for the table.
doc_23528129
# database code with sqlite3.connect("password_vault.db") as db: cursor = db.cursor() # creates a table for masterpassword if one doesn't already exist cursor.execute(""" CREATE TABLE IF NOT EXISTS masterpassword( id INTEGER PRIMARY KEY, password TEXT NOT NULL, email TEXT NOT NULL); """) I would like to store the entry from this TKinter python code within email, how would I do this? # user input of email txt3 = Entry(window, width=20) txt3.pack() txt3.focus() A: You will have to create 3 entries each for each column in your database. Lets assume those are txt1, txt2 and txt3. Here is how you will insert it: def push(): with sqlite3.connect("password_vault.db") as db: cursor = db.cursor() sql_command = 'INSERT INTO masterpassword VALUES (?,?,?)' # Query values = txt1.get(),txt2.get(),txt3.get() # tuple of values cursor.execute(sql_command,values) # Execute the query substituting the values Here, ? is a placeholder and you will later substitute the values instead of that in the execute method. Take a stroll down here There are alot of things to note here: * *Id column requires to have unique value, so its not best practice to actually ask the user for id or even you creating one, instead you can use AUTOINCREMENT, like id INTEGER PRIMARY KEY AUTOINCREMENT,.... Take proper read here. *You shouldn't just insert the password into a database, you should first hash it and then insert it, or else a simple database query by anyone can get you all the passwords easily. Here is a similar project I worked on if your looking for ideas(it is not perfected yet). A: You need to create a submit button that gets the value from the Entry fields and insert it into the database from tkinter import * import sqlite3 import random window = Tk() width = window.winfo_screenwidth() height = window.winfo_screenheight() window.geometry(f"{width}x{height}") email = StringVar() password = StringVar() def submit(): con = sqlite3.connect('password_vault.db') cur = con.cursor() cur.execute(f"insert into masterpassword values ({random.randint(1, 101)},'{password.get()}','{email.get()}')") con.commit() con.close() # database code with sqlite3.connect("password_vault.db") as db: cursor = db.cursor() # creates a table for masterpassword if one doesn't already exist cursor.execute(""" CREATE TABLE IF NOT EXISTS masterpassword( id INTEGER PRIMARY KEY, password TEXT NOT NULL, email TEXT NOT NULL); """) # user input of email txt3 = Entry(window, width=20,textvariable=email) txt3.pack() txt3.focus() Password_field = Entry(window,textvariable=password) Password_field.pack() submit_button = Button(window,text='Submit',command = submit) submit_button.pack() window.mainloop()
doc_23528130
How can I show text in a JTextArea from another class? Thank You! private void botonReservarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String nombre = ""; String telefono = ""; nombre = JOptionPane.showInputDialog("Nombre de la persona de contacto: "); telefono = JOptionPane.showInputDialog("Número de teléfono: "); setNombreApellidos(nombre); setTelefono(telefono); setTipoEvento(comboEvento.getSelectedItem().toString()); setFechaEvento(spinnerFecha.getValue().toString()); setNumPersonas(Integer.valueOf(spinnerPersonas.getValue().toString())); setTipoCocina(comboCocina.getSelectedItem().toString()); setNumJornadas(Integer.valueOf(spinnerJornadas.getValue().toString())); setNumHabitaciones(Integer.valueOf(spinnerHabitaciones.getValue().toString())); ResumenReserva resumen = new ResumenReserva(new javax.swing.JFrame(), true); JTextArea textAreaResumen = new JTextArea("Prueba"); textAreaResumen.setEditable(false); resumen.setTextAreaResumen(textAreaResumen); add(textAreaResumen); resumen.setVisible(true);}
doc_23528131
If Dir(Filenamepath) <> "" Then 'don't overwrite the packing list if it exists Else PackList.ExportAsFixedFormat Type:=xlTypePDF, _ FileName:=Filenamepath, _ OpenAfterPublish:=False 'True End If This loops through a number of times, e.g. 10, in order to create twn packing lists. Whenever the ExportAsFixedFormat part of the loop runs, all the code afterwards runs slowly. I have run an experiment where I delete just one of the many existing PDF files (in Filenamepath) (so that the code will enter the "export as PDF" loop just once). The code runs fast before the one PDF is created, and then slowly afterwards. If I don't delete any PDF files, so that when the code is run, the loop "export as PDF" is never entered, the code never slows down. I have tried: Application.ScreenUpdating = False Application.DisplayAlerts = False Application.EnableEvents = False Application.Calculation = xlCalculationManual At the beginning of my code, but the result of my experiment stays the same, so this does not seem to be the problem. Why does ExportAsFixedFormat cause the code to slow down so drastically, and what can be done about it? 28 Dec 2017 update: still no resolution, however it seems from searching other questions related to ExportAsFixedFormat causing Excel to crash (such as 35857728) that this is a common problem. Recently, Excel crashes (but only sometimes) while attempting to generate a PDF, where previously it would just run slowly. I have tried changing my default printer, uninstalling other VBA macros, uninstalling Windows updates (all suggestions by other uses to address ExportAsFixedFormat issues). Nothing seems to help. The ONLY resolution that seems to work is if I change the file type of the export from PDF to XPS (the other ExportAsFixedFormat option). For my situation, I can live with the XPS filetype, and I can always convert the files to PDF's later. I have not verified that this speeds up the macro (my original problem) but at least it seems to help with the crashing).
doc_23528132
Table structure is as folllows: PropertyOwner * *Number (primary key) *PropertyId (primary key) *OwnerId Property * *PropertyId (primary key) *LoanId (primary key) Now, if I have a LoanId, how can I find all properties of property ownerId's who have taken the given LoanId? I am having the below now but it looks awkward: Select po.OwnerId, po.PropertyId from Property join PropertyOwner po on po.PropertyId= Property.PropertyId join PropertyOwner po2 on po2.OwnerId = po.OwnerId join Property pp on po2.PropertyId= pp.PropertyId and pp.LoanId = @_givenLoanId Is there a better way? A: Exists comes to mind as being a more direct interpretation of what you are doing: Select po.OwnerId, po.PropertyId from PropertyOwner po where exists (select 1 from Property p2 join PropertyOwner po2 on p2.PropertyId = po2.PropertyId where po2.OwnerId = po.OwnerId and p2.LoanId = @_givenLoanId ); A: This is what you're looking for: SELECT OwnerId, PropertyId FROM PropertyOwner WHERE OwnerId IN ( SELECT DISTINCT o.OwnerId FROM Property p JOIN PropertyOwner o ON o.PropertyId = p.PropertyId WHERE LoanId = @_givenLoanId );
doc_23528133
If we want to work with istio through rest call, what options we have? I'm new to istio.So help me, please! A: You can use Kubernetes API groups for Istio CRD For example the apiVersion: networking.istio.io/v1alpha3 can be accessed at /apis/networking.istio.io/v1alpha3. GET /apis/networking.istio.io/v1alpha3/gateways will get gateways for all namespaces. The full list of istio APIs can be found on istio github page. To directly access the kubernetes REST API follow these instructions. Hope this helps.
doc_23528134
I figured I could just apply -moz-transform and friends and be done with it, but then I realized that my browser does not seem to "push" elements out of the way like I expect, resulting in this: My question is: is there a way for me to rotate the image, while having my browser move the elements around it in respect to its new dimensions? Here's a JSFiddle: http://jsfiddle.net/8pFUB/ . Click the image to rotate it and illustrate the problem. A: In pure CSS, no. But you can use jQuery to set some new margins: var e = $(el); e.css({ 'margin-bottom': (e.width( ) * Math.abs( Math.sin( degree * Math.PI / 180.0 ) ) + e.height( ) * (Math.abs( Math.cos( degree * Math.PI / 180.0 ) ) - 1)) / 2 }); Fiddle: http://jsfiddle.net/8pFUB/21/ Also to reply to Colonel Panic's answer, here is a version which sets all 4 margins: http://jsfiddle.net/8pFUB/24/. It's a bit less elegant in the rotation, so I'd suggest only setting the margins you actually want to change. Full (adapted) code: function setPaddedRotation( element, degree ) { var e = $(element); var rads = degree * Math.PI / 180.0; var ss = Math.abs( Math.sin( rads ) ); var cc = Math.abs( Math.cos( rads ) ); var padx = (e.height( ) * ss + e.width( ) * (cc - 1)) / 2; var pady = (e.width( ) * ss + e.height( ) * (cc - 1)) / 2; e.css({ '-webkit-transform': 'rotate(' + degree + 'deg)', '-moz-transform': 'rotate(' + degree + 'deg)', '-ms-transform': 'rotate(' + degree + 'deg)', '-o-transform': 'rotate(' + degree + 'deg)', 'transform': 'rotate(' + degree + 'deg)', // remove any of these which you don't want 'margin-top': pady, 'margin-bottom': pady, 'margin-left': padx, 'margin-right': padx }) } A: Play with the margin values function degToRad(deg) { return Math.PI * deg / 180; } var height = img.height, width = img.width, rad = degToRad(deg), sin = Math.abs(Math.sin(rad)), cos = Math.abs(Math.cos(rad)), dh = cos * height + sin * width - height, dw = cos * width + sin * height - width; $(img).css({ 'margin-top': dh / 2 + 'px', 'margin-bottom': dh / 2 + 'px', 'margin-left': dw / 2 + 'px', 'margin-right': dw / 2 + 'px' }); DEMO
doc_23528135
This is my webpage. The first picture is made with usemap, and I made an area for each one of those people. When I click on each one, it loads the description in a different tab, and I don't want that. So, can I load the description and the name of the men there in the bottom table, at the click event on that photo? <img src="http://mythologica.ro/wp-content/uploads/2017/10/zei-egipteni2-1280x640.jpg" style="height:60%; width:80%" alt="zeii" usemap="#mapazei"> <map name="mapazei"> <area shape="rect" coords="50,80,280,605" alt="primu" href="1.html"> <area shape="rect" coords="300,80,500,605" alt="primu" href="2.html"> <area shape="rect" coords="490,80,680,605" alt="primu" href="3.html"> <area shape="rect" coords="680,80,830,605" alt="primu" href="4.html"> <area shape="rect" coords="840,80,1030,605" alt="primu" href="5.html"> <area shape="rect" coords="1050,80,1230,605" alt="primu" href="6.html"> </map> <table border="1"> <tr> <td width="20%">name</td> <td width="80">description</td> </tr> </table> The coords may not work in this snippet because the photo I have saved on my PC has a different resolution. A: Event Delegation Register the <map> to the click event and then arrange if/else conditionals so that <area> is the only tag considered clicked. The information was missing so I added data-name and data-dom to each <area>. Also the <area> href were set to jump to another page. You can't have a click transfer info to a <table> and go to another page, you must decide on one or the other. So the href no longer jump to a page, this is done by doing this: href="#/". Demo Details are commented in demo Note: The <area>s rect are overlapping because of the small scale, so review it in full page. // Reference the <map> var map = document.querySelector('map'); // This is the Event Handler - passing the Event Object function identify(event) { // Clicked element (i.e. <area>) var eTgt = event.target; // Registered element (i.e. <map>) var eCur = event.currentTarget; /* if clicked element is NOT the registered element... */ if (eTgt !== eCur) { // if the clicked element is an <area>... if (eTgt.tagName === "AREA") { // Get its data-name... var name = eTgt.dataset.name; //...and data-dom var domain = eTgt.dataset.dom; // Reference the <table> var table = document.querySelector('table'); // Locate the appropriate <td> var nameCell = table.rows[1].cells[0]; var domCell = table.rows[1].cells[1]; // Change the <td> content to the associated values nameCell.textContent = name; domCell.textContent = domain; } } } /* Register the <map> to the click event... when clicked event handler function identify() is called */ map.onclick = identify; <img src="http://mythologica.ro/wp-content/uploads/2017/10/zei-egipteni2-1280x640.jpg" style="height:65.25%; width:100%" alt="zeii" usemap="#mapazei"> <map name="mapazei"> <area href="#/" shape="rect" coords="50,80,280,605" alt="primu" data-name='Bast' data-dom='Goddess of Cats'> <area href="#/" shape="rect" coords="300,80,500,605" alt="primu" data-name='Isis' data-dom='Goddess of Fertility'> <area href="#/" shape="rect" coords="490,80,680,605" alt="primu" data-name='Ra' data-dom='God of the Sun'> <area href="#/" shape="rect" coords="680,80,830,605" alt="primu" data-name='Horus' data-dom='God of the Sky'> <area href="#/" shape="rect" coords="840,80,1030,605" alt="primu" data-name='Hathor?' data-dom='?'> <area href="#/" shape="rect" coords="1050,80,1230,605" alt="primu" data-name='Anubis or Set?' data-dom='God of the Dead or Evil'> </map> <table border="1" style='transform:translateY(-50px)'> <tr> <th width="20%">Name</th> <th width="80">Description</th> </tr> <tr> <td></td> <td></td> </tr> </table>
doc_23528136
main() { int i=1,n,s=1; printf("enter the value of n"); scanf("%d",&n); while(i<=n) { s=s*i; i++; if (i==n+1) { break; } } printf("factorial of n=",s); } it is giving the result as shown in the picture below. A: Your problem is in this line: printf("factorial of n=",s); This outputs factorial of n=, but it does not simply concatenate the value of s, and there is no placeholder for s, so you actually have too many parameters. You need a placeholder for the int output: printf("factorial of n=%d",s); Without it, your program exits with an error (status 15, when 0 would be normal). Also, (as Vlad pointed out in his answer) the if (i==n+1) { ... } block is redundant, as your while loop will already exit when i > n. A: Write printf("factorial of n=%d\n",s); ^^ And this code snippet if (i==n+1) { break; } is redundant and may be removed. You could write the loop simpler. For example while ( n > 1 ) s *= n--; without a need to use one more variable i.
doc_23528137
I get the provider in the onCreate() of my Activity (it extends LocationListener) locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); location = locationManager.getLastKnownLocation(provider); It works fine, my problem is that when onLocationChange() is called, I should act differently if the provider which called it is GPS or NETWORK. Is there a way to know which? To be more clear: When onLocationChanged(Location location) is called, is there a chance to know which provider made the call? I have tried using an if on the provider string but it seems it doesn't work. A: Do you need to know the Location provider (GPS, WIFI or Network) or its accuracy? getAccuracy() Get the estimated accuracy of this location, in meters. We define accuracy as the radius of 68% confidence. In other words, if you draw a circle centered at this location's latitude and longitude, and with a radius equal to the accuracy, then there is a 68% probability that the true location is inside the circle. If you really care about the provider, you could probably use isProviderEnabled(). A: check that accuracy is <= 30m: boolean isGPS = (location.getAccuracy() <= 30); A: I think you wanna know which provider provided last Location update ..... u have created Provider as a string just use that String in code like if (provider.matches("GPS")){} A: I see several answers, and although they may be useful, none addresses the actual question asked: When onLocationChanged(Location location) is called, is there a chance to know which provider made the call? To know whether it was GPS_PROVIDER or NETWORK_PROVIDER the one triggering the onLocationChanged you can use the getProvider() method (or the provider value in Kotlin): @Override public void onLocationChanged(Location location){ //obtain a string, 'gps' or 'network', from the location System.out.println(location.getProvider()); } Or in Kotlin: override fun onLocationChanged(location: Location?) { println(location!!.provider) } Doc reference here
doc_23528138
I found some CLI tools but those are running only on windows. those are * *AzCopy *cloudcopy So can anybody suggest one best azure CLI tool, which can run on linux machine and able to perform upload and download operations?? It would be great if that supports partial read and partial write. A: There's support for upload and download : azure storage blob upload [options] [file] [container] [blob] azure storage blob download [options] [container] [blob] [destination] If not seeing them try to update your cli tools first: npm install azure-cli -g (Node.js must be installed in your system) Hope this helps A: A little late to this question, but hopefully this will help anyone looking for an answer. The Azure Batch and HPC team has released a code sample with some AzCopy-like functionality on Python called blobxfer. [full disclosure: I'm a contributor for this code] A: if the above doesn help, you might also be able to install the latest version through elevated privileges like this sudo npm instal azure-cli -g A: Azure CLI 2.0 which is python based release supporting ARM based deployment can be used to download the blob storage contents one by one. Here is the step by step guide for the same - http://sanganakauthority.blogspot.in/2017/03/how-to-download-azure-blob-storage.html However you can't download the all the blob from a container in one go. Cli does not support it as of today.
doc_23528139
select recordings.ident,users.first_name,users.last_name,recordings.agent_number,recordings.device_id from recordings join agent_phones on recordings.agent_number=agent_phones.phone_id join users on agent_phones.agent_id=users.uid is there a way to do some sort of "if" in the query? so that "if" the agent_number doesn't exist in agent_phones - i can just populate the first_name and last_name with the static "unknown". A: You are looking for LEFT JOIN clause, which also includes rows that cannot be joined (don't have matching row in the second/right table). The values from the second/right table are then NULL. SELECT recordings.ident, users.first_name, users.last_name, recordings.agent_number, recordings.device_id FROM recordings LEFT JOIN agent_phones ON recordings.agent_number = agent_phones.phone_id LEFT JOIN users ON agent_phones.agent_id = users.uid This can further be extended to return a specified string instead of NULL values using the COALESCE function: SELECT recordings.ident, COALESCE(users.first_name, 'unknown'), COALESCE(users.last_name, 'unknown'), recordings.agent_number, recordings.device_id FROM ...
doc_23528140
In the xlsx download section, I encountered this error when putting the "stream" variable into IWorkbook. "System.ArgumentException: 'Update mode requires a stream with read, write, and seek capabilities.'" ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.UseFastRecordParsing = true; var stream = await graphClient.Me.Drive.Items["F90FCCBAC810EFDB!41667"].Content .Request() .GetAsync(); IWorkbook workbook = await application.Workbooks.OpenAsync(stream); And in the upload section, I tried to load a file from the file picker to IWorkbook, then save as Stream , finally successfully uploaded but it was empty. using (ExcelEngine excelEngine = new ExcelEngine()) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.SuggestedStartLocation = PickerLocationId.Desktop; openPicker.FileTypeFilter.Add(".xlsx"); openPicker.FileTypeFilter.Add(".xls"); StorageFile inputStorageFile = await openPicker.PickSingleFileAsync(); Stream fileStream = (await inputStorageFile.OpenReadAsync()).AsStreamForRead(); IWorkbook workbook = await excelEngine.Excel.Workbooks.OpenAsync(fileStream); workbook.Version = ExcelVersion.Excel2016; MemoryStream outputStream = new MemoryStream(); await workbook.SaveAsAsync(outputStream); await graphClient.Me.Drive.Root.ItemWithPath(inputStorageFile.Name).Content .Request() .PutAsync<DriveItem>(outputStream); } What I need is to edit the xlsx file on Ondrive using Syncfusion.XlsIO.UWP from the stream. Can anyone help me? Thanks a lot. A: Query-1: "System.ArgumentException: 'Update mode requires a stream with read, write, and seek capabilities.'" for this code below. Answer: We request you to copy the stream to MemoryStream and set stream.Postion = 0; before loading the file into IWorkbook, to resolve the issue. ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.UseFastRecordParsing = true; var stream = await graphClient.Me.Drive.Root.ItemWithPath("Sample.xlsx").Content.Request().GetAsync(); stream.Position = 0; MemoryStream file = new MemoryStream(); stream.CopyTo(file); file.Position = 0; IWorkbook workbook = await application.Workbooks.OpenAsync(file); Query-2: I tried to upload a file successfully but it was empty. Answer: We request you to set the stream position as 0 here also, before uploading the file to resolve the issue. outputStream.Position = 0; await graphClient.Me.Drive.Root.ItemWithPath("Sample.xlsx").Content.Request().PutAsync<DriveItem>(outputStream); The sample we have tried at our end can be downloaded from the following link. Sample Link: https://www.syncfusion.com/downloads/support/forum/148443/ze/03-add-msgraph1181232979.zip Note: Please add the ApplicationID and use valid file name then execute the sample.
doc_23528141
HTML: <div class="containdiv"> <label>Phone <img src="circle.gif" /></label> <input type="text" name="phone" maxlength="4" size="4"> <input type="text" name="phone" maxlength="4" size="4"> <input type="text" name="phone" maxlength="4" size="4"> </div> <div class="containdiv"> <label>Preferred Contact <img src="circle.gif" /></label> <div class="radio"> <input type="radio" name="email" value="email"> <label for="email">Email</label> <input type="radio" name="phone" value="phone"> <label for="phone">Phone</label> </div> </div> CSS: label { display: inline-block; float: left; clear: left; width: 250px; text-align: right; } input, select, span.radio, textarea { display: inline-block; margin: 3px; float: left; } Any insight would be greatly appreciated. A: Here is a pure HTML and CSS example. The only external resource is a google font I added to improve the text. It is a little complex but play around with it. html, body { padding: 0; margin: 0; height: 100%; width: 100%; font-family: Open Sans; } *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .text-center { width: 100%; text-align: center; } hr { width: 80%; margin: 5px 10%; } form { width: 60%; margin: 0 20%; display: inline-block; } form .form-group { width: 100%; margin: 10px 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; } form .form-group label, form .form-group .form-control { width: 50%; padding: 3px 10px; display: inline-block; margin: 0; } form .form-group > label { font-weight: bold; text-align: right; } form .form-group div.form-control { padding: 0; } form .form-group .checkbox, form .form-group .btn { margin-left: 50%; } form .form-group .form-control label { width: 100%; margin: 0; padding: 0; } form .form-group .form-control label.radio-inline { width: auto; display: inline-block; } <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- title --> <h1 class="text-center">Form</h1> <hr> <form> <!-- email --> <div class="form-group"> <label>Email</label> <input class="form-control" type="text"> </div> <!-- who are you --> <div class="form-group"> <label>Who you are</label> <textarea class="form-control" rows="4"></textarea> </div> <!-- favorite number --> <div class="form-group"> <label>Favorite number</label> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <!-- how many pizzas --> <div class="form-group"> <label>How many pizzas</label> <div class="form-control"> <label class="radio-inline"> <input type="radio" name="pizzas" value="male">1</label> <label class="radio-inline"> <input type="radio" name="pizzas" value="female">2</label> <label class="radio-inline"> <input type="radio" name="pizzas" value="female">3</label> </div> </div> <!-- where did you hear about us --> <div class="form-group"> <label>Where did you hear about us</label> <div class="form-control"> <label> <input type="radio" name="referral" value="male">The internet</label> <label> <input type="radio" name="referral" value="female">From a friend</label> <label> <input type="radio" name="referral" value="female">Other</label> </div> </div> <!-- send me updates --> <div class="form-group"> <div class="checkbox"> <input type="checkbox">Send me updates</div> </div> <!-- submit --> <div class="form-group"> <button type="submit" class="btn">Submit</button> </div> </form> A: So your markup is not valid and is impossible to follow so lets start over and help you out. You want your elements in a form in a tabular arrangement, so lets use a table. You have 3 inputs for 1 phone number, why not just use 1? This is a form so we need a form tag: <form> </form> In the form lets add a table with 2 lines. <form> <table> <tr></tr> <tr></tr> </table> </form> Now lets put our fields in the table. <form> <table> <tr> <td>Phone</td> <td colspan="2"><input type="text"></td> </tr> <tr> <td>Preferred Contact</td> <td>Phone <input type="radio" name="preferred"></td> <td>Email <input type="radio" name="preferred"></td> </tr> </table> </form> codepen I highly suggest you read: W3Schools Forms, W3Schools Tables. A: @christian i get ur point i think this one would help Create the form in html and style it with css in the following way... Use labels to write the names next to the text boxes Like: Username Now style it and try tu arrange it in css by targeting the label and the input in the following way: label { margin : 5px 15px; And whatever you want to style } Input { margin:5px 0px 10px 150px; Hint....the 150px is the one that will push all the textboxes to start on 150px of the page soh its up to you to place it any where you want on the page by changing the left margin to whatever you want which is currently the 150px }
doc_23528142
To simplify slightly, there are three roughly equal frames side by side. All three of them scroll vertically. The best approach I can think of now is to float everything left, with appropriate width and margin-left, and use overflow-y (and, where horizontal scrolling makes sense, overflow-x) settings for the DIVs in question. Is "float everything left and set width and margin-left" optimal, and if not, what would be a more idiomatic way to replace the frames? Thanks, A: Replacing frames is tricky if the different frames use different style sheets, JS and what not. If that is not an issue in your case and you can just copy the relavent part of the HTML from the three frames to one new HTML page with three vertical DIV's of some sort then I would suggest that you use something the overflow technique that you described. Position them absolutely with a width of 33% and a height of 100%. You could use floats, but that might result in all kinds of annoying issues. In yoru case I'd go for position: absolute <div class="c c1"> loooooong content </div> <div class="c c2"> loooooong content </div> <div class="c c3"> loooooong content </div> .c { position: absolute; width: 33%; height: 100%; top: 0; overflow-y: scroll; } .c1 { left: 0; } .c2 { left: 33%; } .c3 { left: 66%; width: 34%; } here's a jsfiddle: http://jsfiddle.net/9CAYb/
doc_23528143
The hashing function generates a different hash every time for the same piece of data, but it can determine if a particular hash was generated with the piece of data or not. Eg: hash_func(xyz): abc123 hash_func(xyz): jhg342 // different hash, even if the data was same. decode_hash(jhg324) == xyz This gives true, because the hash function determined that jhg324 is indeed the hash of xyz The Question For an Open Source website, I want to store the email in hashed form (because all the users will be public), but the site needs to know if an email was used to register for another account so that it can ensure one account per email. However, all the emails are from one organization only. This means, they all look exactly like uid@org_name.com. This means anyone can run through all the UIDs and find out which hash belongs to which email, and thus, which person. Therefore, is there a way to hash the email such that the hash knows which email it belongs to, but hashing the same email does not generate the same hash. P.S. Please note that I cannot use Salting as the site will be Open Source and the salt will be publicly available. A: This doesn't make sense - you're conflating hashing and encryption in a very strange way. What you're describing wouldn't really be a cryptographically secure hash function. By definition, cryptographically secure hash functions are one way. In fact, if you could reverse it, there would be little point to using it at all because it would no longer be secure. This would make it possible to brute-force passwords and would "break" passwords that were used in multiple places. Also, why would you want it to hash to different values each time? That's what you use a salt for. If you want to be able to reverse it later, just use an encryption algorithm like AES. Even better, many databases even offer features for securely storing sensitive information; see, for example, SQL Server's Always Encrypted feature.
doc_23528144
Consider I have to search for 10 documents out of a total 1000 documents based on a condition (not id). * *Would it be better to query using document _id's (after storing the required id's in another collection beforehand by checking for the condition whenever insertion is done) OR *Would it better to traverse all the documents and get the required documents using the condition The main aim here is to split documents into different categories and display the documents belonging to a particular category. So storing id's of documents belonging to each category or search for documents in that category by traversing through all the documents? I have heard that mongodb uses hashed indexing (so feel option 1 would be faster), but I couldnt find anything regarding that. So a small description regarding document storage and queries would also be good. A: The optimum way to query for the cuisine type example would be to store what the restaurant serves in an array of strings or objects, and index that field. For example: { name: "International House" cuisine: [ { name: "Chinese", subtype: "Kowloon"}, { name: "Japanese", subtype: "Yakitori"}, { name: "American", subtype: "TexMex" } ] } Then create an index on { "cuisine.name": 1 }. When you need to find all restaurants that serve Chinese food, the query: db.collection.find({"cuisine.name":"Chinese") will use that index, and only scan the documents that match.
doc_23528145
a a a b b a c a c b I want out put a b c Can we do it using grep or awk A: In awk: $ awk '!u[$0]++' file a b c Nice thing with this solution is the file doesn't need sorting first. A: The simplest approach: sort -u INPUT > OUTPUT
doc_23528146
#standardSQL WITH table AS ( SELECT * FROM `project.dataset.ga_sessions_*` WHERE _TABLE_SUFFIX = '20180118' ) SELECT date, device.deviceCategory, CASE WHEN totals.newVisits IS NOT NULL THEN 1 END newUser, (SELECT COUNT(DISTINCT returningUser) FROM (SELECT CASE WHEN totals.newVisits IS NULL THEN fullVisitorId END returningUser FROM table)) returningUser FROM table This returns the below: As you can see, returningUser is a sub-query which isn't correlated to the outer query columns. Question is, how do you go about getting the returningUser numbers based on the outer query columns? Ideally, I wouldn't want to join on outer query columns, as the requirement is returningUser number against all of these columns. I want to be able to update this query to add more outer query columns as well as more sub-queries where their numbers are based on all outer query columns. UPDATE The data-set is from Google Analytics. The fields are default fields, example data-set available at https://support.google.com/analytics/answer/3416091 Example query that returns expected results - however, this is not as clean and flexible as the above method which I'm trying to get working: #standardSQL WITH table AS ( SELECT * FROM `project.dataset.ga_sessions_*` WHERE _TABLE_SUFFIX = '20180118' ) SELECT date, deviceCategory, COUNT(DISTINCT returningUser) returningUser FROM ( SELECT date, device.deviceCategory, CASE WHEN totals.newVisits IS NOT NULL THEN 1 END newUser, CASE WHEN totals.newVisits IS NULL THEN fullVisitorId END returningUser FROM table) GROUP BY date, deviceCategory Results: A: I can't make sense of what you really want the query to do. My best guess is: SELECT date, deviceCategory, COUNT(newVisits), COUNT(DISTINCT COALESCE(s.newVisits, s.fullVisitorId)) FROM `project.dataset.ga_sessions_*` s WHERE _TABLE_SUFFIX = '20180118' GROUP BY date, deviceCategory ORDER BY date, deviceCategory;
doc_23528147
The idea is, we want to know every message that goes across the ws without having to modify either program to install this logging mechanism. A: Yes it is. After a few days of playing around, you can use node-http-proxy to set up a proxy using node's socket library. This npm package also includes websocket proxying through HTTPS or HTTP.
doc_23528148
I have one project done in Windows Game and another project done in WPF. I need to open the Game1 from DemoScene project by clicking a button in WPF. And this is method in WPF project on button click... private void Playgame_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(i don't know how to put on this); } How can I do this? (I'm a beginner) A: System.Diagnostics.Process.Start(@"c:\game\Game1.exe"); Try the above with your path. More here: http://msdn.microsoft.com/en-us/library/53ezey2s.aspx A: Put your two projects in the same folder, for example, in your WPF application folder, there exists a path "game\Game1.exe". Then you can try the code below in your WPF application button click event. System.Diagnostics.Process.Start(AppDomain.CurrentDomain.StartupPath + "game\\Game1.exe");
doc_23528149
* *project-a *project-b *lib Each of these folders have a tsconfig.json file. I have setup these tsconfig files according to the typescript docs and to my older SO answer here: https://stackoverflow.com/a/54772741/681803 In visual studio code, I simply change my build script in my package.json from tsc to tsc --build. That will build all project listed in my project references list of my tsconfig. However, I can't find out now how to do the same with visual studio 2017 (for another project) When I build visual studio project-a (or project-b), it fails to build as the compiler can't find the references of the lib project (not build yet). When I first manually run tsc in the common folder before building project-a or project-b, it does compile because the output folder now already contains the typescript definition files of the lib project which are needed for project-a and project-b. How to setup visual studio 2017 to work with typescript project references? A: Ah, I just found it when I was looking one more time at the typescript docs... https://www.typescriptlang.org/docs/handbook/project-references.html#msbuild If you have an msbuild project, you can enable build mode by adding <TypeScriptBuildMode>true</TypeScriptBuildMode> to your proj file. This will enable automatic incremental build as well as cleaning. After updating my csproj file of my visual studio project with this flag, all project references are nicely being build.
doc_23528150
getTwitters('name', { id: 'account', count: 3, withFriends: false, enableLinks: false, ignoreReplies: true, newwindow: true, template: '<span style="blabla">%time%</span><p style="blabla">%text%</p>' }); Does anyone have an idea: * *why there are only two calls for fetching tweets? *why one of them is made by insecure HTTP? *how to tell twitterjs to load my tweets via HTTPS only? EDIT: I am using the library from http://code.google.com/p/twitterjs/, and yes, the js file is loaded by HTTPS. A: I fixed the problem by changing the hard-encoded http://s to https://s in the library. I hate how simple things seem to be after having struggled for hours :(
doc_23528151
class CreateTodoList { constructor(list) { this.todoList = list; this.todos = []; } Then let's just assume that I have built addTodo() function which takes text parameter where an user enters her/his todo. addTodo(text) { this.todos.push(text); this.todoList.appendChild(CreateTodoList.addtoList(text)); } Here, addtoList creates DOM element that takes value of the user input. This addTodo function, then pushes the text parameter into the array I made in constructor, while also calling addtoList that makes the DOM element. Now, let's say I click on "add" button where it takes user input value. I will build an event handler that responds to click which will add user input to the todoList. CreateTodoList.eventHandler('click', (e) => { let userText.todos = document.querySelector(#userInput).value; addTodo(userText); }) I am trying to build an eventHandler here, so I can add user input to todoList, and have implemented this several times, but had no luck but receiving reference error. Below is my full code. /** @format */ const add = document.querySelector('#btn_add'); let addInput = document.querySelector('#add'); const form = document.querySelector('#form'); class CreateTodoList { constructor(list) { this.todoList = list; this.todos = []; } addtoList(text) { let checkboxEl = document.createElement('span'); checkboxEl.classList.add('round'); let checkboxEl2 = document.createElement('input'); checkboxEl2.id = 'checkbox'; checkboxEl2.type = 'checkbox'; let checkboxEl3 = document.createElement('label'); checkboxEl3.htmlFor = 'checkbox'; checkboxEl.appendChild(checkboxEl2); checkboxEl.appendChild(checkboxEl3); let todoTextEl = document.createElement('input'); todoTextEl.value = text; todoTextEl.disabled = true; todoTextEl.classList.add('edit_input'); todoTextEl.id = 'edit_input'; todoTextEl.type = 'text'; todoTextEl.name = 'edit_input'; let todoTextEl2 = document.createElement('label'); todoTextEl2.htmlFor = 'edit_input'; let editEl = document.createElement('i'); editEl.classList.add('far'); editEl.classList.add('fa-edit'); let deleteEl = document.createElement('i'); deleteEl.classList.add('far'); deleteEl.classList.add('fa-trash-alt'); let dateEl = document.createElement('small'); dateEl.textContent = timeago.format(new Date()); let liEl = document.createElement('li'); liEl.appendChild(checkboxEl); liEl.appendChild(todoTextEl); liEl.appendChild(todoTextEl2); liEl.appendChild(editEl); liEl.appendChild(deleteEl); liEl.appendChild(dateEl); let list = document.querySelector('ul'); list.appendChild(li); return liEl; } removeFromList(text) { let list = document.querySelector('ul'); let childs = Array.from(list.childNodes); let removable = child.find((i) => i.innerText === text); return item; } //todos 배열(todo 데이터에) text를 추가한다. //todoList 에 liEL(리스트 엘레먼트) 를 append 한다. addTodo(text) { this.todos.push(text); this.todoList.appendChild(CreateTodoList.addtoList(text)); } removeTodo(text) { let removed = this.todos.filter((el) => el !== text); todo.todoList.removeChild(CreateTodoList.removeFromList(text)); this.todos = removed; } get getList() { return this.todos; } } class Handlers {}
doc_23528152
I used the following code void MainWindow::test() { QLoggingCategory::setFilterRules("qt.network.ssl.warning=false"); QNetworkAccessManager* manager = new QNetworkAccessManager(this); QUrl url; url.setHost("xx.xxx.xx.xx"); url.setPort(3389); url.setUserName("administrator"); url.setPassword("xxxx"); manager->get(QNetworkRequest(url)); connect(manager,&QNetworkAccessManager::finished, this, &MainWindow::connFinished); } output: QNetworkReply::NetworkError(ProtocolUnknownError) please guide me A: If you only want to know, if the host is online: I would suggest you use connectToHost from QAbstractSocket Class. The RDP-Protocol is based on TCP/UDP according to Wikipedia and listens on 3389 (what you said in the comments.). If the connection on TCP 3389 is successful, the host is online. If you want to verify if the host is online and the authentication works you have to implement your own RDP-library such as FreeRDP, because Qt does not provide any core modules for RDP.
doc_23528153
The data code is this: CombinedMetricScore<-c("zero", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "60", "M11", "MICKEY", "MEANING", "MICKEYTWO", "MICKEYTHREE", "MIKE", "PASTA", "MCIDandPASS", "MICKDorPASS", "MIKEDOORPASS", "WOMAC20andPASS" ,"Ideal") FalsePositiveRate<-c( 0, 0.05, 0.08, 0.12, 0.2, 0.28, 0.19, 0.5, 0.6, 0.7, 0.8, 0.94, 0.11, 0.28, 0.07, 0.5, 0.08, 0.28, 0.04, 0.3, 0.03, 0.03, 0.22, 1 ) TruePositiveRate<-c(0, 0.31, 0.35, 0.46, 0.69, 0.73, 0.59, 0.92, 0.92, 0.96, 1, 1, 0.46, 0.73, 0.42, 0.88, 0.35, 0.73, 0.46, 0.73, 0.46, 0.46, 0.69, 1) ScoreOrMetric<-c("Metric", "Score", "Score", "Score", "Score", "Score", "Score", "Score", "Score", "Score", "Score", "Score", "Metric", "Metric", "Metric", "Metric", "Metric", "Metric", "Metric", "Metric", "Metric", "Score", "Score", "Metric" ) COMBINEDSCORETABLE<-data.frame(CombinedMetricScore, FalsePositiveRate, TruePositiveRate, ScoreOrMetric) The plot code is this: ggplot(COMBINEDSCORETABLE, aes(x = FalsePositiveRate, y = TruePositiveRate, color = ScoreOrMetric)) + geom_abline(slope = 1, intercept = .5, lwd = 1.5, color = "grey") + geom_point(size =2, alpha = .8) + coord_cartesian(xlim=c(0,1), ylim=c(0, 1)) + coord_fixed() + geom_text_repel(label = ifelse(TruePositiveRate > .44 + FalsePositiveRate, yes = CombinedMetricScore, no = ""), box.padding = 0.5) Question: I want to add labels for the following 2 points "5", "45" but I don't know how to add it to my existing plot code. A: We can use an | ("OR") in your ifelse logic. In general, though, I recommend only passing the data you need to geom_text_repel instead of everything (most of which having ""), so try this: ggplot(COMBINEDSCORETABLE, aes(x = FalsePositiveRate, y = TruePositiveRate, color = ScoreOrMetric)) + geom_abline(slope = 1, intercept = .5, lwd = 1.5, color = "grey") + geom_point(size =2, alpha = .8) + coord_cartesian(xlim=c(0,1), ylim=c(0, 1)) + coord_fixed() + ggrepel::geom_text_repel( aes(label = CombinedMetricScore), box.padding = 0.5, data = ~ subset(., TruePositiveRate > (0.44 + FalsePositiveRate) | CombinedMetricScore %in% c("5", "45")))
doc_23528154
I almost got it working. I needed to change js.src assignment from js.src = "//connect.facebook.net/en_US/sdk.js"; to: js.src="https://connect.facebook.net/en_US/all.js"; But now when I enter the login screen I have this error: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this url, add all domains and subdomains of your app to the App Domains field in your app settings. I did just that but the same error is given. Any ideas? I have an app where I made a facebook login using JavaScript SDK. The code works great on mobile browser and on desktop or laptop browsers, but when I install the app using phonegap I have the next error: Uncaught ReferenceError: FB is not defined Can anyone please help me with this? I've read multiple threads on stack about this, but none of them seemed to make some light. My code is this: $(document).ready(function() { (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); window.fbAsyncInit = function() { FB.init({ appId: 'app_id_secret', xfbml: true, version: 'v2.7' }); }; // This is called with the results from from FB.getLoginStatus(). function statusChangeCallback(response) { if (response.status === 'connected') { // Logged into your app and Facebook. getUserData(); } else if (response.status === 'not_authorized') { // The person is logged into Facebook, but not your app. document.getElementById('status').innerHTML = 'Please log ' + 'into this app.'; } else { // The person is not logged into Facebook, so we're not sure if // they are logged into this app or not. document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.'; } } function checkLoginState() { FB.getLoginStatus(function(response) { statusChangeCallback(response); }); } $('.fb_login').on('click', function(e) { e.preventDefault(); FB.login(function(response) { if (response.authResponse) { FB.api('/me', { fields: 'name, email, first_name, last_name' }, function(response) {}); } }, { scope: 'email,public_profile', return_scopes: true }); }); }); I've also found this link Can Facebook JS SDK work with Phonegap / Cordova? where someone asks almost the same question. There is suggested to use an cordova plugin. Is this a solution? If yes, which one of them is best? A: There is a plugin called phonegap.facebook.inappbrowser, that I think it might help you. You can find the plugin here. First add the plugin script in your file head like this: <script type="text/javascript" src="js/phonegap.facebook.inappbrowser.js"></script> Then call it using your own custom parameters for app id, redirect url and permissions: // Settings FacebookInAppBrowser.settings.appId = '123456789'; FacebookInAppBrowser.settings.redirectUrl = 'http://example.com'; FacebookInAppBrowser.settings.permissions = 'email'; // Login(accessToken will be stored trough localStorage in 'accessToken'); FacebookInAppBrowser.login({ send: function() { console.log('login opened'); }, success: function(access_token) { console.log('done, access token: ' + access_token); }, denied: function() { console.log('user denied'); }, timeout: function(){ console.log('a timeout has occurred, probably a bad internet connection'); }, complete: function(access_token) { console.log('window closed'); if(access_token) { console.log(access_token); } else { console.log('no access token'); } }, userInfo: function(userInfo) { if(userInfo) { console.log(JSON.stringify(userInfo)); } else { console.log('no user info'); } } }); Also, I saw that you want to get the first_name and last_name of the logged in user. The plugin doesn't have those set by default after login. But you can modify a variable in the plugin file called get_url. Change it from this: var get_url = "https://graph.facebook.com/me?fields=email,name,gender&access_token=" + window.localStorage.getItem('facebookAccessToken'); To this: var get_url = "https://graph.facebook.com/me?fields=email,first_name,last_name,name,gender&access_token=" + window.localStorage.getItem('facebookAccessToken');
doc_23528155
when updating the same application i got this error. I need help, i searched but nothing worked for me. I am using android studio when i updated studio to 2.2 preview 1 i am getting this error. java 1.8.0_92 installed in my System. A: I found the solution , just extract apk with 7zip and deleted the META-INF folder and re-signed Apk A: This one works for me. Rebuild Project > Clean Project (Is this necessary?)> Generate Signed APK
doc_23528156
This is the code I tried: string readGZipLog () { try { using namespace boost::iostreams; ifstream file(currentFile.c_str(), std::ios_base::in | std::ios_base::binary); boost::iostreams::filtering_istream in; in.push(gzip_decompressor()); in.push(file); std::stringstream strstream; boost::iostreams::copy(in, strstream); return strstream.str(); } catch (std::exception& e) { cout << e.what() << endl; } } void writeGZipLog (char* data) { try { using namespace boost::iostreams; std::ofstream file( currentFile.c_str(), std::ios_base::out | std::ios_base::binary ); boost::iostreams::filtering_ostream out; out.push( gzip_compressor() ); out.push(file); std::stringstream strstream; strstream << data; boost::iostreams::copy( strstream, data ); } catch (std::exception& e) { cout << e.what() << endl; } } It compiles without any warnings (and of course errors) but the function readGZipLog() crashes while running: gzip error ./build: line 3: 22174 Segmentation fault ./test ./build is the script that compiles and starts the application ./test automatically I checked the file: It contains something, but I can't ungzip it using gunzip. So I am not sure whether the compression worked properly and if this has something to do with the gzip error thrown by Boost. Can you give me a hit where the error(s) is(/are)? Thanks for your help! Paul A: after a lot of research and trying I finally found a way how to handle (de)compression correctly. This is the code that works for me without any problems (with gzip and bzip2): string readGZipLog () { using namespace boost::iostreams; using namespace std; try { ifstream file(currentFile.c_str(), ios_base::in | ios_base::binary); boost::iostreams::filtering_istream in; in.push(gzip_decompressor()); in.push(file); stringstream strstream; boost::iostreams::copy(in, strstream); return strstream.str(); } catch (const gzip_error& exception) { cout << "Boost Description of Error: " << exception.what() << endl; return "err"; } } bool writeGZipLog (char* data) { using namespace boost::iostreams; using namespace std; try { std::ofstream file( currentFile.c_str(), std::ios_base::app ); boost::iostreams::filtering_ostream out; out.push( gzip_compressor() ); out.push(file); stringstream strstream; strstream << data; boost::iostreams::copy(strstream, out); return true; } catch (const gzip_error& exception) { cout << "Boost Description of Error: " << exception.what() << endl; return false; } } What I can say is that I did some errors that were not necessary and I just found by looking at the code again many hours later. boost::iostreams::copy( std::stringstream , char* ); for example will even fail if 1 + 1 was 3. I hope that this code piece will help somebody as it helped me. Paul :)
doc_23528157
For example, I can store my variables as either strings or integers (as below). In this case, which of the columns would be more efficient, for a 1 million row dataset, and why? string_col int_col code1 1 code2 2 code3 3 A: A rough approximation (this may change when you put it into a dataframe, which is another structure) > object.size("code1") 112 bytes > object.size(1) 56 bytes Or alternatively > object.size(df$string_col) 248 bytes > object.size(df$int_col) 64 bytes adding the string as a factor > object.size(df$string_col_fact) 648 bytes Using a bigger set: n = 10^6 sapply(list( str=data.frame(rep(c(paste0("code", 1:3)), n)), int=data.frame(rep(1:3, n)), strFactor=data.frame(factor(rep(c(paste0("code", 1:3)), n)))), object.size) # str int strFactor # 24000920 12000736 12001352 A: Under the hood, an R vector object is actually a symbol bound to a pointer (a VECSXP). The VECSXP points to the actual data-containing structure. The data we see in R as numeric vectors are stored as REALSXP objects. These contain header flags, some pointers (e.g. to attributes), a couple of integers giving information about the length of the vector, and finally the actual numbers: an array of double-precision floating point numbers. For character vectors, the data have to be stored in a slightly more complicated way. The VECSXP points to a STRSXP, which again has header flags, some pointers and a couple of numbers to describe the length of the vector, but what then follows is not an array of characters, but an array of pointers to character strings (more precisely, an array of SEXPs pointing to CHARSXPs). A CHARSXP itself contains flags, pointers and length information, then an array of characters representing a string. Even for short strings, a CHARSXP will take up a minimum of about 56 bytes on a 64-bit system. The CHARSXP objects are re-used, so if you have a vector of 1 million strings each saying "code1", the array of pointers in the STRSXP should all point to the same CHARSXP. There is therefore only a very small memory overhead of approximately 56 bytes between a one-million length vector of 1s and a one-million length vector of "1"s. a <- rep(1, 1e6) object.size(a) #> 8000048 bytes b <- rep("1", 1e6) object.size(b) #> 8000104 bytes This is not the case when you have many different strings, since each different string will require its own CHARSXP. For example, if we have 26 different strings within our 1-million long vector rather than just a single string, we will take up an extra 56 * (26 - 1) = 1400 bytes of memory: c <- rep(letters, length.out = 1e6) object.size(c) #> 8001504 bytes So the short answer to your question is that as long as the number of unique elements is small, there is little difference in the size of the underlying memory usage. However, a character vector will always require more memory than a numeric vector - even if the difference is very small.
doc_23528158
Several old machines functioned as "servers" in our environment and when I newly started working here, I wanted to change this cluster into something more appropriate. So I calculated how one big server would cost us a certain amount of money but we would save it in electricity-bills etc. The server finally arrived (HP Proliant) and I installed a Server 2008 R2 on it (boss wont pay for something newer a.k.a. more expensive). I created .vhd files of the HDDs of the servers I want to virtualize and copied those files into the new server. I activated Hyper-V role and created a new VM and selected one of the .vhd files as the HDD for that VM and started the machine. The machine starts, all goody. As far as I understand in Hyper-V we got 3 network-settings and for my purpose "external network" is the one to go with. Correct me if I'm wrong. The server is already in the domain. So I thought it should actually work already, but somehow I cannot connect to the domain. The network settings on the VM is DHCP but it is not getting an IP from the DC. Do I need to spoof the old MAC-Address? Do I have to turn the physical machine that I'm virtualizing off? (I didn't do that because I wanted to check first whether I can get both running at the same time before turning it off. Also I cannot access the environment past business hours, so testing this is when nobody is around is kinda out of question) The VM has W7 running on it, if it matters. I'm kinda lost what to do as I only find how to join a VM into a virtual network when I try to google for solutions. DC (physical, x.x.x.1 IP), The new server (physical, x.x.x.82 IP), The VM (virtual, DHCP, current address of its physical copy x.x.x.123 though DHCP is set on it, 123 is just the IP it got). Regards Edit: Found the solution. The server has 2 NICs. "Connection" and "Connection 2" or whatever it is called by standard in English. The virtual adapter (3rd NIC so to say) has "Connection 2" in its description too. I got confused and addressed the wrong NIC in the Hyper-V options. I am editing this from the VM that finally has connection to the domain. A: Has been resolved. Answer is in the edit of original post.
doc_23528159
<*> -- Does it mean that it cover any state (Initial + all the ones declared with /x) ? A: Yes, that's exactly what it means. See the start conditions section in the flex manual. Note that start conditions can be declared either with %x or %s. The difference is explained in the manual section linked above.
doc_23528160
public void btnFacebookClicked(View view) { openActiveSession(this,true,statusCallback); } Session.StatusCallback statusCallback = new Session.StatusCallback() { @Override public void call(final Session session, SessionState state, Exception exception) { if(session.isOpened()) { requestFacebookFriends(session); } } }; private void requestFacebookFriends(Session session) { Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() { @Override public void onCompleted(List<GraphUser> users, Response response) { // TODO: your code for friends here! Log.e("THIS IS FRIENDLIST",users.size()+""); } }); } A: It looks like you are using the facebook Graph v2.0, as of 30.4.2014 you cannot retrieve a full list of friends from facebook, only the ones who are using the app.
doc_23528161
export const useNavMenuOptions = () => { const intl = useIntl() const profile = intl.formatMessage({ id: 'profile.navMenu.profile' }) const addresses = intl.formatMessage({ id: 'profile.navMenu.addresses' }) const myOrders = intl.formatMessage({ id: 'profile.navMenu.myOrders' }) const navMenuOptions: NavMenuOption[] = [ { id: 0, label: profile, icon: BiUser, url: '/account/profile', }, { id: 1, label: addresses, icon: BiHomeAlt, url: '/account/address', }, { id: 2, label: myOrders, icon: BsBoxSeam, url: '/account/my-orders', }, ] const findSelectedOption = (url: string) => { const selectedOption: NavMenuOption | undefined = navMenuOptions.find( (option) => option.url === url ) if (selectedOption?.label) { return selectedOption?.label } return -1 } return { navMenuOptions, findSelectedOption } } I am then trying to use the findSelectedOption() function in a component and render the string it returns export const NavMenuMobile: React.FC<NavMenuProps> = ({ navMenuOptions, changeMenuOption, currentOption, findSelectedOption, }) => { const selectedOption = useMemo(() => { return findSelectedOption?.(currentOption) }, [currentOption]) console.log('selected option =>', selectedOption) return ( <Box p={4} borderBottomWidth="2px" borderBottomColor="shading.200"> {selectedOption} </Box> ) } selectedOption is returning the correct string but I have a TS lint error: Type 'void | undefined' is not assignable to type 'ReactNode'. what is the fix here? A: React Native really doesn't like undefined being rendered. Try null instead. const selectedOption = useMemo(() => { return findSelectedOption?.(currentOption) ?? null }, [currentOption]) Or: {selectedOption ?? null}
doc_23528162
"Could not load file or assembly 'DTI.FaxManJr, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)' sqlrd7 C:\Visual Studio Projects\pbrs\LC" I am workin with in a 64-bit Windows 10 OS and my project is using the framework .NET 4.6.1 I have tried removing and adding in this dll and any dependencies, unblocking them after I download them, so they aren't blocked by the firewall. I have also moved the dll in the root folder, bin folder, and it still is not working. Any help would greatly be appreciated! p.s. we do have a license for this dll, that file is in the root folder of the project. Here are some xml tags I noticed in my project. <Reference Include="DTI.FaxMan.Core, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3ff15c974c5defd8, processorArchitecture=x86"> <SpecificVersion>False</SpecificVersion> <Reference Include="DTI.FaxMan.Core"> <HintPath>Lib\DTI.FaxMan.Core.dll</HintPath> </Reference> <Reference Include="DTI.FaxMan.Print, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3ff15c974c5defd8, processorArchitecture=x86"> <SpecificVersion>False</SpecificVersion> <Reference Include="DTI.FaxMan.Print"> <HintPath>Lib\DTI.FaxMan.Print.dll</HintPath> </Reference> <Reference Include="DTI.FaxManJr, Version=0.0.0.0, Culture=neutral">
doc_23528163
I use protoc to generate python code, then create a transaction object, then update the data script_sig. In some case it should be None, but if I set it None, it occurs the error : TypeError: None has type NoneType, but expected one of: bytes Here is my code: message Transaction { repeated TxIn vin = 2; repeated TxOut vout = 3; } message TxIn { OutPoint prev_out_point = 1; bytes script_sig = 2; uint32 sequence = 3; } for i in range(len(tx.vin)): if i != index: tx.vin[index].script_sig = None else: tx.vin[index].script_sig = script_pub_key How can I do about this? thx. A: You can either store an empty bytes object (b''), or change the data type to optional bytes: optional bytes script_sig = 2;
doc_23528164
targetSDKVersion 19 and trying to use compile 'com.android.support:recyclerview-v7:19.0.+' is giving me an error failed to resolve ... When I go to SDK Manager, I can only see Android Support Library rev 23.1.1 available for download. If I use that version 23, then I have the error this support library should not use a different version ... My searches only bring up the fact I need to install same version of support library as I have targetted SDK - however as above, I can't find it ? A: The target SDK version and the version of the library must match. So rather than using the support library in version 19, upgrade your targetSDKVersion to 23 and also use the support library in version 23.1.1. If that doesn't work out of the box, try installing the google support repository from the SDK Manager. A: Try using this compile 'com.android.support:recyclerview-v7:23.1.0' and change your gradle file minSdkVersion 19 targetSdkVersion 23
doc_23528165
<Window.Resources> <Style x:Key="TrackingButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"> <Style.Triggers> <!--Default Base--> <Trigger Property="IsMouseOver" Value="False"> <Setter Property="Content"> <Setter.Value> <Image Source="Resources/Start_Base.png"/> </Setter.Value> </Setter> </Trigger> <!--Hover--> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Content"> <Setter.Value> <Image Source="Resources/Start_Hover.png"/> </Setter.Value> </Setter> </Trigger> </Style.Triggers> <!--Default Style--> <Style.Setters> <Setter Property="Background"> <Setter.Value> <SolidColorBrush Color="Transparent"/> </Setter.Value> </Setter> <Setter Property="BorderBrush"> <Setter.Value> <SolidColorBrush Color="Transparent"/> </Setter.Value> </Setter> </Style.Setters> </Style> </Window.Resources> Here is the default state of the button: DefaultState But when hovered over, the button loses its transparency and a white border appears around the areas that are supposed to be transparent: HoveredOver I'm not sure what's going on here.. A: If you want to get rid of the chrome, you could define your own custom ControlTemplate: <Style x:Key="TrackingButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Image x:Name="img" Source="Resources/Start_Base.png"/> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="img" Property="Source" Value="Resources/Start_Hover.png" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
doc_23528166
The problem occurs at the beginning of a function witch gets a year and returns 0, 1 weather it's a leap year or not. 22 p = inputParser; 23 p = p.addRequired('Year',@(x) all(isnumeric(x))); 24 p = p.parse(Year); The error I get is: error: value on right hand side of assignment is undefined error: called from leapyear at line 23 column 3 So why there is this inputParser at all? And how can I get it to work in the new Octave version? Unfortunately there is no documentation for the inputParser function: octave:23> help(inputParser) error: help: invalid input A: I cannot guess as to why that code worked in Octave 3.8, the oldest documentation for Octave available online is for version 4.0. The Octave 4.4 documentation specifies that inputParser.addRequired() doesn't have an output value. So change line 23 by removing p =, so that it reads: p.addRequired('Year',@(x) all(isnumeric(x))); Note that MATLAB's documentation for inputParser says the same thing.
doc_23528167
I need all the functionality of the current Cart Rules. I am looking at the AdminCartRulesController and ofcourse all the code is there. How can I "extend" or copy and modify it so that I will add one more input to the form, and the loop adding to database by form value? Is it possible ? A: You need to create the file: override\controllers\admin\AdminCartRulesController.php overriding the Core file the following way: <?php class AdminCartRulesController extends AdminCartRulesControllerCore { } and there to override the methods you need. Do not forget the clear the classes index (deleting cache/class_index.php) after adding the file.
doc_23528168
I've spent many hours trying the different fixes listed on Stack Overflow and other sites. I'm trying to get the logos in my wait panel to remain horizontal as the outer div rotates. This works perfectly in Chrome, Safari, Edge and Firefox. Just not in IE 11 (I'm not concerned with older versions of IE). As shown, even in IE11, the outer div rotates, and the progress overlay works as expected. But the ccw keyframe on the inner divs (encapsulating the logos and the progress overlays) are not working. Here is what it looks like in IE11 And what it looks like in the other browsers. I setup a fiddle for this, and tested it on Safari and IE11. To my surprise, the fiddle works! The problem is, I don't know why. I'm suspecting that the fiddle site has some code to deal with quirks in IE which is also fixed my fiddle. Fiddle On my production website, I have this wait panel in a bootstrap modal, so among the differences, there's the bootstrap library, bootstrap css, the modal markup, and modernizer. I just don't see how those would interfere with just the ccw keyframe animation and not affect the overlay animation. Actual Website I'm completely baffled at this point. It's not like animations aren't working at all, it's just the ccw keyframe that's not working. Interestingly, if I remove the cw keyframe then the ccw one works. CSS .waitPanel { overflow: hidden; } @keyframes cw { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes ccw { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -ms-transform: rotate(-360deg); -webkit-transform: rotate(-360deg); -moz-transform: rotate(-360deg); -o-transform: rotate(-360deg); transform: rotate(-360deg); } } @keyframes progress { 0% { width: 0; } 8% { width: 50px; } 16% { width: 75px; } 90% { width: 95px; } 100% { width: 105px; border-radius: 10px; } } .carrierLoading { width: 110px; height: 60px; position: absolute; -webkit-animation: ccw 10s linear infinite; -moz-animation: ccw 10s linear infinite; -ms-animation: ccw 10s linear infinite; -o-animation: ccw 10s linear infinite; animation: ccw 10s linear infinite; } .carrierLogos { width: 250px; margin: 50px auto; height: 250px; position: relative; -webkit-animation: cw 10s linear infinite; -moz-animation: cw 10s linear infinite; -ms-animation: cw 10s linear infinite; -o-animation: cw 10s linear infinite; animation: cw 10s linear infinite; } .carrierLoading .bullet { width: 40px; height: 40px; left: 35px; top: 0; position: absolute; font-size: 40px; } .carrierLoaded .overlay { position: absolute; top: 8px; left: 0; width: 0; background: rgba(0, 255, 0, .3); height: 46px; bottom: 8px; border-radius: 10px 0 0 10px; -webkit-animation: progress 60s linear 1s infinite; -moz-animation: progress 60s linear 1s infinite; -ms-animation: progress 60s linear 1s infinite; -o-animation: progress 60s linear 1s infinite; animation: progress 60s linear 1s infinite; } .carrierLoaded .bullet { display: none; } HTML <div id="Searching" title="Please Wait" style="text-align: center;"> <div class="waitPanel"> <p>Please wait while we lookup your insurance rates. This may take a few minutes.</p> <!-- <p><img src="/DemoAgent/Images/indicators/progress.gif" alt="Please Wait"/></p> --> <div class="carrierLogos"> <div class="carrierLoading " style="left: 195px; top: 95px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/10865.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: 175px; top: 163px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/UNITR.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: 122px; top: 209px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/KWPRE.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: 52px; top: 219px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/B4249.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: -12px; top: 189px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/GRNG.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: -50px; top: 130px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/10031.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: -50px; top: 60px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/10864.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: -12px; top: 1px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/PROGR.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: 52px; top: -29px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/KWPIO.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: 122px; top: -19px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/KWPAT.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> <div class="carrierLoading " style="left: 175px; top: 27px;"> <img src="http://www.demoagent.com/DemoAgent/Images/carriers/10730.gif"> <div class="bullet">•</div> <div class="overlay"></div> </div> </div> </div> </div> JAVASCRIPT (function($) { $(function() { $('.carrierLoading img').load(function() { $(this).closest('.carrierLoading').addClass('carrierLoaded'); }).each(function() { if ($(this).prop('complete')) { $(this).trigger('load'); } }); //animateSelector('.carrierLoading'); circleSelector('.carrierLoading'); }); })(jQuery); // arranges logos along a circular path. // if width is less than 85, move logos randomly, otherwise // rotate the circle (see css animations). function circleSelector(selector) { var fields = $(selector); var height = $('.carrierLogos').height(); var width = $('.carrierLogos').width(); var radius = Math.min(height, width) / 2; if (radius < 85) { $('.carrierLogos, .carrierLoading, .carrierLoaded').css('animation', 'none'); animateSelector('.carrierLoading, .carrierLoaded'); return; } var angle = 0; var step = (2 * Math.PI) / fields.length; fields.each(function() { var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2); var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2); $(this).css({ left: x + 'px', top: y + 'px' }); angle += step; }); } function makeNewPosition() { // Get viewport dimensions (remove the dimension of the div) var h = $('.carrierLogos').height() - 60; var w = $('.carrierLogos').width() - 110; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh, nw]; } // moves logos randomly function animateSelector(selector) { $(selector).each(function() { var newq = makeNewPosition(); var oldq = $(this).offset(); var speed = calcSpeed([oldq.top, oldq.left], newq); $(this).animate({ top: newq[0], left: newq[1] }, speed, function() { animateSelector(this); }); }); }; function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest / speedModifier); return speed; } A: I've found a workaround for this. Delaying the animations until the page has loaded worked some of the time. Adding a slight delay seems to work consistently. I also removed the vendor specific markup. That is unnecessary for all the browsers that I'm targeting. .carrierLoading { ... /* animation: ccw 10s linear infinite; */ } .carrierLogos { /* animation: cw 10s linear infinite;*/ } $(window).load(function () { setTimeout(function () { $('.carrierLoading').css('animation', 'ccw 10s linear infinite'); $('.carrierLogos').css('animation', 'cw 10s linear infinite'); },1000); }); I'm still interested in an answer that doesn't rely on timing to work properly.
doc_23528169
A: You can specify the artifact-name with the maven boot plugin: In this case, it will be NewJarName.jar <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> <configuration> <finalName>NewJarName</finalName> </configuration> </execution> </executions> </plugin>
doc_23528170
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application And i am using method below to query EF public virtual IEnumerable<TEntity> Get( Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "") { IQueryable<TEntity> query = dbSet; if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { return orderBy(query).ToList(); } else { return query.ToList(); } } Now i want to create dynamic Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> expression to order my data. I know only field name as string and order type (ascending, descending) as string (asc, desc) A: This is very late to the party but the correct answer is located on another question at https://stackoverflow.com/a/10935223/14275 var students = repository.Get(x => x.FirstName = "Bob",q => q.OrderBy(s => s.LastName)); A: I am not sure what exactly you want to accomplish, but I had changed your code and add some example to demonstrate how does it work. This is a simple console app, which has dummyText as list. Queryable method enables to use filter and sort expression as you want. I hope it helps class Program { private List<string> _dummyText = new List<string>(){ "Arda", "Araba", "Antartika", "Balon"}; static void Main(string[] args) { Program p = new Program(); List<string> result = p.Get(s => s.StartsWith("A"), orderBy: q => q.OrderBy(d => d.Length)).ToList(); Console.ReadLine(); } public virtual IEnumerable<string> Get( Expression<Func<string, bool>> filter = null, Func<IQueryable<string>, IOrderedQueryable<string>> orderBy = null) { IQueryable<string> query = _dummyText.AsQueryable(); if (filter != null) { query = query.Where(filter); } if (orderBy != null) { return orderBy(query).ToList(); } else { return query.ToList(); } } } A: finally i could write the method i want. public static Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> GetOrderBy(string orderColumn, string orderType) { Type typeQueryable = typeof(IQueryable<TEntity>); ParameterExpression argQueryable = Expression.Parameter(typeQueryable, "p"); var outerExpression = Expression.Lambda(argQueryable, argQueryable); string[] props = orderColumn.Split('.'); IQueryable<TEntity> query = new List<TEntity>().AsQueryable<TEntity>(); Type type = typeof(TEntity); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach(string prop in props) { PropertyInfo pi = type.GetProperty(prop, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); expr = Expression.Property(expr, pi); type = pi.PropertyType; } LambdaExpression lambda = Expression.Lambda(expr, arg); string methodName = orderType == "asc" ? "OrderBy" : "OrderByDescending"; MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { typeof(TEntity), type }, outerExpression.Body, Expression.Quote(lambda)); var finalLambda = Expression.Lambda(resultExp, argQueryable); return (Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>)finalLambda.Compile(); } This method takes two parameters, first one field name other one is asc or desc. Result of method can be used directly with IQueryable object. Thanks for your helps
doc_23528171
My intention is to use the aws configure / aws credential helper method as I prefer this, in this context, to a username / password. When attempting any git operations I get: aws codecommit credential-helper $@ get: aws: command not found I'm then able to then use a username and password but this invalidates the point of using aws configure to set up access keys. The credentials section of my .gitconfig file looks like this: [credential] helper = !aws codecommit credential-helper $@ UseHttpPath = true It looks like git can't access aws.cmd but the full path to it is on the system and user path environment settings. Any ideas? A: It seems like a recent update of the AWS CLI for windows possibly removed something. Can you try this as a workaround? [credential] helper = !'C:\\Program Files\\Amazon\\AWSCLI\\bin\\aws.cmd' codecommit credential-helper $@ UseHttpPath = true
doc_23528172
How do I add the title which should be a row with cell merged and also show the filter parameters on which the data is generated in the excel sheet? var mystyle = { headers: true, column: { style: { Font: { Bold: "1" } } }, }; let dataCopy = JSON.parse(JSON.stringify(dataFiltered)); alasql('SELECT * INTO XLSX("' + reportName + '",?) FROM ?', [mystyle, dataCopy]); I have filterParams array which contains the filter parameters with value in the key value pair. I want to generate the excel sheet with the title of the table in the first row below which the data should be generated. After the title should come the parameters which are to be displayed. A: ALASQL doesn't support merging cells or applying filters. But you can add a title/header row. You need to create a header row with the same number of columns and same keys as your data has. Then merge this header row with your data and import in excel. var headers = alasql('select "Title 1" as Key1, "Title 2" as Key2, "Title 3" as Key3'); let dataCopy = JSON.parse(JSON.stringify(dataFiltered)); var mergedArray = $.merge(headers, dataCopy); alasql('SELECT * INTO XLSX("' + reportName + '",?) FROM ?', [mystyle, mergedArray]); Please accept the answer if it solves your problem. Cheers!
doc_23528173
I found topics with similar issues but none of the solutions worked for me. I read that I needed to replace navigationOptions by defaultNavigationOptions however this did not solve the issue. Any one have an idea how I can fix that? const tabNavigator = TabNavigator.createStyles(); export default createBottomTabNavigator( { Overview: { resetOnBlur: true, screen: OverviewStack, navigationOptions: { title: "Home", }, }, Settings: { screen: SettingsStack, resetOnBlur: true, navigationOptions: { title: "Settings", }, }, }, { tabBarOptions: { showLabel: true, labelStyle: {}, hidden: true, activeBackgroundColor: Colors.navigationBkgdActive, activeTintColor: Colors.navigationColorActive, inactiveBackgroundColor: Colors.navigationBkgd, inactiveTintColor: Colors.navigationColor, backgroundColor: Colors.navigationColor, labelBottomStyle: { fontSize: Fonts.bodyFontSizeSmall, }, style: { backgroundColor: Colors.navigationBkgd, height: 64, }, indicatorStyle: { backgroundColor: "transparent", }, }, navigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused }) => { const icons = { Overview: "home-outline", Settings: "settings", }; const style = focused ? tabNavigator.activeTab : {}; return ( <View style={tabNavigator.container}> <View style={style} /> <Icon style={[ tabNavigator.icon, { color: focused ? "#D97D54" : "lightgray" }, ]} size={28} name={icons[navigation.state.key]} /> </View> ); }, showIcon: true, }), } ); A: I ran into a similar issue with icons, mines related to the settings icon. I cannot see you import statements but this is what I did in the end. Before which originally worked on EXPO 38 SDK but doesn't on EXPO 42 SDK: // Import Statements... import { MaterialCommunityIcons } from '@expo/vector-icons'; // Further down in TabNavigator code... <MaterialCommunityIcons name="settings" size={28} color={tintColor} /> After upgrading to EXPO 42 SDK: // Import Statements... import { MaterialCommunityIcons } from '@expo/vector-icons'; // Further down in TabNavigator code... <MaterialCommunityIcons name="account-settings" size={28} color={tintColor} /> According to the list of Material Icons, it appears that "settings" has been renamed to to "cog" but I wanted to change mine to look more like "account-cog", So I highly recommend you look through and identify which Icons you want as they may have been renamed.
doc_23528174
Creat_Dttm Month 2014-01-01 00:33:58.000 = 1/1/2014 2014-01-01 07:40:01.000 = 1/1/2014 2014-01-03 01:50:12.000 = 1/1/2014 2014-02-18 11:42:13.000 = 2/1/2014 2014-02-20 07:49:11.000 = 2/1/2014 2014-04-09 06:02:36.000 = 4/1/2014 A: select CAST(MONTH(Creat_Dttm) AS VARCHAR(2)) + '/1/' + CAST(YEAR(Creat_Dttm) AS VARCHAR(4)) as month from TEMPSO_INV_DATA
doc_23528175
But I'm always getting an error: 'QuerySet' object has no attribute 'get_quantities_sold' Here is my model: generate_ref_no = str(uuid.uuid1()) class Transaction(models.Model): business = models.ForeignKey(Business_Account, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) amount = models.FloatField() productSold = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quanties_of_product_sold = models.IntegerField() transaction_date = models.DateTimeField(auto_now_add=True) payment_method = models.CharField(choices=PAYMENT_METHOD, max_length=50) reference_num = models.CharField(max_length=50, editable=False, default=generate_ref_no) def __str__(self): return f'{self.customer} ' def get_quantities_sold(self,quantities_sold): return print(quantities_sold) My view: class TransactionView(generics.GenericAPIView): def post(self,request, business=None): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save() getTransaction = Transaction.objects.filter(reference_num=serializer.data['reference_num']) getTransaction_serializer = TransactionSerializer(getTransaction, many=True) getTransaction.get_quantities_sold(serializer.data['quanties_of_product_sold ']) return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_404_NOT_FOUND) I'm trying to call the 'get_quantities_sold' method from the Transaction model in my transaction view but I'm an error: QuerySet' object has no attribute 'get_quantities_sold' A: getTransaction is in your method is a QuerySet and thus a collection of items, not a single item, hence getTransaction.get_quantities_sold makes no sense. You can retrieve a single Transaction object by using .get(…) [Django-doc] over .filter(…) [Django-doc]: getTransaction = Transaction.objects.get( reference_num=serializer.data['reference_num'] ) It might also be worth to guarantee uniqueness for the reference_num with: reference_num = models.CharField( max_length=50, editable=False, default=generate_ref_no, unique=True )
doc_23528176
sample_photo_rep["photo"]["tags"]["tag"] for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]: print [sample_tags_list['raw'].decode('utf-8')] current output: [u'Nature'] [u'Mist'] [u'Mountain'] correct output: [u'nature', u'mist', u'mountain'] A: In each loop, you're printing a list containing a single element, i.e. [u'Nature'], [u'Mountain'], etc. If you remove the enclosing braces, i.e. [sample_tags_list['raw'].decode('utf-8')] to sample_tags_list['raw'].decode('utf-8'), you should just get the string. Not sure why your append didn't work, as output = [] for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]: output.append(sample_tags_list['raw'].decode('utf-8')) should do the trick. A list comprehension would accomplish the same thing as in the answer from @abccd; both give the same output. A: You can always use list comprehension like this: print [sample_tags_list['raw'].decode('utf-8') for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]] In place of your for loop. This is by far still the most preferred way of doing this. You can see the pydoc for a simple example of using list comps. A: declare an empty list at the top of your code like this: tags = [] Then, instead of printing it out in your for loop append it to the list: for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]: tags.append([sample_tags_list['raw'].decode('utf-8')]) Then tags should be this: [u'nature', u'mist', u'mountain'] Further Reading Info on appending to lists: https://www.tutorialspoint.com/python/list_append.htm Info on lists in general: https://developers.google.com/edu/python/lists
doc_23528177
What I have: indexAarrays = [['bar', 'bar', 'baz', 'baz', ], ['one', 'two', 'one', 'two']] indexTuples = list(zip(*indexAarrays)) index = pd.MultiIndex.from_tuples(indexTuples, names=['firstIndex', 'secondIndex']) colAarrays = [['c1', 'c1', 'c2', 'c2', ], ['d1', 'd2', 'd1', 'd2']] colTuples = list(zip(*colAarrays )) col = pd.MultiIndex.from_tuples(colTuples, names=['firstCol', 'secondCol']) df = pd.DataFrame(data=np.random.random_sample((len(index), len(col))), index=index, columns=col) df The above gives the DF i have: firstCol c1 c2 secondCol d1 d2 d1 d2 firstIndex secondIndex bar one 0.231221 0.846196 0.037493 0.516474 two 0.810847 0.204095 0.423766 0.513262 baz one 0.433040 0.118018 0.267039 0.356261 two 0.529042 0.181886 0.093488 0.643357 What I want: wantedCols = [idxName for idxName in index.names] \ + [colName for colName in col.names]\ + ['Value'] dfWanted = pd.DataFrame(index = range(int(df.shape[0]*df.shape[1]/(len(wantedCols)-1))), columns=wantedCols) idxCounter = 0 for idx1 in df.index.get_level_values(0).unique(): for idx2 in df.index.get_level_values(1).unique(): for c1 in df.columns.get_level_values(0).unique(): for c2 in df.columns.get_level_values(1).unique(): dfWanted.loc[idxCounter, 'firstIndex'] = idx1 dfWanted.loc[idxCounter, 'secondIndex'] = idx2 dfWanted.loc[idxCounter, 'firstCol'] = c1 dfWanted.loc[idxCounter, 'secondCol'] = c2 dfWanted.loc[idxCounter, 'Value'] = df.loc[(idx1, idx2), (c1, c2)] idxCounter += 1 dfWanted The above gives the DF I want: firstIndex secondIndex firstCol secondCol Value 0 bar one c1 d1 0.231221 1 bar one c1 d2 0.846196 2 bar one c2 d1 0.037493 3 bar one c2 d2 0.516474 4 bar two c1 d1 0.810847 5 bar two c1 d2 0.204095 6 bar two c2 d1 0.423766 7 bar two c2 d2 0.513262 8 baz one c1 d1 0.43304 9 baz one c1 d2 0.118018 10 baz one c2 d1 0.267039 11 baz one c2 d2 0.356261 12 baz two c1 d1 0.529042 13 baz two c1 d2 0.181886 14 baz two c2 d1 0.0934878 15 baz two c2 d2 0.643357 Does anyone know of an easier way to reset the indices than the method I used above? A: Use DataFrame.stack by both levels and then convert MultiIndex Series to columns by Series.reset_index: df = df.stack([0,1]).reset_index(name='Value') print (df) firstIndex secondIndex firstCol secondCol Value 0 bar one c1 d1 0.746027 1 bar one c1 d2 0.622784 2 bar one c2 d1 0.613197 3 bar one c2 d2 0.449560 4 bar two c1 d1 0.560810 5 bar two c1 d2 0.125046 6 bar two c2 d1 0.147148 7 bar two c2 d2 0.622862 8 baz one c1 d1 0.537280 9 baz one c1 d2 0.801410 10 baz one c2 d1 0.889445 11 baz one c2 d2 0.226477 12 baz two c1 d1 0.100759 13 baz two c1 d2 0.279383 14 baz two c2 d1 0.041767 15 baz two c2 d2 0.739942
doc_23528178
import pandas as pd import matplotlib.pyplot as plt df=pd.read_csv('F:/ex2data2.txt', sep=",", header=None) X=df.iloc[:, :2] y=df.iloc[:, 2] def plotData(X,y): fig=plt.figure() pos = y==1 neg = y==0 plt.plot(X[pos, 0], X[pos, 1], 'k*') plt.plot(X[neg, 0], X[neg, 1], 'ko') plt.show() plotData(X,y) The line "plt.plot(X[pos, 0], X[pos, 1], 'k*') and plt.plot(X[neg, 0], X[neg, 1], 'ko')" is showing error. Can anyone help me with the reason? A: Use DataFrame.loc for select DataFrame by boolean mask and by column 0 or 1: X=df.iloc[:, :2] y=df.iloc[:, 2] def plotData(X,y): fig=plt.figure() pos = y==1 neg = y==0 plt.plot(X.loc[pos, 0], X.loc[pos, 1], 'k*') plt.plot(X.loc[neg, 0], X.loc[neg, 1], 'ko') plt.show() plotData(X,y) Or convert values of Dataframe and Series to numpy arrays: X=df.iloc[:, :2].to_numpy() y=df.iloc[:, 2].to_numpy() #oldier pandas versions #X=df.iloc[:, :2].values #y=df.iloc[:, 2].values def plotData(X,y): fig=plt.figure() pos = y==1 neg = y==0 plt.plot(X[pos, 0], X[pos, 1], 'k*') plt.plot(X[neg, 0], X[neg, 1], 'ko') plt.show() plotData(X,y)
doc_23528179
public Timer timer = new Timer(); private string jsonContents; private string currentTickerPlaylist; private int i = 0; private List<string> playlistTickers; public void StartTickerTimer(int seconds, string selectedPlaylist) { currentTickerPlaylist = selectedPlaylist; InitPlaylistTickerTimer(seconds); } public void StopTickerTimer() { StopTimer(); } private void InitPlaylistTickerTimer(int seconds) { timer.Elapsed += new ElapsedEventHandler(t_Tick); timer.Interval = seconds * 1000; timer.AutoReset = true; timer.Start(); } private void StopTimer() { timer.Stop(); } private void t_Tick(object sender, EventArgs e) { SetPlaylistTickerSettings(); if (i >= playlistTickers.Count) { i = 0; Payload ticker = new Payload { ticker = playlistTickers[i] }; Payload ticker2 = new Payload { payload = ticker }; var json = ServiceStack.Text.JsonSerializer.SerializeToString(ticker2); PutToSingular("url", json); i++; } else { Payload ticker = new Payload { ticker = playlistTickers[i] }; Payload ticker2 = new Payload { payload = ticker }; var json = ServiceStack.Text.JsonSerializer.SerializeToString(ticker2); PutToSingular("url", json); i++; } } A: You started your timer, but you are not calling your "StopTimer" anywhere in the code...
doc_23528180
It is distinct from cross field validation in which a value of one field is dependent upon the value(s) of one or more of the rest of the fields. Given below a simple scenario. <p:inputText id="txt1" value="#{testBean.txt1}" required="false" maxlength="45"/> <p:inputText id="txt2" value="#{testBean.txt2}" required="false" maxlength="45"/> <p:inputText id="txt3" value="#{testBean.txt3}" required="false" maxlength="45"/> <p:commandButton id="btnSubmit" actionListener="#{testBean.insert}" icon="ui-icon-check" value="Save"/> In which, validation violation should be occurred only when one of the given three text fields is left blank. If anyone of them is filled with a value then, all should be validated. In which case, validation should not be violated. How to proceed with this scenario? Does JSF/PrimeFaces provide some way to perform validation in this way? A: I have a hard time in wrapping my head around your concrete functional requirement, but I believe you're looking for "all or none" validation. I.e. either all fields should be blank, or all fields should be filled. JSF utility library OmniFaces has a validator for exactly this purpose, the <o:validateAllOrNone>. Here's how you could use it: <p:inputText id="txt1" value="#{testBean.txt1}" maxlength="45" /> <p:inputText id="txt2" value="#{testBean.txt2}" maxlength="45" /> <p:inputText id="txt3" value="#{testBean.txt3}" maxlength="45" /> <o:validateAllOrNone components="txt1 txt2 txt3" /> A: Of course! Primefaces provide a lot of ways that can satisfact you. First of all, you can make validations in your MBean method. In your case, you're calling insert method, so you can do something like this: public String insert(){ boolean error = false; if(txt1.isEmpty()){ error = true; } if(txt2.isEmpty()){ error = true; } if(txt3.isEmpty()){ error = true; } if(error == true){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Empty fields!", "Insert something in at least one input!")); return null; }else{ return "myPage" } } Note that you can improve the validations by yourself, following your needs. You can also change the message from: FacesMessage.SEVERITY_WARN to: FacesMessage.SEVERITY_INFO FacesMessage.SEVERITY_ERROR FacesMessage.SEVERITY_FATAL What can give your application a better error message. Before this works, add this above your input fields: <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> Probably this will work like a charm! If you're interested, check the Primefaces Messages showcase, where you can find some examples and understand better how <p:messages> works. Also, feel free to check <p:growl>, that in my opinion is a lot better than simple messages. Check out the growl here. Hope I helped you (:
doc_23528181
But I want them to be autonomous : they should be able to create their own service accounts on the scopes I allow. The issue is that if I give them the IAM editor permisson, they can grant themselves any other permission in the project. The Kubernetes's RBAC API is very well designed for that and a user who is able to modify the roles can't put more permission than the ones he has. So is it possible to have for example a user with the Cloud SQL admin role, to allow him to grant similar permissions to service accounts, but also to prevent him from granting Cloud Storage permissions ? A: Sadly not. It's not possible to prevent "roles/permission escalation". If someone is IAM admin, he can assign the role that her want, even to himself and higher they hide current permission. However, you have policies which allow you to limit things on the project or organisation: allowed API, external account allowed, public IP... A: I want to create a GCP project and to grant access on specific APIs / permissions to a team. You can do that for services, that is one of the reasons that Google IAM exists. You cannot specify roles for APIs specifically - you can prevent any APIs from being enabled by not granting permission to enable services. You can use Organization Policy Contraints to prevent certain APIs from being enabled for the project but not for individuals. But I want them to be autonomous : they should be able to create their own service accounts on the scopes I allow. This is not supported by Google Cloud IAM. If you have permission to create a service account (roles/iam.serviceAccountAdmin), you also have permission to assign roles to that service account. This is an admin level permission that should only be granted to admins and not regular users. Manage this role carefully as an admin can create a service account with the Project Owner role. So is it possible to have for example a user with the Cloud SQL admin role, to allow him to grant similar permissions to service accounts, but also to prevent him from granting Cloud Storage permissions ? This is not supported. In order to have permission to assign roles to a service account, you must be a service account admin. A: It seems it is possible as per the documentation here: https://cloud.google.com/iam/docs/setting-limits-on-granting-roles In large organizations, it can be helpful to let teams independently manage the Identity and Access Management (IAM) policies for their resources. However, letting a principal grant or revoke all IAM roles can greatly increase your security risk. Given use case: Consider a scenario where you want to let a user, Finn (finn@example.com), act as a limited IAM admin for your project. You want Finn to be able to grant and revoke only the Billing Account Administrator (roles/billing.admin) and Billing Account User (roles/billing.user) roles for your project. I'm trying to achieve the same thing. I want a Terraform service account to be able to do everything it needs to do, EXCEPT allow users to elevate their role beyond the scope of the project (ie. No owner level roles, only resource level roles).
doc_23528182
What are the best practices to perform that task? A: * *Stage 1 - take a look at this module node-xlsx or more robust and possibly better for your needs xlsx. *Stage 2 - Writing the file to JSON - if the module can return a JSON format then great. If you use xlsx it has an option to JSON --> take a look here. *Since you may need to actually strip and/or protect special accents etc. you may need to validate the data which is returned before producing a JSON file. *As to actually writing a JSON file, there are a huge amount of NPM modules for the task.
doc_23528183
Any help would be great : ) A: Because you mentioned flash I think you search a player for web pages, am I right? If yes, then you could take a look at jsmad. It's a decoder (aka player) written in JavaScript (but therefore needs a decent browser). Or you could use the audio-Tag of HTML5.
doc_23528184
class Tiger extends Animal { ... } class Deer extends Animal { ... } Now I wanted to have a namedQuery as class Animal { ... static namedQueries = { findAllAnimalBySpecies{ ... some logic for fetch only Tiger ... some logic for fetch only Deer } } } In controller, def tigers = Animal.findAllAnimalBySpecies().list() How is it possible to fetch only "Tiger"s by querying the Animal? Or i am missing proper concept. A: Give this a try: class Animal { ... static namedQueries = { findAllAnimalBySpecies { species -> switch(species) { case 'tiger': Tiger.all break case 'lion': Lion.all break ... } } } } and then: def tigers = Animal.findAllAnimalBySpecies('tiger').list()
doc_23528185
I want to be able to add topics not selected in the list to the lookup table where the topic_fk does not already exist for the specimen_fk: CREATE TABLE IF NOT EXISTS `specimen_topic_lookup` ( `specimen_topic_lookup_pk` int(6) NOT NULL AUTO_INCREMENT, `specimen_fk` int(6) NOT NULL, `topic_fk` int(3) NOT NULL, PRIMARY KEY (`specimen_topic_lookup_pk`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci AUTO_INCREMENT=8 ; Any ideas how I can do this? UPDATE I have made the fields specimen_fk and topic_fk UNIQUE. Using the code below, only one record is created in specimen_table lookup, when two records should have been created (before making the fields UNIQUE, two records were created OK...). I assume this is because $specimen_pk is the same value for each insert. foreach($topics as $topic){ $query_topics = "INSERT IGNORE INTO specimen_topic_lookup(specimen_fk, topic_fk) VALUES ('$specimen_pk', '$topic')"; $result_topics = mysql_query($query_topics, $connection) or die(mysql_error()); } Looks like having UNIQUE is stopping having a record made with the same value (which is at least what I expected...) THIS WORKS Without having to make specimen_fk OR topic_fk UNIQUE... foreach($topics as $topic){ $query_topics = "INSERT INTO specimen_topic_lookup(specimen_fk, topic_fk) SELECT '$specimen_pk', '$topic' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM specimen_topic_lookup WHERE specimen_fk = '$specimen_pk' AND topic_fk = '$topic')"; $result_topics = mysql_query($query_topics, $connection) or die(mysql_error()); A: Create a unique index on the table and use insert ignore or on duplicate key update: create unique index specimen_topic_lookup(specimen_fk, topic_fk); insert ignore into specimen_topic_lookup(specimen_fk, topic_fk) select $speciment_fk, $topic_fk; Or, alternatively, you can just do the following without the unique index: insert into specimen_topic_lookup(specifmen_fk, topic_fk) select $speciment_fk, $topic_fk from dual where not exists (select 1 from specimen_topic_lookup where specimen_fk = $specimen_fk and topic_fk = $topic_fk ); A: Use an INSERT IGNORE statement. This will insert any rows that do not violate the unique key, and ignore the ones that do.
doc_23528186
Does anybody have an idea what's going wrong here? Thanks a lot! EDIT: Here comes the code: #include <stdio.h> #include <pthread.h> #include <time.h> #include <sys/time.h> // replacement function because OS X doesn't seem to have clock_gettime() static int clock_gettime(int clk_id, struct timespec* t) { struct timeval now; int rv = gettimeofday(&now, NULL); if(rv) return rv; t->tv_sec = now.tv_sec; t->tv_nsec = now.tv_usec * 1000; return 0; } static void *threadproc(void *data) { pthread_mutex_t mutex; pthread_mutexattr_t attr; pthread_cond_t cond; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cond, NULL); for(;;) { struct timespec ts; clock_gettime(0, &ts); // wait 60ms ts.tv_nsec += 60 * 1000000; pthread_mutex_lock(&mutex); pthread_cond_timedwait(&cond, &mutex, &ts); pthread_mutex_unlock(&mutex); #if 0 pthread_testcancel(); #endif } return NULL; } int main(int argc, char *argv[]) { pthread_t pThread; pthread_create(&pThread, NULL, threadproc, NULL); printf("Waiting...\n"); sleep(5); printf("Killing thread...\n"); pthread_cancel(pThread); pthread_join(pThread, NULL); printf("Ok!\n"); return 0; } A: Your expectations about how the code should behave are correct, and in fact it works as expected on other systems I just tested. I think you've just found (yet another) bug in OSX. A: pthread_cancel functions correctly in OS X 10.11.4 (and possibly earlier versions). In addition, the value_ptr argument of pthread_join returns PTHREAD_CANCELED, as should be expected.
doc_23528187
When passing parameters instead the first parameter (%1) should be PARAM and the other parameters are shown in the list. %epin% or %1 contains the file with full path and no extensions for input files %epout% or %2 contains the file with full path and no extensions for output files %epinext% or %3 contains the extension of the file selected from the EP-Launch program. Could be imf or idf -- having this parameter ensures that the correct user selected file will be used in the run. %epwthr% or %4 contains the file with full path and extension for the weather file %eptype% or %5 contains either "EP" or "NONE" to indicate if a weather file is used %pausing% or %6 contains Y if pause should occur between major portions of batch file %maxcol% or %7 contains "250" if limited to 250 columns otherwise contains "nolimit" if unlimited (used when calling readVarsESO) %convESO% or %8 contains Y if convertESOMTR program should be called %procCSV% or %9 contains Y if csvProc program should be called %cntActv% or %10 contains the count of other simulations active or about to be active %multithrd% or %11 contains N if multithreading should be disabled All i want is to pass parameters %1, %2, %3, %4 and %5... the rest should not be set... Can somebody please tell me how this works? I searched the web and tried for hours but i won`t get this. Thanks and greets! A: It looks to me like the author of this batch file allows you to use it in 2 different ways, Option 1 Just pass the parameters on the command line, file.bat Param1 Param2 Param3 ..... Option 2 set the variables listed and then call the batch file with the single parameter that is exactly PARAM. SET epin=Param1 SET epout=Param2 ... file.bat PARAM A: what is the problem with ?: set "epin=%~dpfn1" set "epout=%~dpfn2" set "epinext=%~3" if /I not .%epinext% equ .imf ( if /I not .%epinext% equ .idf ( echo wrong extension exit /b 1 ) ) set "epwthr=%%~dpfnx4" set "eptype=%%~5" A: use a short batchfile (in fact it is very short: one line) (you could name it "DoFile.bat") @file.bat %1 %2 %3 %4 %5 Y "250" Y Y 3 N It takes 5 parameters and starts the wanted batch with the full amount of 11 parameters. It might be neccessary to adapt it a little bit to the needs of file.bat (no errorhandling included)
doc_23528188
But also have reserved url's, such as url.com/categories, url.com/login etc. I have states setup for the reserved url's e.g. .state('categories',{ url:'/categories', // i.e. url.com/categories ... }); Then I've tried to provide a regex for the root state that would match for usernames and not match for the above reserved url states e.g. $stateProvider .state('profile',{ url:'/{username:^((categories|login(?!$)).+|(?!categories|login).+)$}', ... }); I reviewed the UI-Router URL-Routing documentation (https://github.com/angular-ui/ui-router/wiki/URL-Routing) and attempted to understand urlMatcher, as well as make my regex comply. Currently it will take me to the reserved states e.g. url.com/categories but if I attempt to visit url.com/someusername it doesn't load the profile and takes me to url.com/ Do I need to change my regex? Is it possible to do this with a certain regex, or is urlMatcher not capable of handling reserved + dynamic url's / 'does not match' regex? A: The order you set up the states does matter here. When it finds the first match, it will stop looking and just use the first state it matches on. This is useful when you want to catch some states before others. You can set up all your reserved states before you setup your dynamic ones. $stateProvider .state('categories',{ url:'/categories', ... }) .state('login',{ url:'/login', ... }) .state('profile',{ url:'/:username', ... }); Example: http://fiddle.jshell.net/TheSharpieOne/ftxfceg1/1/
doc_23528189
I'm working on Eclipse, I build with clean install and run the app with springboot:run. I've setup a controller and a couple of template and css but it seems that thymeleaf cannot find the css, in the browser it shows the template (es. 'panda.html') without loading the css but if I open manually the .html the browser load also the .css . What i need to add to my code? this is the mapping @Controller public class MyController { @Autowired UtentiRepository utentiRepository; @GetMapping("/gab") public String panda(Model model) { return "panda"; } and this is the template resolver @Bean public SpringResourceTemplateResolver templatecssResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(applicationContext); templateResolver.setPrefix("classpath:/static/css/"); templateResolver.setSuffix(".css"); return templateResolver; } @Bean public SpringResourceTemplateResolver templateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(applicationContext); templateResolver.setPrefix("classpath:/templates/"); templateResolver.setSuffix(".html"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.addTemplateResolver(templatecssResolver()); templateEngine.setTemplateResolver(templateResolver()); templateEngine.setEnableSpringELCompiler(true); return templateEngine; } @Override public void configureViewResolvers(ViewResolverRegistry registry) { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); registry.viewResolver(resolver); } A: You've to override the addResourceHandlers(..) method of the you calls that implements the WebMvcConfigurerAdapter not as a bean (SpringResourceTemplateResolver ) SO just add the overiding method @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/**") .addResourceLocations("classpath:/static/css/"); } in your template use <link href="<c:url value="/css/style.css" />" rel="stylesheet"> or using themleaf <link th:href="@{/css/style.css}" />" rel="stylesheet">
doc_23528190
function user_data($user_id) { $data = array(); $user_id = (int)$user_id; $func_num_args = func_num_args(); $func_get_args = func_get_args(); if ($func_num_args > 1) { unset($func_get_args[0]); $fields = '`' . implode('`, `', $func_get_args) . '`'; $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM users WHERE user_id = $user_id")); return $data; } } to this: function user_data($user_id) { $data = array(); $user_id = (int)$user_id; $func_num_args = func_num_args(); $func_get_args = func_get_args(); if ($func_num_args > 1) { unset($func_get_args[0]); $fields = '`' . implode('`, `', $func_get_args) . '`'; $query = $db->prepare("SELECT $fields FROM `admin` WHERE `id` = :user_id"); $query->bindParam(":user_id", $user_id); $query->execute(); $data = $query->fetch(PDO::FETCH_ASSOC); print_r ($data); } } Problem is I cannot get the second bit to work. I keep getting this: Fatal error: Call to a member function prepare() on a non-object in /home/ds4887/public_html/silverjet/v1.20/admin/core/functions/main.php on line 39 If you need any other information I will be more than glad to provide it. If not possible than can somebody please so me the correct method to do this. THe top works, the bottom needs to work. Thanks in advance A: $db is not defined within user_data(). As such, $db->prepare() fails with the error. You need to establish your PDO connection and ensure user_data() has access to $db either by: * *Passing it as an argument (Dependency Injection) *Establishing the connection within user_data() (inefficient) *Or using global (poor design) A: My guess is you have a problem with variable scoping. You should pass the $db variable to the function (preferred), or use global $db declaration to import the variable from the global scope to the function's scope. Your previous function only worked because you were using mysql_query() in a sort of hackish fashion, without specifying the connection for the query. The default behavior in this case is to use the most recently opened mysql resource link globally, so it just happened to work. A: You're not passing in a value for $db for this line: $query = $db->prepare("SELECT $fields FROM `admin` WHERE `id` = :user_id"); $db is the connection resource set up when you connected to the database. You need it in PDO, but you can get away without it with mysql because mysql assumes the last connection you established.
doc_23528191
How to print the contents of (CrystalDecisions) ReportDocument.ExportToStream(Type=PDF) without creating a file? Because we are having issues on access rights of the ASP.NET server printer when executing RptDoc.PrintToPrinter (Users would log in our system using their Active Directory Account, the printer right is granted to these user accounts instead of to NETWORK SERVICE/the IIS/ASP.NET worker process, our system will impersonate these AD user accounts to do the printing) (We also do not prefer caching the generated crystal report as a PDF file and do the print) Thanks a lot! A: You need to call the ExportToHttpResponse method crReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "Exported Report"); The parameters being: * *formatType - the format type to export the report *response - the response object of the page *asAttachment - whether the report will be exported as an attachment *attachmentName - the name of the exported report A: Try to use ReportDocument.PrintToPrinter(1, True, 0, 0) PrintToPrinter(nCopies As Integer, collated As Boolean, startPageN As Integer, endPageN As Integer)
doc_23528192
Thanks! A: Jison docs would be a good place to start. A breakdown of how it's used to build a parser for the CoffeeScript grammar may be helpful in seeing the big picture. References * *npm: An UriTemplate implementation of rfc 6570
doc_23528193
My understanding is that to be able to send a single Push I need an Endpoint ID. My issue is that I can't find a way for my web app to be able to look for an Endpoint ID in the AWS cloud based on, say, user ID. Does anybody thinks there is a way? Thanks! Michal A: If you are trying to target endpoints (devices) based on userId: * *Set the UserId on the Endpoint [1] *Use the Send User Messages API [2] [1]http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/pinpoint/model/EndpointUser.html [2]http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/pinpoint/AmazonPinpointClient.html#sendUsersMessages-com.amazonaws.services.pinpoint.model.SendUsersMessagesRequest-
doc_23528194
import pyodbc cnxn = pyodbc.connect(driver ='{SQL Server}' ,server ='host-MOBL\instance',database ='dbname', trusted_connection = 'yes' ) cursor = cnxn.cursor() cursor.execute("""SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'TableName'""") def checkTableExists(cnxn, TableName): cursor = cnxn.cursor() cursor.execute(""" SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_NAME = '{0}' """.format(TableName.replace('\'', '\'\''))) if cursor.fetchone()[0] == 1: cursor.close() return True cursor.close() return False if checkTableExists == True: print ("already") elif checkTableExists == False: print ("No") But there is nothing happen, can anyone help me on this? I am using Micrsoft SQL Server Management Studio 2014 Express version. The code will be run in Python. Thank you A: Here's a simple example: import pyodbc conn = pyodbc.connect('DRIVER={FreeTDS};SERVER=yourserver.com;PORT=1433;DATABASE=your_db;UID=your_username;PWD=your_password;TDS_Version=7.2;') cursor = conn.cursor() cursor.execute(""" IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'your_table_name') BEGIN SELECT 'Your table exists.' AS result END """) rows = cursor.fetchall() for row in rows: print(row.result) That prints "Table Exists" for me. You should be able to modify it to your needs. A: Use the built-in Cursor.tables method for this check - following code sample assumes connection and cursor are instantiated if cursor.tables(table='TableName', tableType='TABLE').fetchone(): print("exists") else: print("doesn't exist") Note this isn't functionally different from querying INFORMATION_SCHEMA.TABLES, but allows code portability with different database platforms (and IMO improves readability). Using SQL Server Native Client 11.0 and SQL Server 2014, calling Cursor.tables just executes the sp_tables system stored procedure.
doc_23528195
* *Using the bind, I tried to change the font size of the button, and it works well with only one button. However, when two buttons were applied, it worked at first but suddenly program fails with the warning sign: import traceback File "", line 1024, in _find_and_load File "", line 170, in enter File "", line 196, in _get_module_lock RecursionError: maximum recursion depth exceeded Here's my code: from tkinter import * from tkinter import ttk, filedialog import math root = Tk() root.geometry('1280x720+400+200') lotlist_frame =LabelFrame(root,text="Test") lotlist_frame.place(relx=0,rely=0,relwidth=1,relheight=1) btn_lotdelete=Button(lotlist_frame,text="Delete",width=10) btn_lotdelete.place(relx=0.5,rely=0.8,relwidth=0.5,relheight=0.2) btn_query=Button(lotlist_frame,text="Query!",width=10) btn_query.place(relx=0,rely=0.8,relwidth=0.5,relheight=0.2) def resize(e): font_size = int((math.sqrt(pow(e.width,2)+pow(e.height,2)))/10) btn_query.config(font = ("Helvetica", font_size)) btn_lotdelete.config(font = ("Helvetica", font_size)) root.resizable(True,True) root.bind('<Configure>', resize) root.mainloop() ############################################## *I also want to change the font size of the LabelFrame txt, but I don't know how to do it. A: When you apply a binding to the root window, that binding will fire for every widget and not just the root window. In the binding you're computing the size of the font based on the size of the widget, but the widget will sometimes be the root window, and sometimes other windows. And each time you change the font it causes the other widgets to change size, creating a whole new batch of <Configure> events. I think the simple solution is to make sure that your resize only does work if it catches the event on the root window: def resize(e): if e.widget == root: ... your code here ... I also want to change the font size of the LabelFrame txt, but I don't know how to do it. Assuming you mean the tkinter.LabelFrame, you do it the same way as with other widgets: lotlist_frame.configure(font=("Helvetica", font_size)) All of that being said, a better solution is to use a font object. With a font object, you can change the size of the object and all widgets that use that font will automatically update. Here's an example: from tkinter import * from tkinter import ttk, filedialog from tkinter.font import Font import math root = Tk() root.geometry('1280x720+400+200') resizable_font = Font(family="Helvetica") lotlist_frame =LabelFrame(root,text="Test", font=resizable_font) lotlist_frame.place(relx=0,rely=0,relwidth=1,relheight=1) btn_lotdelete=Button(lotlist_frame,text="Delete",width=10, font=resizable_font) btn_lotdelete.place(relx=0.5,rely=0.8,relwidth=0.5,relheight=0.2) btn_query=Button(lotlist_frame,text="Query!",width=10, font=resizable_font) btn_query.place(relx=0,rely=0.8,relwidth=0.5,relheight=0.2) def resize(e): if e.widget == root: font_size = int((math.sqrt(pow(e.width,2)+pow(e.height,2)))/10) resizable_font.configure(size=font_size) root.resizable(True,True) root.bind('<Configure>', resize) root.mainloop() This example correctly changes the font of all of the widget, though the end result isn't very good since you use place, and because your calculation of the new size isn't particularly accurate. However, it illustrates how you can change the font object and all widgets that use that font will automatically see the changes.
doc_23528196
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles/style.css"> <title>Document</title> </head> <body> <div class="container"> <div class="slider"> <div class="slides-container"> <div class="slides slide1"></div> <div class="slides slide2"></div> <div class="slides slide3"></div> <div class="slides slide4"></div> </div> <button class="slider-btn next-btn">next</button> <button class="slider-btn pre-btn">pre</button> </div> </div> <script src="scripts/script.js"></script> </body> </html> * { padding: 0; margin: 0; box-sizing: border-box; text-decoration: none; list-style-type: none; font-family: roboto; } .container { display: flex; justify-content: center; align-items: center; width: 100vw; min-height: 100vh; background-color: #fce9fa; } .slider { padding: 16% 40%; min-width: 800px; min-height: 300px; /* border: 1px solid red; */ position: relative; } .slides-container { position: absolute; left: 0; top: 0; width: 80vw; height: 100%; height: 100%; min-width: 800px; min-height: 300px; border-radius: 25px; box-shadow: 10px 10px 20px -15px black, inset 0px 0px 280px 2px rgb(0, 0, 0); background-color: rgb(255, 255, 255); overflow: hidden; display: flex; justify-content: flex-start; align-items: center; } .slide1 { min-width: 100%; height: 100%; background-image: url(../resource/images/slider/1.jpg); background-repeat: no-repeat; background-size: 100%; background-position: 0px -80px; transition: all 0.2s ease-in; } .slide2 { min-width: 100%; height: 100%; background-image: url(../resource/images/slider/2.jpg); background-repeat: no-repeat; background-size: 100%; background-position: 0px -80px; transition: all 0.2s ease-in; } .slide3 { min-width: 100%; height: 100%; background-image: url(../resource/images/slider/3.jpg); background-repeat: no-repeat; background-size: 100%; background-position: 0px -80px; transition: all 0.2s ease-in; } .slide4 { min-width: 100%; height: 100%; background-image: url(../resource/images/slider/4.jpg); background-repeat: no-repeat; background-size: 100%; background-position: 0px -80px; transition: all 0.2s ease-in; } .slider-btn { position: absolute; top: 92%; width: 50px; padding: 5px; text-transform: uppercase; border: none; border-radius: 5px; background-color: black; color: white; font-weight: bold; cursor: pointer; } .slider-btn:hover { box-shadow: inset 0px 0px 0px 1px pink; } .next-btn { right: 20px; } .pre-btn { left: 20px; } I wrote this code, and I tried to be dynamic * *so I tried to give all slides with querySelectorAll as an array *then I tried to move slides depend on every slide width *and move the slides to the length of the array but my slider move one more than Array length // get elements var slider = document.querySelector(".slider"); var sliderContainer = document.querySelector(".slides-container"); var nextBtn = document.querySelector(".next-btn"); var preBtn = document.querySelector(".pre-btn"); var eachSlide = document.querySelectorAll(".slides"); var x = 0; // commands console.log(slider); console.log(sliderContainer); console.log(eachSlide); nextBtn = nextBtn.addEventListener("click", nextSlide); function nextSlide() { if (x < eachSlide[0].clientWidth * eachSlide.length) { console.log(x); x += eachSlide[0].clientWidth; console.log(x); eachSlide.forEach((element) => { element.style.transform = `translateX(${-x}px)`; element.style.transition = "all 1.5s ease-out"; }); } else if (x == eachSlide[0].clientWidth * eachSlide.length) { x = 0; eachSlide.forEach((element) => { element.style.transform = `translateX(${-x}px)`; }); } }
doc_23528197
Now, I want to automatically test my API via features. So I successfully set up a guard server which starts cucumber and rspec. Does cucumber start my application and provide my API entry point under any port? So that I can use a HTTP client inside my step definitions and point it to http://127.0.0.1:8989/api for example? I know that I can specify a :cucumber_port => 4321 in the Guardfile but my API is not available under this port. A: No, Cucumber doesn't start your application with server. To test it you can do the following: * *Use rack_test. It provides you with methods like #get, #post, etc. It's preferred. For example: get('api/test') response.code.should == '200' * *Start you server with Capybara. It'll be much longer however. You can do this by adding the following code to env.rb: require 'capybara/rails' Capybara::Server.new(Capybara.app).boot Now you can access your API at http://127.0.0.1:9887/api
doc_23528198
However, I want to access the backend database in order to perform SQL queries and see all the tables in my website. I managed to find the .html, .jsp pages which is located at C:\Program Files\Apache Foundation\Tomcat5.5\webapps\root. I also managed to get snippets of the code which might be of help. -- <%@page language="java" import="java.sql.*" %> <%@page import="javax.servlet.*"%> <% String sDBDriver="sun.jdbc.odbc.JdbcOdbcDriver"; String sConnStr="jdbc:odbc:tutoring"; Connection conn=null; ResultSet rs=null; String username="username"; String password="heyicanttelluthepassword"; conn=DriverManager.getConnection(sConnStr,username,password); Statement stmt=conn.createStatement(); %> -- Any idea how the hell I can access the database? I don't even know if it uses MS SQL sever or MYSQL..Haha..
doc_23528199
Is there any way to make sure each task in those n tasks always finishes (callback is called) in case is callback is not called? A: This is a hard question without any specific code because the ways to address this issue are all related to specific code. The best way to fix it would be to go into each specific operation and make sure that the callback is always called (fix the bug that causes it to not be called). Then, you can reliably use the code everywhere without this issue. If you can't go into the code itself, then all you can really do is to set a timer and if the callback hasn't been called in some time period (that you define), then you can call the callback yourself with a timeout error. You could do this by hooking the function so you can intercept the callback to know when it's been called and how to call it with the timeout error. If you can provide actual code for the situation you're trying to fix, then we can provide much more specific code in an answer. A: Assuming these are all asynchronous, I'd try out Bluebird and use Promises. You can use Promise.settle to make sure everything finishes, whether the Promise is fulfilled or not. https://github.com/petkaantonov/bluebird/blob/master/API.md#settle---promise