text
stringlengths
175
47.7k
meta
dict
Q: How does this code for extraction via string methods work? I have read this code for extraction of data from a website through string methods: def extract_results(data) start_index= data.find("<p>") while -1 != start_index: end_index = data.find("</p>", start_index) Here what is while loop doing? Why start_index is being compared with -1? A: The return value of str.find() is -1 if the text is not found: str.find(sub[, start[, end]]) Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. The while loop effectively makes the code go into an endless loop if start_index is not -1 and is useless unless there is more code following the snippet you shared with us. Presumably there is something like return data[start_index + 3:end_index] as a next line, in which case using if start_index > -1: instead of the while statement would have been far more readable. It could be that start_index is set again further down, of course.
{ "pile_set_name": "StackExchange" }
Q: How to check if an attribute has default value defined in __init__ How can I check if an attribute of an object has been set by the user or not? Currently, I have a class class foo: def __init__(self): self.bar = 'baz' Later I would like to check if the user set the value of bar or not, i.e. with something like my_foo = foo() my_foo.bar = 'mybaz' so I would like to know if the second line above has been called or not (to throw a warning if it has not). I have two solutions, but I don't like either of them: Check if my_foo.bar is equal to the default value. But it could be that the user sets my_foo.bar to the same value and then I don't want to throw a warning. Don't set the default value in __init__, but only when it is used. Then it can be checked with getattr() and set with setattr(). I'm sure there is an elegant pythonic way to do it that I haven't thought of. A: Use the @property decorator to construct getters and setters, and the make the setter tell you when a user changes the attribute, example below class Foo: def __init__(self): self._x_was_modified = False self._x = None @property def x(self): return self._x @x.setter def x(self, value): self._x_was_modified = True self._x = value foo = Foo() print('x was modified by user: {}'.format(foo._x_was_modified)) foo.x = 42 print('x was modified by user: {}'.format(foo._x_was_modified)) This will output: x was modified by user: False x was modified by user: True
{ "pile_set_name": "StackExchange" }
Q: Insert text to a web browser and a Java application at the same time I developing a Sinhala-English Unicode converter in java.Now I want to add the final output unicode sinhala word in facebook chat window while i typing them.If i type a word in application that letters also should print on facebook chat(Web browser's active window) window in any browser.I think the problem might be slightly unclear.But I expect any kind of answer for this problem... A: Java has only one tool that allows emulation of user activity: java.awt.Robot. Using this class you can emulate mouse clicks and keyboard usage, so theoretically you can select browser window, then select text area on site and "type" any text you want. The problem with this solution is that current java API does not allow you to identify native window, so it is not easy to find the browser among the windows existing on user's desktop. Finally, exactly as @Jonas said - better use Facebook API.
{ "pile_set_name": "StackExchange" }
Q: Hand recognition script for OpenCV+Python not working I'm trying to get the following script to work. I found it from this website but I keep getting the error : contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ValueError: too many values to unpack (expected 2) I have little experience in Python and OpenCV so if anyone here can help that would be much appreciated! I'm running Mac OS X 10.13.4, OpenCV 3.4.1, Python 3.6.5 and Here is the script I'm trying to get work : import cv2 import numpy as np cap = cv2.VideoCapture(0) while( cap.isOpened() ) : ret,img = cap.read() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) drawing = np.zeros(img.shape,np.uint8) max_area=0 for i in range(len(contours)): cnt=contours[i] area = cv2.contourArea(cnt) if(area>max_area): max_area=area ci=i cnt=contours[ci] hull = cv2.convexHull(cnt) moments = cv2.moments(cnt) if moments['m00']!=0: cx = int(moments['m10']/moments['m00']) # cx = M10/M00 cy = int(moments['m01']/moments['m00']) # cy = M01/M00 centr=(cx,cy) cv2.circle(img,centr,5,[0,0,255],2) cv2.drawContours(drawing,[cnt],0,(0,255,0),2) cv2.drawContours(drawing,[hull],0,(0,0,255),2) cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True) hull = cv2.convexHull(cnt,returnPoints = False) if(1): defects = cv2.convexityDefects(cnt,hull) mind=0 maxd=0 for i in range(defects.shape[0]): s,e,f,d = defects[i,0] start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) dist = cv2.pointPolygonTest(cnt,centr,True) cv2.line(img,start,end,[0,255,0],2) cv2.circle(img,far,5,[0,0,255],-1) print(i) i=0 cv2.imshow('output',drawing) cv2.imshow('input',img) k = cv2.waitKey(10) if k == 27: break Thank you so much in advanced! A: The function cv2.fincContours has changed since OpenCV 3.x , and back in OpenCV 4.x . Try this: ## Find contours if cv2.__version__.startswith("3."): _, contours, _ = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) else: contours, _ = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) Related: How to use `cv2.findContours` in different OpenCV versions?
{ "pile_set_name": "StackExchange" }
Q: Is 4K monitor a good replacement for Retina display? I'm in the middle of reviewing different monitor options to finally buy one for myself. Please do not consider this post as a product placement. I'm not going to promote any particular brand(s), nonetheless I will paste a link to a particular one I found. Basically as a MBP user, I fell in love in Retina display but I won't buy Apple Thunderbolt Display (27-inch) because I find this one as overpriced. I'm looking for something that will be as close as possible to Retina. Are 4K monitors good replacements? I found one from Kogan (Kogan 28" 4K LED Monitor (Ultra HD)). Is it worth considering? Kogan was suggested by my workmate (we both develop software) who ordered one for his daily work. Not exactly this model but quite similar. Can you share your thoughts or some recommendations? A: A 13" Retina MacBook Pro has a screen resolution of 2,560 × 1,600, while the 15" has a 2,880 × 1,800 resolution. 4K is defined as a 4096 x 2160 resolution. So depending on how big the monitor is, a 4K monitor should actually look better from the same viewing distance. As for my personal recommendation, anything but a Samsung.
{ "pile_set_name": "StackExchange" }
Q: jQuery, ajax request doesn't success with JSON on IE I made an AJAX call and it works on FF & Chrome but not on IE 7-8-9. I'm loading a JSON file from my domain: $.ajax({ url: 'js/jquery.desobbcode.json', dataType: 'json', cache: false, success: function(json) { alert('ok'); }, error: function(xhr, errorString, exception) { alert("xhr.status="+xhr.status+" error="+errorString+" exception="+exception); } }); I also tried by adding contentType: 'application/json' but I receive the same output which is : xhr.status=200 error=parsererror exception=SyntaxError Unterminated string constant I checked my JSON file with JSONLint and it's OK. I checked if there is an extra comma and the content is also trimmed. See my JSON file If I put dataType: 'text', I receive the OK alert but a debug popup too. Could you help me? Regards. A: IE is known to have issues with implied content types. ... the new XmlHttpRequest class in Internet Explorer 7 doesn’t implement setRequestHeader very intuitively. Instead of setting the specified header, it appends the value. Try specifying a contentType and check what's coming back from the server: $.ajax({ url: 'js/jquery.desobbcode.json', dataType: 'json', contentType: "application/json; charset=utf-8", ... }); You may also want to try sending blank data: $.ajax({ url: 'js/jquery.desobbcode.json', dataType: 'json', contentType: "application/json; charset=utf-8", data: {} ... });
{ "pile_set_name": "StackExchange" }
Q: Container which iterates a range or a list I have made some composited container Range which accepts either a min/max range as a std::pair or a set of integers as a std::set. internally it saves a copy of the input by as void * This container supports iterators which is useful. I am not sure if there is a better implementation to mimic an iteration for both, a range or a list of numbers, also with respect to move semantics. I could have used boost::variant types, but that only bloats the whole class, and for the iterator I need another boost::variant filled with iterators ...? Have I used the move semantics correctly? I added also some performance test in the MWE: MWE LINK template<typename Type> class Range{ public: typedef std::pair<Type,Type> Pair; typedef std::set<Type> Set; Range(const Pair & pair){ m_ptr = static_cast<void * >( new Pair(pair) ); m_which = 0; } Range(Pair && pair){ m_ptr = static_cast<void * >( new Pair( std::move(pair) ) ); m_which = 0; } Range(const Set & set){ m_which = 1; m_ptr = static_cast<void * >( new Set(set) ); } Range(Set && set){ m_which = 1; m_ptr = static_cast<void * >( new Set( std::move(set) ) ); } Range(const Range & r){ *this = r; } // Move Constructor Range(Range && r){ *this = std::move(r); } // Move Assigment Range & operator=(Range && r){ assert(r.m_ptr); if(m_ptr != r.m_ptr && this != &r ){ // Prevent self-assignment ~Range(); // delete resources m_ptr = std::move(r.m_ptr); m_which = std::move(r.m_which); r.m_ptr = nullptr; r.m_which = 0; } } // Assigment Range & operator=(Range & r){ if(m_ptr != r.m_ptr && this != &r ){ // Prevent self-assignment if(r.m_which == 0){ if(m_which == 0 && m_ptr){ *static_cast<Pair*>(m_ptr) = *static_cast<Pair*>(r.m_ptr); // Copy } m_ptr = static_cast<void * >( new Pair(*static_cast<Pair*>(r.m_ptr))); // Make new and Copy }else if(r.m_which==1){ if(m_which == 1 && m_ptr){ *static_cast<Set*>(m_ptr) = *static_cast<Set*>(r.m_ptr); // Copy } m_ptr = static_cast<void * >( new Set(*static_cast<Set*>(r.m_ptr))); // Make new and Copy } m_which = r.m_which; } } ~Range(){ if(m_ptr){ if(m_which == 0){ auto p = static_cast<Pair * >(m_ptr); delete p; }else if(m_which==1){ auto p = static_cast<Set * >(m_ptr); delete p; } m_which = 0; } } class iterator { public: iterator():m_r(nullptr),m_cur(0){}; iterator(Range * r, bool atEnd = false):m_r(r) { if(!m_r->m_ptr){ m_cur=0; return; } if(m_r->m_which == 0){ auto p = static_cast<Pair * >(m_r->m_ptr); if(atEnd){ m_cur = p->second; }else{ m_cur = p->first; } }else{ auto p = static_cast<Set * >(m_r->m_ptr); if(atEnd){ m_it = p->end(); }else{ m_it = p->begin(); } } }; //Delete assignment operator iterator & operator=(const iterator&) = delete; iterator & operator=(iterator&) = delete; ~iterator() { } iterator( const iterator & it ): m_r(it.m_r), m_cur(it.m_cur) { } /** pre-increment ++it * Allow to iterate over the end of the sequence */ iterator & operator++() { if(m_r->m_which == 0){ ++m_cur; }else { ++m_it; } return *this; } /** post-increment it++ * */ iterator operator++(int) { iterator it(*this); operator++(); return it; } bool operator==(const iterator &rhs) { if(m_r->m_which == 0){ return m_cur == rhs.m_cur; // Two iterators for differente ranges, might compare equal! }else { return m_it == rhs.m_it; } } // Return false if the same! bool operator!=(const iterator &rhs) { return !(*this==rhs); } Type operator*() { if(m_r->m_which == 0){ return m_cur ; }else { return *m_it; } } private: Range * m_r; typename Set::iterator m_it; Type m_cur; }; iterator begin(){ return iterator(this); } iterator end(){ return iterator(this,true); } private: unsigned int m_which = 0; void * m_ptr = nullptr; }; Usage: std::pair<Type,Type> p(0,100); Range<Type> range( std::pair<Type,Type>(0,100) ); for(auto it=range.begin(); it != range.end(); ++it) { std::cout << *it << std::endl; } } Here the updated MWE (from the comments)! =) https://ideone.com/jXI7Si A: You should use template specialization rather than casting to void* here // Pair or set depends on m_which. // Very easy to get that screwed up. // Especially since it is not const. Range(const Pair & pair){ m_ptr = static_cast<void * >( new Pair(pair) ); m_which = 0; } Range(const Set & set){ m_which = 1; m_ptr = static_cast<void * >( new Set(set) ); } Your technique is very error prone as the compiler can no longer validate the types you are using. By using template specialization you remove the problem. This is the wrong way around. Range(const Range & r){ *this = r; } You should define the copy constructor like normal. Then define the assignment operator in terms of the copy constructor. It is known as the copy and swap idiom. Also you don't set up the members. This means unless the assignment operator only sets the values you are looking at undefined behavior when they are read. // As I suspected the first thing you try and do is read from `m_ptr`. // This value has not been set in the copy constructor and thus you have // undefined behavior. Range & operator=(Range & r){ if(m_ptr != r.m_ptr && this != &r ){ This is very hard to understand. Comes from casting around void*. Would not do this. if(m_which == 0 && m_ptr){ *static_cast<Pair*>(m_ptr) = *static_cast<Pair*>(r.m_ptr); // Copy } Now you leak the original data and replace it with the a copy of the source. m_ptr = static_cast<void * >( new Pair(*static_cast<Pair*>(r.m_ptr))); // Make new and Copy } Copy and Swap idiom looks like this: Range(Range const& r) : m_which(r.m_which) , m_ptr(r.m_which == 0 ? static_cast<void*>(new Pair(*static_cast<Pair*>(r.m_ptr))) : static_cast<void*>(new Set(*static_cast<Set*>(r.m_ptr))) ) {} Range& operator=(Range value) // Pass by value to generate copy. { value.swap(*this); // Swap value with the copy. return *this; } // Destructor of `value` cleans up the old value. void swap(Range& other) noexcept { std::swap(m_which, other.m_witch); std::swap(m_ptr, other.m_ptr); } Same problem with the move constructor. // Move Constructor Range(Range && r){ *this = std::move(r); } You don't initialize the members. Since the members are POD they have indeterminate values and thus reading them is undefined behavior (unless you assign something to them). So the move assignment operator has the same problems as the assignment operator as it reads the value of m_ptr (only a problem when called from the move constructor). // Move Assigment Range & operator=(Range && r){ assert(r.m_ptr); // Reading m_ptr here. // But we have just been called from the move constructor // thus m_ptr is not defined. if(m_ptr != r.m_ptr && this != &r ){ You are allowed to call the destructor. ~Range(); // delete resources But this stops the object from being an object. The only thing you are allowed to do at this point is call the call placement new to make it a real object again (or pass it around as void*). So calling the destructor is not really a good idea. Move the code for releasing resource into another function and call that from here and the destructor. OK. So after a move the source should be in a valid state (but can be indeterminate state). r.m_ptr = nullptr; r.m_which = 0; I suppose this does that. But a lot of code assumes that m_which of 0 means that it contains a pointer to a pair. You may want to have another state ie 2 (or -1) that indicates nothing is stored in the object. Personally I would simplify the above: Range(Range && r) : m_which(r.m_wich) , m_ptr(r.m_ptr) { // r.m_which = ?? not sure you may want to set this. r.m_ptr = nullptr; } Range& operator=(Range&& r) { r.swap(*this); // Just swap the objects on assignment. return *this; }
{ "pile_set_name": "StackExchange" }
Q: Object rotation using keys I want to rotate a cube using keys. This is a part of the code. When I press LEFT key, cube rotates to left, etc. My goal is to rotate cube all around, so I have to rotate it by x and y axis which causes a problem. I have defined mat4 rotation; and used it to assign a rotation when I press and hold a key. When I hold the key, it is rotating, for example to left. Then I release the key and the object gets back to initial position (camera gets back to initial position, since object is not moving). I think this problem is causing the auto rotateMat = rotation; line which is defined below the key functions. What am I doing wrong? mat4 rotation; //global if(keysPressed[GLFW_KEY_LEFT]){ timer -= delta; rotation = rotate(mat4{}, timer * 0.5f, {0, 1, 0}); } if(keysPressed[GLFW_KEY_RIGHT]){ timer += delta; rotation = rotate(mat4{}, timer * 0.5f, {0, 1, 0}); } if(keysPressed[GLFW_KEY_UP]){ timer += delta; rotation = rotate(mat4{}, timer * 0.5f, {1, 0, 0}); } if(keysPressed[GLFW_KEY_DOWN]){ timer -= delta; rotation = rotate(mat4{}, timer * 0.5f, {1, 0, 0}); } ... program.setUniform("ModelMatrix", rotation* cubeMat); cube.render(); UPDATE: So the problem to this was solved when I used matrix variable as global variable, not local. A: There are multiple ways how such an interaction can be implemented. One of the easier ones is to create a relative translation in every frame instead of a global one and add it to the current rotation: For this, one has to store the sum of all rotations in a global varialbe //Global variable mat4 total_rotate; And calculate the relative translation in every frame: //In the function mat4 rotation; if(keysPressed[GLFW_KEY_LEFT]){ rotation = rotate(mat4{}, delta, {0, 1, 0}); } if(keysPressed[GLFW_KEY_RIGHT]){ rotation = rotate(mat4{}, -delta, {0, 1, 0}); } if(keysPressed[GLFW_KEY_UP]){ rotation = rotate(mat4{}, delta, {1, 0, 0}); } if(keysPressed[GLFW_KEY_DOWN]){ rotation = rotate(mat4{}, -delta, {1, 0, 0}); } total_rotate = total_rotate * rotation; ... program.setUniform("ModelMatrix", total_rotate * cubeMat); cube.render(); As an alternative, you could store the two rotation angles instead and calculate the matrix in every frame: //Global variables float rot_x = 0.0f, rot_y = 0.0f; //In every frame if(keysPressed[GLFW_KEY_LEFT]){ rot_x += delta; } if(keysPressed[GLFW_KEY_RIGHT]){ rot_x -= delta; } //Same for y auto rotation = rotate(rotate(mat4{}, rot_y, {0, 1, 0}), rot_x, {1, 0, 0} ... program.setUniform("ModelMatrix", rotation * cubeMat); cube.render();
{ "pile_set_name": "StackExchange" }
Q: How do phone chargers have variable input voltage with constant output voltage? My basic understanding is that a transformer can step down a voltage by the ratio of the primary and secondary windings, since this is a ratio the output is not constant. Thus my question is, how are chargers like the apple phone charger (a Fly-back Switch mode power supply) able to take an input of 100v-240v ~ 50/60 Hz to create a constant 5v output? Above is a supposed circuit diagram of the apple phone charger. is this constant output voltage an effect of the flyback transformer? (i have little experience in AC to DC power supplies) Any help is appreciated. A: Modern AC-DC power supplies do the voltage conversion in three steps. Roughly speaking, the process is as follows. First, they rectify the AC into DC, so 100 V AC gets into about 140 V DC, and 240 V AC results in about 340 V DC. This is a first step. This is the range of voltages that the second stage of converter is dealing with. And this voltage has horrible ripples at 100-120 Hz. The second stage is a "chopper" that modulates the high-voltage DC into high-frequency pulses, 100 kHz or something. There is a controller IC that drives a pair of powerful MOSFETs, which are loaded with primary winding of the isolation transformer. The transformer, as you duly noted, has a fixed winding ratio, so the output pulses would have the variable amplitude proportional to the input DC (which is 140 to 340V, not counting ripples from 50/60 Hz primary rectification). However, the chopper also makes these pulses of different width, which is called PWM - Pulse-Width-Modulation. Thus the output of the transformer, when rectified by "half-way" diode rectifier and smoothened with a large output capacitor, on average can have variable amplitude: narrow pulses make lower average amplitude, and vice versa. This is the third stage of AC-DC converter. So, while the transformer has a fixed winding ratio, the PWM still allows to change the output of rectifier in considerable range, thus accommodating the fixed transformer ratio and vast input voltage range, including voltage ripples. The final control and voltage stabilization is done via negative feedback mechanism using linear opto-isolators. If the rectified voltage goes too high, the feedback makes the controller IC to produce narrower pulses, so the voltage goes down, and vice versa. This feedback mechanism not only takes care of the voltage, it also controls the overall power delivered into PSU load. There are some fine details how the transformers tolerate the asymmetic waveforms, there are some fine engineering tricks behind the scenes, but basically that's it. A: If you want to identify one 'component' that's responsible for the constant output voltage, then it's the 'feedback'. The forward path which includes the flyback transformer pushes a controllable amount of power to the output. The voltage on the output is measured, and the feedback requests a smaller or larger amount of power moment by moment, to keep the voltage constant. The forward path is designed to be able to run from any voltage in the input range, which needs a bit of care with design, but is fairly straightforward. The way a flyback converter works is that its output voltage adjusts to whatever voltage is needed to deliver the power it's been asked to deliver. It can step up or down by a large ratio, to allow it to match the input and output voltage ratio. A: The phone charger has to do several things in addition to regulating the voltage. It has to convert AC to DC, step down the voltage substantially and provide substantial isolation between input and output. Since we're only concerned with regulation lets instead consider a DC-DC "in car" charger, that accepts DC over a typically wide voltage range possibly up to 28V, and converts it to 5V. The charger probably uses a fast switching transistor and diode to rapidly switch between the input voltage and ground, then an LC filter to smooth out the switching and output the average voltage. The resulting transfer function is Vout=D*Vin, where D is a PWM duty cycle. For reasonable input voltages there will be a "D" value that yields 5v. In its simplest form D is set by a controlling "error amplifier" comparing Vout with a reference voltage. In more refined versions the PWM circuit is modified to cancel out the influence of Vin, two examples of this are "feedforward" and "current mode". In current mode the PWM pulse ends when the current in the inductor reaches a value. If the input voltage is higher the value is reached sooner but the output is relatively unaffected. If this DC-DC design is "upgraded" to include a transformer then it gives the popular "forward" configuration which can be more compact and efficient than flyback as the transformer can use magnetic parts optimized for transformer use (ferrite), and the inductor can use parts for inductor use (iron powder).
{ "pile_set_name": "StackExchange" }
Q: Name a dictionary from a variable value How can I give a dictionary a name from a variable value? An example of what I'm trying to build: apache['name'] = "Apache Web Server" apache['category'] = "web" apache['version'] = "2.2.14-4" However I don't know the dictionary's name in advance, that arrives as variable, e.g. dname = 'apache'. Dname is parsed from a text file. The logic is: "First word after delimiter is dict_name; next n lines are split into key:value pairs for dict_name; skip to next delimiter; repeat until end". What doesn't work: key = 'category' value = 'web' dname[key] = value TypeError: 'str' object does not support item assignment eval(dname)[key] = value NameError: name 'apache' is not defined getattr(dname, '__contains__')[key] = value and similar attempts with keywords from dir(dname) spawn only errors. (Because getattr is only for functions and modules?) From How to create a dictionary based on variable value in Python I'm introduced to vars(), but it wants the dictionary to exist already? vars(dname)[key] = value TypeError: vars() argument must have __dict__ attribute This question's title is the closest sounding I've found to what I'm after, but the answers are about using variables for keys, not the dict name: Create a dictionary with name of variable A: From the discussion in the comments, it is clear that you're trying to create a variable whose name is contained in another variable. The following shows how this can be done: d = {} d["name"] = "Apache Web Server" d["category"] = "web" d["version"] = "2.2.14-4" locals()["apache"] = d print apache This creates a local variable, but also take a look at globals().
{ "pile_set_name": "StackExchange" }
Q: Parse Boolean C# Culture verdadero I am trying to run this exact line, and it isn't working. Anyone know the reason why? Convert.ToBoolean("verdadero", new System.Globalization.CultureInfo("ES-MX")); I am parsing this from an xml file generated by a program that has many languages installed, and so it will use "true" in "EN-US" culture or "verdadero" in "ES-MX". A: Interesting. Running Convert.ToBoolean through a decompiler emits this: /// <summary> /// Converts the specified string representation of a logical value to its Boolean equivalent, using the specified culture-specific formatting information. /// </summary> /// /// <returns> /// true if <paramref name="value"/> equals <see cref="F:System.Boolean.TrueString"/>, or false if <paramref name="value"/> equals <see cref="F:System.Boolean.FalseString"/> or null. /// </returns> /// <param name="value">A string that contains the value of either <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. </param><param name="provider">An object that supplies culture-specific formatting information. This parameter is ignored.</param><exception cref="T:System.FormatException"><paramref name="value"/> is not equal to <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. </exception><filterpriority>1</filterpriority> [__DynamicallyInvokable] public static bool ToBoolean(string value, IFormatProvider provider) { if (value == null) return false; else return bool.Parse(value); } This makes it look like the IFormatProvider is completely disregarded. I'm tempted to say it's a bug in the framework, but experience has taught me that I'm usually missing something when I come to that conclusion...
{ "pile_set_name": "StackExchange" }
Q: Can the wp_posts table have the same slug (post_name) in multiple statuses (post_status)? I'm using function get_posts to retrieve a set of post objects that are my custom post type (CPT). I am counting on being able to programmatically flip these posts between status "publish", "pending" and "draft". Before I go through the trouble of detecting and "fixing" potential duplicates -- is it even something I have to worry about? Is there any scenario where the same CPT post_name can reside in the wp_posts table in more than one (row) of differing post_status: publish, pending or draft? (edit) After some experimentation I found that when inserting a post of status "pending", it ignores the post_name parameter - so that ends up being blank in the database. And yes, it will allow many rows in the wp_posts table with the same post_name of '' (blank). I'm sure there's a good reason for this but it is not what I expected that's for sure. A: No, multiple posts with the same CPT and post name (slug) are not possible. Someone can work hard and ruin the DB by writing into it some illegal values, but that should not be something you think of when writing your code. Posts in their initial state are not true posts, they are just place holders, therefor while your observation is valid, it is not really relevant for usual usage pattern of wordpress API, unless once again your aim is to break things.
{ "pile_set_name": "StackExchange" }
Q: HP laptop not charging over 86%, dies at 50% without warning I'm running Windows 10 on an HP laptop. I always have to keep it charging because it doesn't charge past 86%, and it turns off itself at around 50% without any warning. Is this a problem with the battery or power settings? A: Seems like you need to run the Battery Test and Calibration. Check out - https://support.hp.com/us-en/document/c00821536 Should correct the issue, or at least tell you if your battery is toast.
{ "pile_set_name": "StackExchange" }
Q: Listings custom font size in beamer I have a beamer frame like this: \documentclass{beamer} \usepackage{listings} \begin{document} \begin{frame}[fragile] \begin{lstlisting}[basicstyle=\tiny] Long code { ... } \end{lstlisting} \end{frame} \end{document} What I need is even smaller font than \tiny - is that somehow possible? I've also tried this: \documentclass{beamer} \usepackage{listings} \begin{document} \begin{frame}[fragile] \fontsize{2pt}{0.5pt} \selectfont \begin{lstlisting} Long code { ... } \end{lstlisting} \end{frame} \end{document} Which doesn't look good since some symbols - e.g. '{', '}', '<', '>' are larger. A: As you can tell from the warnings your MWE causes, some symbols are not available in 2pt font size and are substituted with symbols in 5pt. I'm not really sure what the purpose of such a small font is, but as a workaround you could use the smallest available font which contains your symbols (5pt) but make the slides larger to get the same ratio between frame size and font. The following example uses frame twice the normal size: \documentclass{beamer} \usepackage{listings} \makeatletter \setlength\beamer@paperwidth{25.60cm} \setlength\beamer@paperheight{19.20cm} \geometry{% papersize={\beamer@paperwidth,\beamer@paperheight}, hmargin=2cm,% vmargin=0cm,% head=1cm,% might be changed later headsep=0pt,% foot=1cm% might be changed later } \makeatother \AtBeginDocument{\fontsize{22pt}{24pt}\selectfont} \begin{document} \begin{frame}[fragile] normal text \fontsize{5pt}{7pt} \selectfont \begin{lstlisting} Long code { ... } \end{lstlisting} \end{frame} \end{document} Another approach would be to look for a font that contains all your symbols in 2pt
{ "pile_set_name": "StackExchange" }
Q: How to properly call a single server from multiple actors / web handlers using Akka HTTP? I have a service (let's call it Service A) which uses Akka Server HTTP to handle incoming requests. Also I have 3rd party application (Service B) which provides several web services. The purpose of service A is to transform client requests, call one or multiple web services of service B, merge/transform results and serve it back to a client. I am using Actors for some parts, and just Future for other. To make a call to Service B, I use Akka HTTP client. Http.get(actorSystem).singleRequest(HttpRequest.create() .withUri("http://127.0.0.1:8082/test"), materializer) .onComplete(...) The issue is, a new flow is created per each Service A request, and if there are multiple concurrent connections, it results in akka.stream.OverflowStrategy$Fail$BufferOverflowException: Exceeded configured max-open-requests value of [32] error I already asked this question and got a suggestion to use a single Flow How to properly call Akka HTTP client for multiple (10k - 100k) requests? While it works for a batch of requests coming from a single place, I don't know how to use a single Flow from all my concurrent request handlers. What is the correct "Akka-way" to do it? A: I think you could use Source.queue to buffer your requests. The code below assume that you need to get the answer from 3rd party service, so having a Future[HttpResponse] is very welcomed. This way you could also provide an overflow strategy to prevent resource starvation. import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.{HttpRequest, HttpResponse} import akka.stream.scaladsl.{Keep, Sink, Source} import akka.stream.{ActorMaterializer, OverflowStrategy} import scala.concurrent.duration._ import scala.concurrent.{Await, Future, Promise} import scala.util.{Failure, Success} import scala.concurrent.ExecutionContext.Implicits.global implicit val system = ActorSystem("main") implicit val materializer = ActorMaterializer() val pool = Http().cachedHostConnectionPool[Promise[HttpResponse]](host = "google.com", port = 80) val queue = Source.queue[(HttpRequest, Promise[HttpResponse])](10, OverflowStrategy.dropNew) .via(pool) .toMat(Sink.foreach({ case ((Success(resp), p)) => p.success(resp) case ((Failure(e), p)) => p.failure(e) }))(Keep.left) .run val promise = Promise[HttpResponse] val request = HttpRequest(uri = "/") -> promise val response = queue.offer(request).flatMap(buffered => { if (buffered) promise.future else Future.failed(new RuntimeException()) }) Await.ready(response, 3 seconds) (code copied from my blog post) A: Here is Java version of the accepted answer final Flow< Pair<HttpRequest, Promise<HttpResponse>>, Pair<Try<HttpResponse>, Promise<HttpResponse>>, NotUsed> flow = Http.get(actorSystem).superPool(materializer); final SourceQueue<Pair<HttpRequest, Promise<HttpResponse>>> queue = Source.<Pair<HttpRequest, Promise<HttpResponse>>> queue(BUFFER_SIZE, OverflowStrategy.dropNew()) .via(flow) .toMat(Sink.foreach(p -> p.second().complete(p.first())), Keep.left()) .run(materializer); ... public CompletionStage<HttpResponse> request(HttpRequest request) { log.debug("Making request {}", request); Promise<HttpResponse> promise = Futures.promise(); return queue.offer(Pair.create(request, promise)) .thenCompose(buffered -> { if (buffered instanceof QueueOfferResult.Enqueued$) { return FutureConverters.toJava(promise.future()) .thenApply(resp -> { if (log.isDebugEnabled()) { log.debug("Got response {} {}", resp.status(), resp.getHeaders()); } return resp; }); } else { log.error("Could not buffer request {}", request); return CompletableFuture.completedFuture(HttpResponse.create().withStatus(StatusCodes.SERVICE_UNAVAILABLE)); } }); }
{ "pile_set_name": "StackExchange" }
Q: Getting 'Coikoe' in http request instead of 'Cookie' Our website is receiving http requests from a user which contains 'Coikoe' tag instead of 'Cookie'. Http request object received from firefox is mentioned below : com.pratilipi.servlet.UxModeFilter doFilter: REQUEST : GET http://www.pratilipi.com/books/gujarati HTTP/1.1 Host: http//www.pratilipi.com User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Referer: http://www.pratilipi.com/?action=login Coikoe: _gat=1; visit_count=1; page_count=2 X-AppEngine-Country: XX X-AppEngine-Region: xx X-AppEngine-City: XXXXXX X-AppEngine-CityLatLong: 12.232344,12.232445 Http request object received from google chrome is mentioned below : com.pratilipi.servlet.UxModeFilter doFilter: REQUEST : GET http//www.pratilipi.com/books/hindi HTTP/1.1 Host: http//www.pratilipi.com Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36 Referer: http//www.pratilipi.com Accept-Language: en-US,en;q=0.8,ta;q=0.6 Coikoe: _gat=1; visit_count=1; page_count=1 X-AppEngine-Country: XX X-AppEngine-Region: xx X-AppEngine-City: xxxxxx X-AppEngine-CityLatLong: 12.232344,12.232445 User is using window 8 system. Question : Why is this happening and how can I solve it? I have never seen anything like this before. Anyone has come accross anything like this Thank You A: This user will be using some sort of privacy proxy. The same happens for the Connection request header as explained in Cneonction and nnCoection HTTP headers: the proxy mangles the header so it won't be recognized by the receiver, but by merely shuffling some letters around the TCP packet's checksum will remain the same.
{ "pile_set_name": "StackExchange" }
Q: How to get physical memory and cpu used by particular process in windows? Hi this is my code that prints the physical memory used by some process displayed in bytes , when i am converting bytes into kb by google converter. The value shown in task manager for memory usage is less than output given by my code. Also i want to know the Cpu used by the same process ? I found this question on Stack overflow,CPU USAGE that provides guidance in knowing cpu usage,but i want to know CPU usage for some Particular process id ,instead of current process as mentioned in my code, Can i achieve the same with the code provided. Any guidance would be appreciated. int main( void ) { HANDLE hProcess; PROCESS_MEMORY_COUNTERS pmc; DWORD processID = 4696; // Print information about the memory usage of the process. hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID ); if (NULL == hProcess) return 1; if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) { printf( "\tWorkingSetSize: %u\n", pmc.WorkingSetSize ); } CloseHandle( hProcess ); return 0; } A: CPU From the answer linked, you want to use your 'hProcess' handle instead of the 'self' handle from the sample. Turn this: self = GetCurrentProcess(); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); ... Into this: GetProcessTimes(hProcess, &ftime, &ftime, &fsys, &fuser); ... Memory The Working Set is comprised of Private (heap, stack, etc) + Shared (typically dll/exe code pages). What specific column in Task Manager (and what OS) are you referencing?
{ "pile_set_name": "StackExchange" }
Q: Android TranslateAnimation - Moving an image from the right side of the screen into the screen I am desperate right now and I really really need some help. I want an image to move in from the right of the screen into it. Initially, the image exists outside the screen area. However, based on an event, I want it to slide in. Does anyone know how this can be done? I read in a tutorial(http://developerlife.com/tutorials/?p=343) online that if "the animation effects extend beyond the screen region then they are clipped outside those boundaries". Hence, according to this tutorial, this is not possible. However, remember the android 2.2 lock screens? The two images (for unlocking and putting it on silence) used to slide in from left and right side of the screen respectively. I can make my image slide in from the left side of the screen but not from the right. Any ideas on how I can get this done??? If you want to see my code, I can put it up. A: This is actually pretty simple. In your layout, position the ImageView to where you want it at the end of the animation and either set its visibility to INVISIBLE or GONE, depending on your layout needs. Then when the event occurs, start a TranslateAnimation with starting coordinates set using RELATIVE_TO_PARENT with the x of 1.0 (all the way to the right) and the destination x coordinates of 0.0 with type RELATIVE_TO_SELF so that your image end up in the position determined by the layout. Make sure to also turn on the visibility as you start the animation. PS. It's important that whatever ViewGroup your ImageView is nested under extends all the way to the right of the screen. Otherwise the ImageView will be clipped against its parent's bounds.
{ "pile_set_name": "StackExchange" }
Q: MySQL - ODBC connect fails, Workbench connect works I am trying to install and test a MySQL ODBC Connector on my machine (Windows 7) to connect to a remote MySQL DB server, but, when I configure and test the connection, I keep getting the following error: Connection Failed [MySQL][ODBC 5.3(w) Driver]Access denied for user 'root'@'(my host)' (using password: YES): The problem is, I can connect with MySQL Workbench (remotely - from my local machine to the remote server) just fine. I have read this FAQ extensively but it's not helping out. I have tried: Checking if mysql is running on the server (it is. I even tried restarting it many times); Checking if the port is listening for connection on the remote server. It is. Connecting to the remote server using MySQL Workbench. It works. Checking if the IP address and Ports of the remote database are correct; Checking if the user (root) and password are correct; Re-entering the password on the ODBC config window; Checking and modifying the contents of the "my.conf" on the remote server to allow connections from all sides (0.0.0.0); Including (my host) on the GRANT HOST tables from mySQL (I also tried the wildcard '%' but it's the same as nothing); Running a FLUSH HOSTS; And FLUSH PRIVILEGES; command on the remote mySQL server to reset the privilege cache; Turning off my Firewall during the configuration of the ODBC driver; Checked if the MySQL variable 'skip_networking' is OFF in order to allow remote connections. What is frustrating is that I can connect with MySQL Workbench on my local machine (with the same IP/user/password), just not with ODBC. What could I be doing wrong, or what could be messing up my attempt to connect with ODBC? Update: I managed to set up the ODBC driver and get it running correctly on the server side. I can connect there to the localhost using a command line (with the "isql" command). But I still can't connect over remotely with my Windows 7 machine. A: Solved. As it turns out, it was a permissions problem. I ran the following command on the remote server SQL: GRANT ALL PRIVILEGES ON *.* TO 'root'@'(my_host)' IDENTIFIED BY '(my_password)'; I had run the previous command, but without the "IDENTIFIED BY" password. Then, to reset the mysql permissions cache, I also ran FLUSH PRIVILEGES; And now it works.
{ "pile_set_name": "StackExchange" }
Q: nodejs mongodb driver native query issue It turns a funny error in Node.js mongodb, if I put the form below: locals.collection.find(filter, req.query); returns me the following error: MongoError: query selector must be an object Now if I manually put the query works. I'm having this problem a long time, and I've tried several ways. locals.collection.find({slug:'somak'}, req.query); I am using the following function: exports.findAll = function(req, res, next) { var locals = {}, section = req.params.section, query = req.query, filter = {}; if(query.filter) { filter = query.filter.replace(/"(\w+)"\s*:/g, '$1:'); filter = filter.replace(/["]/g, "'"); } console.log(filter); delete query.filter; async.series([ function(callback) { MongoClient.connect(url, function(err, db) { if (err) return callback(err); locals.collection = db.collection(section); callback(); }); }, function(callback) { locals.collection.count(filter, function (err, result){ if (err) return callback(err); locals.count = result; callback(); }); }, function(callback) { var cursor = locals.collection.find({slug:'somak'}, req.query); if(req.query.page) { cursor = cursor.skip(Math.abs(req.query.limit) * --req.query.page); } cursor.toArray(function(err, docs) { if (err) return callback(err); locals.docs = docs; callback(); }); } ], function(err) { //This function gets called after the three tasks have called their "task callbacks" if (err) return next(err); // Here locals will be populated with 'count' and 'docs' res.json({ count: locals.count, data: locals.docs }); }); A: Just use JSON.parse: exports.findAll = function(req, res, next) { var locals = {}, section = req.params.section, query = req.query, filter = {}; if(query.filter) { filter = JSON.parse(query.filter); } delete query.filter; ...
{ "pile_set_name": "StackExchange" }
Q: How to use variable between functions I'm having a problem of using variables between functions. As you can see down below User.username is available and good at the sign up page, but when you go to the login page I told it to first alert the value of User.username, and it alerts undefined? I'm confused here. I'm pretty sure I'm missing a concept here. Anyways Thank you so much!: Here is a plunkr: http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH Here is my script.js: app.controller("AuthCtrl", ["$scope", "Auth","$rootScope", function($scope, Auth, $rootScope) { var User = {} $scope.createUser = function(username, email, password) { $rootScope.usernames = username User.username = username $scope.message = null; $scope.error = null; var ref2 = new Firebase("https://uniquecoders.firebaseio.com/"); ref2.createUser({ email: $scope.email, password: $scope.password }, function(error, userData) { if (error) { switch (error.code) { case "EMAIL_TAKEN": alert("The new user account cannot be created because the email is already in use. Try to login"); break; case "INVALID_EMAIL": alert("The specified email is not a valid email."); break; case "INVALID_PASSWORD": alert("The Specified Passowrd Is not valid.") break; default: alert("Error creating user:", error); } } else { alert("Successfully created user account with username" + User.username); window.location.hash = "/User" } }); }; $scope.logIn = function(){ alert(User.username) $rootScope.usernames = User.username $scope.message = null; $scope.error = null; var ref2 = new Firebase("https://uniquecoders.firebaseio.com/"); ref2.authWithPassword({ "email" : $scope.logInemail, "password" : $scope.logInemailpassword }, function(error, userData){ if(error){ alert("Login Failed Because : " + error) } else{ alert("Logged In!") window.location.hash = "/User" } }) } /* $scope.removeUser = function() { $scope.message = null; $scope.error = null; Auth.$removeUser({ email: $scope.email, password: $scope.password }).then(function() { $scope.message = "User removed"; }).catch(function(error) { $scope.error = error; }); };*/ } ]); A: When page reloads the entire javascript is re executed. So user object populated in registration process is no longer available in login function because page has reloaded on clicking on signup button. So we need to store the user name in cookie so that we can access it any time. Even when its removed from javascript runtime it will be there in the browser cache. Its risky to store passwords in cookies for security issues. On successful registration save the username in cookie. Some thing like this document.cookie ="username =" +username + "; " +"email ="+ email; In login function get cookie values and check if email of user is same as entered function getCookie(name ) { var pairs = document.cookie.split("; "), count = pairs.length, parts; while ( count-- ) { parts = pairs[count].split("="); if ( parts[0] === name ) return parts[1]; } return false; } var username=getCookie("username"); var email=getCookie("username"); if($scope.logInemail ==email) { alert(username); }
{ "pile_set_name": "StackExchange" }
Q: Creating a class in Angular How to create a class in angularjs with a constructor, getter, setter, variables and methods? Here is example of what I want to make in angulajs class Abc { int a; string str ="Hello world"; public Abc(){ } public show(){ return str; } public setStr(string str){ this.str = str; } public getStr(){ return this.str; } } I don't want to use any type script. Just want to know how to make a class in angularjs with the following abilities. A: That is not the way JS or angular work. Update Since what you are trying to do is to be able to create new instances, you should probably create this in a service, and then in the controller you can inject your service. For example: angular.module('app', function(){ }); angular.module('app').factory('Abc', function(){ return { a: 0, str: "Hello world", show: function() { return str; }, setStr: function(str) { this.str = str; }, getStr: function() { return str; } } }); angular.module('app').controller('myController', function(Abc) { $scope.newClass = new Abc; }); Old answer. Instead you create objects which have there own properties, usually inside the $scope of your controller. An equivalent angular code to your code would be: angular.module('app', function(){ }); angular.module('app').controller('Abc', function(){ $scope.a; var str = "Hello world"; $scope.show = function() { return str; }; $scope.setStr = function(str) { str = str; }; $scope.getStr = function() { return str; }; });
{ "pile_set_name": "StackExchange" }
Q: What article would be correct here? A belief that / The belief that Can I change the definite article in the following sentence and remain grammatical? Once you adopt the belief that there's nothing you can do to change something, you start to take a pernicious poison into your system. I might mean that of all the beliefs someone might adopt you adopt one of them. On this assumption, I might say ''There's a belief that there's nothing you can do etc.'' On the other hand, there might be only one belief that there's nothing you can do: the belief. If I can, what's the principle by which a native speaker chooses between the two? Thanks! A: Once you adopt the belief that there's nothing you can... ... is absolutely correct because you are specific about that belief. And, that is why it'd take the. Again, you are right! Now, you are introducing that belief and that's why you can put an indefinite article. It's the same as you say - there's a place called Times Square. There is the belief somehow does not look idiomatic, at least to me.
{ "pile_set_name": "StackExchange" }
Q: How does this javascript object array work? I am trying to understand something very basic. If I have an object like this: var topics = {} And I do this: topics[name] = ["chapter 1", "chapter 2", "chapter 3"]; When I log this object, I don't see the name attribute. What have I done exactly? Have I created a key called name with the value of an array? Of course I know I can do that by just doing topics.name = ["chapter 1", "chapter 2", "chapter 3"]; But then what is this doing? topics[name] = ["chapter 1", "chapter 2", "chapter 3"]; Could someone please clarify? A: Your are creating a property on the object with a name based on the value of the name variable. If you want to create a property called name in that way you need to do: topics["name"] = ["chapter 1", "chapter 2", "chapter 3"]; A: When you use the [] notation it expects an expression in between, that translates to a string. Using name not enclosed in quotes 'name' it assumes you are using a variable called name. Which in your case is undefined. The correct usage would be topics["name"] = ["chapter 1", "chapter 2", "chapter 3"]; If you want to use a variable you can do things like var prop = 'name'; var topics = {}; topics[prop] = ["chapter 1", "chapter 2", "chapter 3"]; this will create the name property on the object.. useful for dynamic/automatic creation/filling of objects.. A: That should generate an error, unless you have variable name defined as a string or a number. These three are equivalent: var name = "key"; topics[name] = "value"; topics["key"] = "value"; topics.key = "value";
{ "pile_set_name": "StackExchange" }
Q: Deadlock in a simple PL/pgsql stored procedure that updates a single row (called by Hibernate) I wrote a simple stored procedure: CREATE OR REPLACE FUNCTION "public"."update_table01" ( int4, -- $1 (population) int2 -- $2 (id) ) RETURNS "pg_catalog"."void" AS $body$ BEGIN UPDATE "table01" SET population = $1 WHERE id = $2; END; $body$ LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER COST 100; I am calling this within my Java server (jre7), and I'm using Hibernate 4 with C3P0 as my connection pool. This is being executed on PostgreSQL 9.2.4. I have a Hibernate entity corresponding to table01 (mapped by annotations), and I specified this procedure to be used as SQL update: @SQLUpdate(sql = "{call update_table01(?, ?)}", callable = true) When I did a load test with multiple threads (around 20-30) that were frequently calling this, a few deadlocks occurred, much to my surprise. Here is the relevant part of the log: 2013-08-14 14:51:19 CEST [23495]: [3-1] LOG: process 23495 detected deadlock while waiting for ShareLock on transaction 140127434 after 1000.048 ms 2013-08-14 14:51:19 CEST [23495]: [4-1] STATEMENT: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23495]: [5-1] ERROR: deadlock detected 2013-08-14 14:51:19 CEST [23495]: [6-1] DETAIL: Process 23495 waits for ShareLock on transaction 140127434; blocked by process 23481. Process 23481 waits for ShareLock on transaction 140127431; blocked by process 23495. Process 23495: update table01 set population=$1 where id=$2 Process 23481: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23495]: [7-1] HINT: See server log for query details. 2013-08-14 14:51:19 CEST [23495]: [8-1] STATEMENT: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23481]: [3-1] LOG: process 23481 still waiting for ShareLock on transaction 140127431 after 1000.086 ms 2013-08-14 14:51:19 CEST [23481]: [4-1] STATEMENT: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23481]: [5-1] LOG: process 23481 acquired ShareLock on transaction 140127431 after 1000.227 ms 2013-08-14 14:51:19 CEST [23481]: [6-1] STATEMENT: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23938]: [3-1] LOG: process 23938 still waiting for ExclusiveLock on tuple (8,72) of relation 16890 of database 16751 after 1000.119 ms 2013-08-14 14:51:19 CEST [23938]: [4-1] STATEMENT: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23938]: [5-1] LOG: process 23938 acquired ExclusiveLock on tuple (8,72) of relation 16890 of database 16751 after 1000.174 ms 2013-08-14 14:51:19 CEST [23938]: [6-1] STATEMENT: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23520]: [3-1] LOG: duration: 970.319 ms execute <unnamed>: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23520]: [4-1] DETAIL: parameters: $1 = '5731', $2 = '294' 2013-08-14 14:51:19 CEST [23481]: [7-1] LOG: duration: 1000.361 ms execute <unnamed>: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23481]: [8-1] DETAIL: parameters: $1 = '1586', $2 = '253' 2013-08-14 14:51:19 CEST [23524]: [3-1] LOG: duration: 531.909 ms execute <unnamed>: update table01 set population=$1 where id=$2 2013-08-14 14:51:19 CEST [23524]: [4-1] DETAIL: parameters: $1 = '1546', $2 = '248' 2013-08-14 14:51:19 CEST [23938]: [7-1] LOG: duration: 1004.863 ms execute <unnamed>: update table01 set population=$1 where id=$2 I am bad at interpreting Postgres logs, so correct me if I am wrong. I think this says that two processes ended up in a deadlock. Both were executing the same statement. A lot of stuff puzzles me her. The most important is: I do not understand how could two processes (that even update different rows) end up in a deadlock, when only a single row-level lock for a row that has that specific ID is obtained in the stored procedure? This is the only procedure that changes this table. Isn't it supposed to obtain an exclusive lock (the same when executing SELECT ... FOR UPDATE)? Where do ShareLocks come from? What is that process that show in later lines (23938)? My best guess is that 23938 was also waiting for the lock, and when 23495 was killed, it acquired the lock. Then I tried the following: CREATE OR REPLACE FUNCTION "public"."update_table01" ( int4, -- $1 (population) int2 -- $2 (id) ) RETURNS "pg_catalog"."void" AS $body$ BEGIN PERFORM 1 FROM "table01" WHERE id = $2 FOR UPDATE; UPDATE "table01" SET population = $1 WHERE id = $2; END; $body$ LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER COST 100; When I ran it again, I couldn't reproduce it. There were no more deadlocks. Why is this happening? EDIT: After investigating a little bit, it seems that Hibernate is calling this method by itself sometimes when flushing session. Several times in some cases, for different entities, all in the same transaction. This can cause deadlocking because each call to update_table01() locks specific table01 column row with FOR UPDATE lock. With some improper call ordering, it can create a circular wait. After I made this entity non-updatable (i.e. marked all columns with update=false), everything works as it should. Now, I am really surprised with this Hibernate behaviour, because table01 entities in RAM were not attached to any of sessions which were responsible for later transactions. And yet, Hibernate flushed these entities to database, and I don't know why. As for the locks, I've identified two more stored procedures of mine that insert/update to some other table which references table01 (one of them changes the FK column). These will request a ShareLock on the appropriate FK row in table01, and will, therefore, conflict with update_table01(). So these three stored procedures will wait for each other to complete. This alone cannot create a circular wait, but it becomes possible if you add a couple of Hibernate-caused calls to update_table01() after calls to these stored procedures. A: Firstly, the exclusive lock you see in: ExclusiveLock on tuple (8,72) of relation 16890 of database 16751 This should hopefully be your "table01" - try: SELECT * FROM pg_class WHERE oid = 16890; Secondly, yes you have processes 23495 and 23481 blocking each other. PostgreSQL detects this after waiting 1 second and cancels 23495. Then, a few lines further down 23481 goes through after 1000.361ms. To test this, you'll want two terminals open, each running psql. That way you can control the pauses in each. Issue a BEGIN in each and try running the update in both terminals. Take a look at the pg_locks view to see what's going on. None of my experimenting has been able to reproduce this, and I can't see how it can. The ShareLock you see is probably the one preventing changes to the table while the UPDATE occurs. You wouldn't want someone dropping the column you are trying to update. Naturally, two share-locks can't conflict so there must be something else at work. What does strike me from your log extract is that you have a number of other simple updates that are all sat there for what seems like a long time for such a simple update. It's possible that the deadlock detector was mistaken - your server was just under extreme load and there was no conflict between your two transactions. If your deadlock_timeout setting was a bit longer this might never have happened.
{ "pile_set_name": "StackExchange" }
Q: Showing the bijection between countable dense subset of a metric space $E×\mathbb{Q}→$neighborhoods of $E$ with rational radius Let $X$ be a separable metric space. Let $E$ be a countable dense subset of $X$. Let $p_i$ enumerate $E$ and $q_j$ enumerate $\mathbb{Q}$. Let $G=\{N(p_i,q_j) \subset X | i,j\in \omega\}$ Then $G$ is a base for $X$. Can one show the bijection between $E×\mathbb{Q}$ and $G$ in ZF? I want to show that $G$ is countable, and since $E×\mathbb{Q}$ is countable, if i can show the bijection, proof will be done. Help I don't know whether $f:(p,q)→N(p,q)$ is a bijection and even if it is a bijection, i have no idea how to show that $f$ is injective.. A: The map $(p,q)\mapsto N(p,q)$ is not necessarily bijection. Take $X=E=\mathbb Z$ as an example. (For any $z\in\mathbb Z$ the ordered pairs $(z,\frac1n)$ are mapped to the same set $N(z,\frac1n)=\{z\}$.) However, you can take some well-ordering on $E\times\mathbb Q$ and define $$N(p,q)\mapsto \min\{(a,b)\in E\times\mathbb Q; N(a,b)=N(p,q)\}.$$ (If you prefer, you can get a well-ordering of order type $\omega$ on the set $E\times\mathbb Q$. This can be obtained using any bijection between $E\times\mathbb Q$ and $\omega$. Since you are given enumeration of $E$ and $\mathbb Q$, exhibiting such a bijection does not need axiom of choice.) The image of this map is a subset of countable well-ordered set $E\times\mathbb Q$. Therefore it is again a countable well-ordered set. So it is in bijection with some countable ordinal. Additional question in your comment: How do I show that $G$ is not finite. If $E$ is infinite, then $G$ cannot be finite. Just show by induction on $i$ that for each $p_i$ you can find $r_i\in\mathbb Q$ such that $N(p_i,r_i)$ is different from $N(p_j,r_j)$ for each $j<i$. This can be done by induction, in the inductive step you choose $r_i < \min \{d(p_i,p_j); j<i\}$. (Note that $ \{d(p_i,p_j); j<i\}$ is a finite set of positive real numbers, so the minimum of this set is a positive real number and there exists a rational number smaller than this minimum.) Then $i\mapsto N(p_i,r_i)$ is an injective map $\omega\to G$. (The point $p_i$ is contained in $N(p_i,r_i)$, but it does not belong to any of the sets $N(p_j,r_j)$ for $j<i$. Therefore any two sets $N(p_i,r_i)$ and $N(p_j,r_j)$, $i\ne j$, are different.)
{ "pile_set_name": "StackExchange" }
Q: regex parsing delimited string I am having trouble with parsing my delimited string with the following regex (this regex also takes into account situation, when user is using quotes as a grouping character): "[^"]*"|[^;]* This works perfectly fine when there is no empty space between the delimiter, such as following: 31.12.2015;M234;94 841,00;C **results:** 31.12.2015 M234 94 841,00 C However it fails, when some of the 'columns' / values are empty such as following: 31.12.2015;M234;94 841,00 ;C;;;0000-0000-00;0000000 The problem is, that it does not return empty space between my delimiters as a result and simply skips to a new delimiter. What do I need to change to fix this regex? Here is the code I am using to loop through values For Each Match In sRegex.Execute(sRow) If Match.Length > 0 Or bDelimiter = False Then Debug.Print Match.Value sHolder(UBound(sHolder)) = Match.Value ReDim Preserve sHolder(0 To UBound(sHolder) + 1) bDelimiter = True Else bDelimiter = False Debug.Print "delimiter" End If Next Match A: I see the problem is identifying whether the empty string is actually an empty string before a ; after a valid item, or whether is an empty item itself. I suggest changing the regex to "[^"]*"|([^;]*);? to capture all non-;s before an optional ; that will be consumed, and no empty space will no longer be available for the regex to match. Some more logic should be introduced though. Here is an example code: Sub ExecuteTest2() Dim s As String Dim sRegex As New regexp Dim sHolder() As String Dim strPattern As String strPattern = """[^""]*""|([^;]*);?" s = "31.12.2015;M234;94 841,00 ;C;;;0000-0000-00;0000000" sRegex.Global = True sRegex.MultiLine = False sRegex.IgnoreCase = True sRegex.pattern = strPattern ReDim Preserve sHolder(0) For Each match In sRegex.Execute(s) If match.SubMatches.Count > 0 Then Debug.Print match.SubMatches(0) sHolder(UBound(sHolder)) = match.SubMatches(0) ReDim Preserve sHolder(0 To UBound(sHolder) + 1) Else Debug.Print match.Value sHolder(UBound(sHolder)) = match.Value ReDim Preserve sHolder(0 To UBound(sHolder) + 1) End If Next match End Sub
{ "pile_set_name": "StackExchange" }
Q: Show a child's Matrix within a Structure I want to show a child entry and can so: <ul> {% for entry in craft.entries.section('products') %} {% switch entry.level %} {% case '1' %} {# level 1 #} <h1>{{ entry.title }}</h1> {% case '2' %} <li> {# level 2 #} <h2>{{ entry.title }}</h2> {% case '3' %} <ul> <li> {# level 3 #} <h4>{{ entry.title }}</h4> </li> </ul> {% case '4' %} {# level 4 #} 4 </li> {% endswitch %} {% endfor %} </ul> but I can't get a matrix field to show for the child entry, using: {% for block in entry.myMatrix %} {{ block.intro }} {% endfor %} within any of the cases? A: This should do it, user2569 {% for block in entry.myMatrix %} {% if block.type == 'intro' %} {{ block.intro }} {% endif %} {% endfor %}
{ "pile_set_name": "StackExchange" }
Q: Static Comments System for Jekyll My blog currently runs Jekyll and the Minimal Mistakes theme, and uses the theme's built in functionality to add the Disqus comments system. This JavaScript-based commenting system, to me sort of defeats the purpose of having a static blog in Jekyll, considering: Its JavaScript creates a decisively non-static page. Comments are not stored with the website. Comments are stored in some database instead of flat-text files. My question is, therefore: What is a suitable system for comments that stays as close to the Jekyll philosophy as possible (an ideally runs on gh-pages)? I found several possible candidates: Isso is a comments system which is looks similar to Disqus, it works with a SQLite database Jekyll::StaticComments seems pretty suitable, but it means you have to manually add the comments from emails. Are there any other options? If so, what would work with gh-pages, and what would work on a self-hosted Jekyll blog? A: Here's another solution which is dynamic and uses JavaScript, but doesn't store the comments at a 3rd party provider: This guy made a static website with Jekyll, but uses GitHub's issue tracker to create his comments. He uses GitHub Pages to host his blog, and for each new post, he creates a new issue in his blog's repository. Then, he uses JavaScript to get the issue's comments from the GitHub API and show it on the page. Here's a blog post which explains how to set this up: GitHub hosted comments for GitHub hosted blogs A: Whether a javascript loaded, externally hosted comment system "defeats the purpose" of a static site is a matter of opinion. For me, the point is to be able to host the site as entirely static resources, to take advantage of caching, CDN, distributed hosting, etc. I have seen huge advantages to that, and externally hosting my comments doesn't conflict at all. That being said, it's an interesting question. Isso (like Disqus) uses JS on the client side and requires server side software (Python based) that you have to manage, so it doesn't seem like this is any closer to your ideal. Jekyll::StaticComments is in the right direction, but it's not supported on gh-pages if you have GitHub processing your Jekyll site (you can of course generate the static site yourself and then host it on GitHub Pages). You also need a way for users to submit comments, and then to get those comments into a file that can be used by the generation process (not necessarily via email as you thought though). So you need to take comments from somewhere, possibly email, possibly yet another third party hosted app (SimpleForm maybe). And then you need to manually put them into the YAML site, regenerate, then publish, or, you can set up an automated build process for your site, which can pull the user submitted content when available and build and publish automatically. Other than manually accepting comments through an off-site medium, you're going to deal with something dynamic somewhere.
{ "pile_set_name": "StackExchange" }
Q: same image but getting different size when installing the app in simulator and device,AFNetWorking I am doing like following to determine the size of the downloaded image during the block and then i will set the size of the uiimageview accordingly. self.headerView is an outlet connection to uiimageview in the xib __weak UIImageView *weakObj = self.headerView; [self.headerView setImageWithURLRequest:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:fundraiserInfo.imageUrl]] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { NSLog(@"image is %@",NSStringFromCGSize(image.size)); CGRect newFrame ; newFrame = weakObj.frame; newFrame.size.width = image.size.width; newFrame.size.height = image.size.height; weakObj.frame = newFrame; } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { ; } ]; However, when running the app on the simulator (Device-Iphone), iam getting image is {300, 222} However, If I am using simulator (Retina 3.5) or (Retina 4) or I install the app on iphone4 or iphone 5, I am getting : image is {150, 111} Why it happens like that. A: Its because the image you're downloading isn't identified as a 'retina' image, so on retina devices it will appear as half the size it's actual pixels are. You can specify an image as retina by reading in an image who's filename is 'filenam@2x.jpg' or you can specify a UIImage's 'scale' value at the time of creation as 1.0 (non-retina) or 2.0 (retina) [UIImage imageWithData:scale:] [UIImage imageWithCGImage:scale:orientation:] If you don't provide a scale value its assumed the image is the appropriate resolution as you've discovered.
{ "pile_set_name": "StackExchange" }
Q: Aligning of modal box I am trying to align the modal box ( in this case it's a confirm box ) in the center of the page. So I set the position of the main container to be relative and then positioned the div element of the modal box using the following CSS code: .confirmBox{ top:25%; left:25%; } I have adjusted the values of the top and left attributes. This works fine at lower zoom but as I zoom in the box does not remain in the center of the page. How can I solve this using CSS? The original code is actually big and i am not able to think of an instance for this case. Still I am considering the div element with class="confirmBox" to be the code for confirmBox and attaching the fiddle http://jsfiddle.net/W6ATN/47/. A: You can use 50% left and top positions, and then subtract half of the width and height to make up for the size of the element: position:absolute; top:50%; height: <your value>px; margin-top: (negative value of your height, divided by 2); width:<your value>px; left:50%; margin-left: (negative value of your width, divided by 2); I think this way is easier to understand. If the width of the element is 40% (of its container), then it should be 30% to the left to be equally centered: |-----30%-----|-------40%--------|-----30%-----| which all == 100% Or you can use % width and % height, and use simple math to figure out the left and top positioning: position:absolute; height:40%; width:40%; left:30%; // (100 - width) divided by 2 top:30%; // (100 - height) divided by 2
{ "pile_set_name": "StackExchange" }
Q: How can I learn to think and interpret things more critically? As a freelance journalist, I spend a lot of time reading the media. Often I'll come across an article that I admire, and feel is leaps and bounds above my own work. Naturally, I want to learn from such pieces: but often I struggle to understand exactly why I find them inspirational. Without that, they're not very helpful as learning tools. I understand the oft-given advice that to improve as a writer, one must read a lot and read with a critical mind. However, I frequently feel that I'm not doing the latter bit as well as I should. I studied Literature to A-level (age 16-18 - no idea what the US equivalent was), and did well. However as the years have passed and I've no longer needed to exercise those critical skills, they've atrophied. I've become more used to reading and interpreting things on their surface level, and not looking so hard to see what's underneath. This is of particular importance to me because much of what I write is criticism. A lot of the material I cover doesn't offer layers of allegory or metaphor. But when it's there, I'm sure I often miss it. So I need to learn to be critical not just of writing but other media, and to learn the language of critical theory that goes with it. There's also an element of self-discipline here. Why look harder when you don't need to? Especially when it comes to fast-paced media where it's easy to get caught up in the ride. When a moment rises that invites reflection, it's too late: you're swept on to the next scene. So - what can I do to learn more about how to think critically, and to encourage myself to use those skills? I'm aware that a lot of Universities offer free videos of lecture courses nowadays, which on the surface would seem an ideal resource - but almost everything I've found in that vein is STEM focussed. A: You could read a text (literary or media) and then look at what other people have said about it. This can make you more aware of what to look for so that you can look for it in future and make you think about the text in a deeper way. You could look into literary theory as a way to make you more aware of different ways of looking at texts. Personally, when I was taught about semiotics it changed how I looked at Shakespeare. If you want a start on literary theory I would recommend downloading the audio versions of the Open Yale course available here. On a simpler level, try using the frameworks that you were given for analysing literature at A-Level.
{ "pile_set_name": "StackExchange" }
Q: How to Disable drawer in fragment and back back to correct fragment I have a main Activity with a Fragment layout. The drawer has 3 option: Fragment[1], Fragment[2], Fragment[3]. Inside Fragment[2] and Fragment[3] is one button. This button open other fragment. Fragment[4]. I want Fragment[4] without drawer but with a back button. This is the onClick code in Fragment[2] Fragment fragment = new InstalacionesEncontradasFragment(); Bundle bundle = new Bundle(); bundle.putSerializable("key", this.instalacionesConCategorias); fragment.setArguments(bundle); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction(); mFragmentTransaction.addToBackStack(null); mFragmentTransaction.replace(R.id.main_frame_container, fragment, "ACTIVIDADES").commit(); And in Fragment[4] onCreate method: getActivity().getActionBar().setDisplayHomeAsUpEnabled(true); But this solution doesn't work. How to disable the drawer? Where should I implement the back button? In Fragment[2] or Fragment[3]? A: You can use : mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); This will lock drawer opening on swipe Add the line getActivity().getActionBar().setDisplayHomeAsUpEnabled(true); in Activity which makes all fragments like Fragment 1, 2,3 and 4. May be in your case, Fragment 4 is from differenct activity than Fragment 2. So, back button press is not working
{ "pile_set_name": "StackExchange" }
Q: Word2Vec and Gensim parameters equivalence Gensim is an optimized python port of Word2Vec (see http://radimrehurek.com/2013/09/deep-learning-with-word2vec-and-gensim/) I am currently using these vectors: http://clic.cimec.unitn.it/composes/semantic-vectors.html I am going to rerun the model training with gensim because there was some noisy tokens in their models. So i would like to find out what are some equivalent parameters for word2vec in gensim And the parameters they used from word2vec are: 2-word context window, PMI weighting, no compression, 300K dimensions What is the gensim equivalence when i train a Word2Vec model? Is it: >>> model = Word2Vec(sentences, size=300000, window=2, min_count=5, workers=4) Is there a PMI weight option in gensim? What is the default min_count used in word2vec? There's another set of parameters from word2vec as such: 5-word context window, 10 negative samples, subsampling, 400 dimensions. Is there a negative samples parameter in gensim? What is the parameter equivalence of subsampling in gensim? A: The paper you link to compares word embeddings from a number of schemes, including Continuous Bag of Words (CBOW). CBOW is one of the models implemented in Gensim's "word2vec" model. The paper also discusses word embeddings obtained from Singular Value Decomposition with various weighting schemes, some involving PMI. There is no equivalence between SVD and word2vec, but if you want to do an SVD in gensim, it's called "LSA" or "Latent Semantic Analysis" when done in natural language processing. The min_count parameter is set to 5 by default, as can be seen here. Negative Sampling and Hierarchical Softmax are two approximate inference methods for estimating a probability distribution over a discrete space (used when a normal softmax is too computationally expensive). Gensim's word2vec implements both. It uses hierarchical softmax by default, but you can use negative sampling by setting the hyperparameter negative to be greater than zero. This is documented in comments in gensim's code here as well.
{ "pile_set_name": "StackExchange" }
Q: PHP I have two arrays, I want to extract items from Array 1 if it's not already in Array 2 Like the title says, I have two arrays and I just want to get everything from the first array that's not already in the second array. How do I do this? A: Use array_diff: $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); print_r($result); Result: Array ( [1] => blue ) See it working online: ideone
{ "pile_set_name": "StackExchange" }
Q: Convergence of $\sum_{n=1}^{\infty}\dfrac{(-1)^n}{n^{1+1/n}}$ Does the series $$\sum_{n=1}^{\infty}\dfrac{(-1)^n}{n^{1+1/n}}$$ converge absolutely, converge conditionally, or diverge? I've tried applying the ratio test and the root test, and in both cases the limit is $1$, so I cannot conclude anything. A: This series does not converge absolutely, by the limit comparison test $$ \lim_{n\to\infty} \frac{1/n^{1+1/n}}{1/n} = \lim_{n\to\infty} \frac{1}{n^{1/n}} = 1 $$ with the divergent harmonic series $\sum \frac{1}{n}$. But since $$ \frac{1}{n^{1+1/n}} = \frac{1}{n} \exp\left( - \frac{\log n}{n} \right) = \frac{1}{n} + O\left(\frac{\log n}{n^2} \right), $$ the series converges conditionally by noting that $$ \sum_{n=1}^{\infty} \frac{(-1)^{n}}{n^{1+1/n}} = \sum_{n=1}^{\infty} (-1)^{n} \left( \frac{1}{n} + O\left(\frac{\log n}{n^2} \right) \right), $$ which is a sum of two convergent series. This is my favorite style of argument for proving that an alternating series with complicated term converges. If you feel uncomfortable with the Big-Oh notation, then consider the function $$ f(x) = x^{-1-\frac{1}{x}} = \exp\left( - \frac{x+1}{x}\log x \right). $$ Then by the logarithmic differentiation, $$\frac{f'(x)}{f(x)} = -\frac{x+1-\log x}{x^2} < 0 $$ for large $x$ and thus $f(x)$ is a non-negative decreasing function. Since it is immediate that $f(x) \to 0$ s $x \to \infty$, the conclusion follows from the alternating series test that $$ \sum_{n=1}^{\infty} \frac{(-1)^{n}}{n^{1+1/n}} = \sum_{n=1}^{\infty} (-1)^{n} f(n) $$ converges.
{ "pile_set_name": "StackExchange" }
Q: Is there a convenient way to initialize simple structs in C++? Let's say I have a simple struct like this: struct Simple { int weight; std::string name; float power; }; I'd like to be able to initialize one of these without creating a constructor for it and without having to individually set its parameters. I dream of a syntax like this, for example: Simple s( 4, "bill", 3.1f ); ...or perhaps... Simple s = { 4, "bill", 3.1f }; ...or verily... Simple s{ 4, "bill", 3.1f }; I know that I can get the first example to work by adding a braindead constructor of my own. Tedious. Likewise, the last example will work in C++11, but I believe I have to provide the constructor. Is there a way to simply and elegantly initialize a struct in C++ without having to provide a constructor? A: Simple s = { 4, "bill", 3.1f }; Simple s{ 4, "bill", 3.1f }; These are valid. This syntax will map each value in the above groups/sets to each struct member variable depending on the order and you don't even need to define a constructor.
{ "pile_set_name": "StackExchange" }
Q: PHP Array to XML with no numbers PHP array to XML problem. I have an array and when trying to convert it into an xml file, it is counting the total fields using "item0" "item1"...so on. I only want it to display "item" "item". Examples below. Thank you. PHP code turning the array($store) into an XML file. // initializing or creating array $student_info = array($store); // creating object of SimpleXMLElement $xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>"); // function call to convert array to xml array_to_xml($student_info,$xml_student_info); //saving generated xml file $xml_student_info->asXML('xmltest.xml'); // function defination to convert array to xml function array_to_xml($student_info, &$xml_student_info) { foreach($student_info as $key => $value) { if(is_array($value)) { if(!is_numeric($key)){ $subnode = $xml_student_info->addChild("$key"); array_to_xml($value, $subnode); } else{ $subnode = $xml_student_info->addChild("item$key"); array_to_xml($value, $subnode); } } else { $xml_student_info->addChild("$key","$value"); } } } What the XML file looks like (with the item# error) <student_info> <item0> <item0> <bus_id>2436</bus_id> <user1>25</user1> <status>2</status> </item0> <item1> <bus_id>2438</bus_id> <user1>1</user1> <status>2</status> </item1> <item2> <bus_id>2435</bus_id> <user1>1</user1> <status>2</status> </item2> </item0> </student_info> Once again, I just want each "item" to display "item" with no number. and the first and last "item0"... I dont know what thats about. Thanks for any help! A: Answer to question Replace this: else{ $subnode = $xml_student_info->addChild("item$key"); array_to_xml($value, $subnode); } with this: else{ $subnode = $xml_student_info->addChild("item"); array_to_xml($value, $subnode); } Answer to comment I don't know how your array is structured but, from the output, I would guess the problem is in the following line: $student_info = array($store); So, change to this: if (!is_array($store)) { $student_info = array($store); } else { $student_info = $store; } This should fix it
{ "pile_set_name": "StackExchange" }
Q: PHP Check if dynamic named folder exists I'm having problems checking if a dinamically named folder exists using php. I know i can use file_exists() to check if a folder or file exists, but the problem is that the name of the folders I'm checking may vary. I have folders where the first part of the name is fixed, and the part after "_" can vary. As an example: folder_0, where every folder will start with "folder_" but after the "_" it can be anything. Anyway i can check if a folder with this property exists? Thanks in advance. SR A: You make a loop to go through all the files/folders in the parent folder: $folder = '/path-to-your-folder-having-subfolders'; $handle = opendir($folder) or die('Could not open folder.'); while (false !== ($file = readdir($handle))) { if (preg_match("|^folder_(.*)$|", $file, $match)) { $curr_foldername = $match[0]; // If you come here you know that such a folder exists and the full name is in the above variable } }
{ "pile_set_name": "StackExchange" }
Q: How to send a batch with emails in android? I want to send several emails to different recipients, but the text of the letters may differ. And I also want to authorize the user and send mail on his behalf, by Intent and the built-in mail client app. And is there any way to do this with one button click, rather than calling up a new email window (activity) for each of these letters and forcing the user to confirms the sending of each letter? And is there any way to not call the new e-mail window for each of these letters, so that the user confirms the sending of each letter, and do this at the touch of a button? Maybe are there any third-party libraries or free mail services for this purpose? A: You can use simple-java-mail to achieve that. public static void SendMail(String recipientName,String recipientAddress,String subject,String message,File file,String myAdress,String password) throws IOException{ System.out.println("File size "+file.length()); Email email = new Email(); email.setFromAddress(myAdress.split("@")[0], myAdress); email.addRecipient(recipientName, recipientAddress, Message.RecipientType.TO); email.setSubject(subject); email.setText(message); if(file!=null) email.addAttachment(file.getName(), FileUtils.readFileToByteArray(file),"application/pdf"); String host = myAdress.split("@")[1]; new Mailer( new ServerConfig("smtp."+host, 587, myAdress, password), TransportStrategy.SMTP_TLS, new ProxyConfig("socksproxy."+host, 1080, "proxy user", "proxy password") ).sendMail(email); } If your client is using Gmail, they have to allow third parties to send mail in their settings
{ "pile_set_name": "StackExchange" }
Q: The Kephas.Model package seems a bit heavy weight for my requirements of extensible metadata. Is there a lighter alternative? My requirement is to use some kind of metadata system for the entities we use, but extensible, meaning that we need to support some kind of custom metadata additionally to querying for properties and methods. The standard Type/TypeInfo classes are useful to some extent, but they cannot be customized to add specific properties to support various patterns we have: tree nodes, master-detail, and other. Kephas.Model provides a complex infrastructure for supporting such cases, including advanced features like mixins and dimensions, but this is however a bit too much for our system. We need something more lightweight for the code-first entities we have. Is there a suggestion about what can we use for this kind of requirements? I noticed the Kephas.Reflection namespace, and this seems like a proper candidate, but I am not sure how to use it properly. A: That's right, Kephas.Runtime namespace provides a lightweight extensible metadata through the base IRuntimeTypeInfo interface (in Kephas.Core package). There are mainly two ways of accessing it using extension methods: // get the type information from an object/instance. var typeInfo = obj.GetRuntimeTypeInfo(); // convert a Type/TypeInfo to a IRuntimeTypeInfo typeInfo = type.AsRuntimeTypeInfo(); From here on you can manipulate properties, fields, methods, annotations (attributes), and so on, typically indexed by their names. A very nice feature is that IRuntimeTypeInfo is an expando, allowing adding of dynamic values at runtime. Please note that IRuntimeTypeInfo specializes ITypeInfo (in Kephas.Reflection namespace), which is the base interface in Kephas.Model, too. You are right that Kephas.Model provides a more complex functionality which might make sense for a more elaborate metadata model, including entities, services, activities, and whatever classifiers you can think of, as well as loading the model also from sources other than the .NET reflection (JSON, XML, database, so on). Another aspect is that up to version 5.2.0, the IRuntimeTypeInfo would be implemented by the sealed RuntimeTypeInfo class. Starting with version 5.3.0, it will be possible to provide your own implementations, which can be more than one.
{ "pile_set_name": "StackExchange" }
Q: Difference between OpenPGP symmetric encryption and AES-256? I would like to understand the difference between: OpenPGP symmetric encryption and AES-256 using Winzip/7-zip? I mean if you encrypt a file with an OpenPGP program like GnuPG, using AES-256 symmetric encryption. And do the same with Winzip/7-zip using AES-256. What is the difference? [I am not asking about the asymmetric encryption in OpenPGP with public-private keys] Thanks. A: OpenPGP is a standard defining a message format. That message format is fairly complex, but in short, it contains: Which algorithm it's using, if any Any required parameters for that algorithm (e.g. nonces) The (encrypted) message body Some other metadata which isn't relevant here OpenPGP is, notably, not an encryption algorithm. It can use encryption (and that's its whole raison d'être, so it normally does) but the algorithm it uses is variable. AES-256, on the other hand, is a specific algorithm. It takes as input a secret key and a message, and it encrypts that key with that message. AES-256 is one of the many encryption algorithms that the OpenPGP standard supports. Encrypting something with AES-256 and the same key with OpenPGP is going to lead to the same ciphertext (encrypted text) as using any other software. However, there are two things to note: Bad implementations of AES do exist, and can be exploited, depending on context. Bad usages also exist; for example, the AES mode can be any number of things -- ECB, CBC, GCM -- and picking the wrong one could break your security. Because they're in different formats, the files produced by telling 7zip to encrypt a zipfile versus telling OpenPGP to encrypt a message will likely be different. However, this has nothing to do with their implementation of AES-256; as long as it's not broken, it'll still produce the same ciphertext. It's just represented differently.
{ "pile_set_name": "StackExchange" }
Q: HTML5 dialog element close button not working properly I'm looking at this question post, and I'm having trouble applying it to work in my code. It's confusing me because I'm doing the exact same thing for the save button as I am the cancel button (at least, the part about it closing) and nothing happens upon clicking cancel. <dialog class="my-modal"> <p>Add Cust</p> <label for="nameField">Name</label><input id=nameField><br> <label for="addressField">Address</label><input id=addressField><br> <label for="cityField">City</label><input id=cityField><br> <label for="stateField">State</label><input id=stateField size=2> &nbsp; <label for="zipField">Zip</label><input id=zipField><br> <br> <button onclick="closeAndSave()">Save</button> <button onclick="close()">cancel</button> </dialog> function close(){ const modal = document.querySelector('.my-modal'); modal.close(); } Have also tried: <button class="btn btn-default" data-dismiss="my-modal" aria-label="Close">Cancel</button> A: Another way to approach this would be to bind behavior to buttons in your script, rather than to specify functionality for buttons with the inline "onclick" attribute. The "inline onclick method" can lead to unexpected behavior (which may be the cause of the problem in your case). An example would be, if close() is redefined/reassigned elsewhere in your apps global scope, then that would cause "the wrong close function" to be called by the dialog's close button. Consider revising your HTML and script so that event binding is delegated to your script for better control, as shown below: /* Obtain modal as before */ const modal = document.querySelector('.my-modal') /* Select buttons from modal and bind click behavior */ modal.querySelector("button.cancel").addEventListener("click", () => { /* Call close method on modal to dismiss */ modal.close(); }); modal.querySelector("button.save").addEventListener("click", () => { alert("save data"); modal.close(); }); /* Added for snippet to prelaunch dialog */ modal.showModal(); <dialog class="my-modal"> <p>Add Cust</p> <label for="nameField">Name</label><input id=nameField><br> <label for="addressField">Address</label><input id=addressField><br> <label for="cityField">City</label><input id=cityField><br> <label for="stateField">State</label><input id=stateField size=2> &nbsp; <label for="zipField">Zip</label><input id=zipField><br> <br> <!-- Replace onclick with classes to identify/access each button --> <button class="save">Save</button> <button class="cancel">cancel</button> </dialog> Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: Do processors need to be hardened against vibration? Rockets are very loud, and seems to have a lot of vibration caused by turbulence. They're also run by microchips, which I tend to think of as fragile. Do the microchips need to be specially designed or encased to withstand these forces? A: Well, yes and no. The most important feature for modern space-bound CPUs (aside from 100% reliability) is radiation hardening. Radiation hardening is considered at every step of the design process from the materials used to the configuration of the transistors in each internal circuit. These chips are specifically designed to withstand any bombardment of radiation that can be thrown at them. That being said, there have been some improvements considering susceptibility to vibration in recent history. Traditionally processor circuits for devices meant to live in the harshness of space contain a simple (or in the case of the Voyager 10/11 crafts completely discrete logic) devices that are supported by a large array of discrete logic. This was done, again, in pursuit of radiation hardening. Such circuits were composed of a large number of components with exposed leads. Below is an image one of the main computer boards for the (now retired) space shuttle: Nowadays the dense CPUs (such as the CPU in the BAE RAD750 single board computer) are designed with some variety of a leadless (the pins are underneath the component) footprint. This document shows the features of the CPU contained within the RAD750, and there is a section on the device's reliability: The RAD750 will be packaged in a Ceramic Column Grid Array (CGA) package, constructed by attaching extended columns to the original Ball Grid Array (BGA) 360 pin package employed for the 0.25 micron PowerPC 750. The CGA package has been adopted because it is better suited to the stresses of launch and the space environment. The CGA has demonstrated significantly increased reliability during temperature cycling and stress, when compared to BGA packages, as shown in Figure 3. The CGA package has also passed shock and vibration testing for the space launch environment. As you can imagine, the column grid array components are much more rigid than the leaded components. More information on CGA can be found here.
{ "pile_set_name": "StackExchange" }
Q: How do i make JOIN when need to carried out first table column values? I have two tables rawtable and tradetable rawtable rawid companyname uniqueID 1 AAA-XA 9CV 2 BBB-DEMO 10K 3 CCC-XOXO 7D tradetable tradeid securityname CUSIP 1 AAACOMP 9CV 2 BBBCOMP 10K Now what I need is companyname from rawtable is bit mixed so I need to have securityname from tradetable as companyname for that I used LEFT JOIN declare DataSourceId = 3; SELECT DISTINCT @DataSourceId, dbo.CleanText(tradetable.securityname) FROM tradetable LEFT JOIN ( SELECT DISTINCT companyname, uniqueID FROM rawtable ) rawtable ON tradetable.cusip = rawtable. uniqueID which will give me names from tradetable but here I will miss the new not matching names from rawtable but I want those name too but in select statement if I use declare DataSourceId = 3; SELECT DISTINCT @DataSourceId, dbo.CleanText(rawtable.securityname) --instead of tradetable then I will select wrong mixed name So how can I solve this problem? or from somewhere else I need to carried out correct names as I want it like tradetable securityname OUTPUT I EXPECTED : rawtable companyname uniqueID AAA-XA 9CV BBB-DEMO 10K CCC-XOXO 7D tradetable securityname CUSIP AAACOMP 9CV BBBCOMP 10K I WANT A securityname i.e companyname in proper format for that i'm checking uniqueID if it is matching then it will fetch securityname from tradetable NOW when there is an addition record in rawtable like CCC_XOXO is there it actual name might be CCC so for taking CCC i should have to take that CCC from where it is present in 3rd table or is there any other way? means i need to import that 3rd table also in my JOIN right? A: You mean you want to take the value from tradetable and if it doesn't exist, take it from rawtable? Like this (sqlfiddle)? SELECT dbo.CleanText(COALESCE(t.securityname,r.companyname)) AS companyname, COALESCE(t.CUSIP,r.uniqueID) AS uniqueID FROM rawtable r LEFT OUTER JOIN tradetable t ON r.uniqueID = t.CUSIP Output is: COMPANYNAME UNIQUEID AAACOMP CV BBBCOMP 10K CCC-XOXO 7D
{ "pile_set_name": "StackExchange" }
Q: Using nested resources without the parent ID in Rails I have a class called Imprintables with nested resources Styles, Brands, Colors, and Sizes. I currently have this in my routes file: resources :imprintables do resources :styles, :brands, :colors resources :sizes do collection do post 'update_size_order' end end end Which produces routes like this: /imprintables/:imprintable_id/brands /imprintables/:imprintable_id/colors /imprintables/:imprintable_id/styles /imprintables/:impritnable_id/sizes I don't want to have all my nested resources tied to 1 specific imprintable. I want to have my routes look like: /imprintables/brands /imprintables/styles /imprintables/colors /imprintables/sizes ...etc. Whats the best way to go about this? A: resources :imprintables do collection do resources :styles, :brands, :colors end end
{ "pile_set_name": "StackExchange" }
Q: Print what percent of numbers are even and print out even numbers in the array I'm recently learning arrays, and I am stuck on this question. I basically have to ask the user to input the numbers that will go into the array, and have to print out the percent of the numbers even and have to print all even numbers in the format that follows. Even values are : 89,22,-8, 0 My code is this import java.util.*; public class Change { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("How many numbers in the array?"); int num = input.nextInt(); int count=0; int count1=0; for (int i=1; i<=num; i++) { System.out.println("Enter an integer: "); count++; int integer= input.nextInt(); if(integer%2==0) { int list[]=new int[integer]; count1++; } } System.out.println("There were "+((double)count1/count)*100+" percent of even numbers."); System.out.println("Even values are "+Arrays.toString(list)+""); } } This code ends up with an error message, saying "list" is not initialized. I know that because "list" is inside the for loop, the system doesn't realize that it has been initialized, but I have no idea how to have the system recognize "list". Any help or comments are appreciated. :) A: package com.inlet.ifserver; import java.util.*; public class x { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("How many numbers in the array?"); int num = input.nextInt(); int count1 = 0; Integer[] evens = new Integer[num]; for (int i = 0; i < num; i++) { System.out.println("Enter an integer: "); int integer = input.nextInt(); if (integer % 2 == 0) evens[count1++] = integer; } evens = Arrays.copyOfRange(evens, 0, count1); System.out.println("There were " + ((double) count1 / num) * 100 + " percent of even numbers."); System.out.println("Even values are " + Arrays.toString(evens) + ""); } }
{ "pile_set_name": "StackExchange" }
Q: Can't install Grapefruit on Windows 10 When running cabal install grapefruit-ui-gtk I get build errors on the dependency TypeCompose. The exact command I run is cabal install grapefruit-ui-gtk and get the following error output: Resolving dependencies... Configuring TypeCompose-0.9.12... Configuring hashtables-1.2.3.1... Building TypeCompose-0.9.12... Building hashtables-1.2.3.1... Failed to install TypeCompose-0.9.12 Build log ( C:\Users\me\AppData\Roaming\cabal\logs\ghc-8.4.3\TypeCompose-0.9.12-4FepCXFvbF94E2D2EggnNC.log ): Preprocessing library for TypeCompose-0.9.12.. Building library for TypeCompose-0.9.12.. src\Data\Title.hs:1:33: warning: -XOverlappingInstances is deprecated: instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS | 1 | {-# LANGUAGE FlexibleInstances, OverlappingInstances, TypeOperators, TypeSynonymInstances #-} | ^^^^^^^^^^^^^^^^^^^^ [ 1 of 10] Compiling Control.Instances ( src\Control\Instances.hs, dist\build\Control\Instances.o ) [ 2 of 10] Compiling Data.Bijection ( src\Data\Bijection.hs, dist\build\Data\Bijection.o ) [ 3 of 10] Compiling Control.Compose ( src\Control\Compose.hs, dist\build\Control\Compose.o ) src\Control\Compose.hs:596:10: error: * Could not deduce (Semigroup (Flip j o a)) arising from the superclasses of an instance declaration from the context: (Applicative (j a), Monoid o) bound by the instance declaration at src\Control\Compose.hs:596:10-61 * In the instance declaration for `Monoid (Flip j o a)' | 596 | instance (Applicative (j a), Monoid o) => Monoid (Flip j o a) where | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ src\Control\Compose.hs:645:10: error: * Could not deduce (Semigroup (App f m)) arising from the superclasses of an instance declaration from the context: (Applicative f, Monoid m) bound by the instance declaration at src\Control\Compose.hs:645:10-54 * In the instance declaration for `Monoid (App f m)' | 645 | instance (Applicative f, Monoid m) => Monoid (App f m) where | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ src\Control\Compose.hs:851:1: error: * Could not deduce (Semigroup (Arrw j f g a)) arising from the superclasses of an instance declaration from the context: Monoid (j (f a) (g a)) bound by the instance declaration at src\Control\Compose.hs:851:1-63 * In the instance declaration for `Monoid (Arrw j f g a)' | 851 | deriving instance Monoid (f a `j` g a) => Monoid (Arrw j f g a) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cabal: Leaving directory 'C:\Users\me\AppData\Local\Temp\cabal-tmp-17748\TypeCompose-0.9.12' Installed hashtables-1.2.3.1 cabal.exe: Error: some packages failed to install: TypeCompose-0.9.12-4FepCXFvbF94E2D2EggnNC failed during the building phase. The exception was: ExitFailure 1 grapefruit-frp-0.1.0.7-28vOfRvsiGH71mjsrgG35Q depends on grapefruit-frp-0.1.0.7 which failed to install. grapefruit-records-0.1.0.7-Ih2DxRIbFnG7TB7BHtPbwq depends on grapefruit-records-0.1.0.7 which failed to install. grapefruit-ui-0.1.0.7-DMol4wZpyyFEHFP2NRKthr depends on grapefruit-ui-0.1.0.7 which failed to install. grapefruit-ui-gtk-0.1.0.7-EsNz0f5KGlp47W2BX85WRG depends on grapefruit-ui-gtk-0.1.0.7 which failed to install. GHC Version: The Glorious Glasgow Haskell Compilation System, version 8.4.3 Cabal version: cabal-install version 2.2.0.0 compiled using version 2.2.0.1 of the Cabal library What could be causing this issue? I have tried installing it in a fresh directory with cabal init, and that didn't seem to have any effect. A: This is a known issue with TypeCompose under 8.4, which has been fixed but not put on Hackage yet. You might be able to configure your cabal commands with an older version of GHC (see this question), such as 8.2.2, which shouldn't have this issue. Alternatively, use stack, which will let you switch ghc versions per-project, and which provides TypeCompose for 8.2.2 on the LTS resolver.
{ "pile_set_name": "StackExchange" }
Q: Cirqus: "Expected an event with sequence number 0." exception Every once in a while I receive exceptions in Cirqus when trying to process commands. It happens with different types of commands, however it always happens with this specific aggregate root type (let's say its a registration form). We haven't deleted events nor messed with the Events table in any way, so I'm wondering what else can cause the issue. The exact (but anonymized) error message is: Tried to apply event with sequence number 12 to aggregate root of type RegistrationForm with ID d863ac79-6bc0-480d-9d83-30b7696e7ea1 with current sequence number -1. Expected an event with sequence number 0. So for example to debug the latest instance of the exception I queried the database for this aggregate id and got 37 events in return. I then checked the sequences and the sequences seemed correct. I also checked that the global sequences were at least also chronologically correct. Then I checked to see if the "meta" column had a different global sequence than the record, but that also checked out OK. What I find most confusing is that other registration forms are able to go through. Looking at our logs there's no pattern I can identify, and also it only happens about 3-5% of the time. I guess what I'm wondering is: what can cause this issue? how can I debug it? how can I prevent it from happening in the future? System specifics: We're running under .net 4.5, using Cirqus 0.63.12 (and then also tested on 0.66.4), using Postgres 9.4 as the database (and using v0.63.12 of the Cirqus.Postgres package). A: I found the issue! It seems that the PostgreSQL event source's SQL code was missing an Order By clause and in some cases my events were being returned out of order. I submitted this pull request as a proposed fix to the problem: https://github.com/d60/Cirqus/pull/75
{ "pile_set_name": "StackExchange" }
Q: Compile Groovy files in Eclipse My java web project includes some Groovy code. But eclipse is not recognizing Groovy files and not generating any classes out of it. I have installed Groovy plugin in Eclipse. Installed Groovy in my windows machine and setup GROOVY_HOME and include groovyall jar file in my lib folder. But no luck. Please help. A: You could also use STS, when the dashboard opens up click on the "extensions" tab and click on the Groovy language feature and install it. Then right click on project, -> Spring -> configure groovy nature to use groovy also. Another option is create a new Groovy project, the upshot is that you can use any java file within a groovy project since they are so well coupled.
{ "pile_set_name": "StackExchange" }
Q: Retrieve the PK using @@identity I'm building a website using ASP.NET and SQL Server, and I use SELECT PK FROM Table WHERE PK = @@identity My question is which is better and more reliable to retrieve the last inserted PK for multiuser website, using @@identity or using this: SELECT MAX(PK) FROM Table WHERE PK = Session ("UserID") A: I'm not sure exactly what you want to achieve, but the recommended way to retrieve the primary key value of the last statement on a connection is to use SCOPE_IDENTITY() @@Identity is particularly risky where you are using triggers, since it returns the last generated identity value, including those generated by triggers flowing on from a statement. MSDN has the following to say: SCOPE_IDENTITY and @@IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope. You should certainly use SCOPE_IDENTITY() in favour of the MAX(PK) approach - any number of possible future changes could invalidate this method. A: For SQL Server 2005 and above... You can do the INSERT and SELECT in one call using the OUTPUT clause... INSERT MyTable (col1, col2, ..., coln) OUTPUT INSERTED.keycol, INSERTED.col1, INSERTED.col2, ..., INSERTED.coln VALUES (val1, val2, ..., valn) Otherwise, you only use SCOPE_IDENTITY()
{ "pile_set_name": "StackExchange" }
Q: Delete the [wish], [harry-potter], and other tags? IMO, wish (deleted) and harry-potter (deleted) do not appear to serve any useful purpose and can be deleted. Other tags which appear ripe for deletion/synonymisation: ic ian tech-speak management-speak genericized-trademarks polisemy productiveness I'm not sure about these either: untagged idiomaticity (Suggested as a synonym of idioms) acceptability Edit: I've added a (deleted) note to those tags which have been deleted. Users who can should visit the suggested synonyms page and vote on any pending suggestions. A: Yes, delete those tags! I just noticed the wish tag too! There are four instances of it, I believe. Consider also as candidates for deletion: schwa: There is only one question on the entire site with that tag. word and its synonym words: It seems to be used primarily by one person (user account). term and terms: Neither have any associated questions. A: I agree. Synonyms will stop deleted tags being resurrected in the future. Perhaps management-speak should be a synonym of business-language. Perhaps tech-speak should be a synonym of computing. Perhaps idiomaticity should be a synonym of idioms. A: Questions with genericized-trademarks should have been retagged with trademarks, rather than untagged. Unless trademarks should be deleted, or genericized-trademarks were a mistagging in the first place. Please take more care next time!
{ "pile_set_name": "StackExchange" }
Q: How do I use my Stack Exchange OpenID? I'm trying to sign up for mrmoneymustache.com, but I'm not sure about where to find my Stack Exchange OpenID URL. I entered https://openid.stackexchange.com/, but it did not work for me: A: You need to set Vanity OpenID (second field) by editing your profile (accepts "Only letters, numbers, periods, and dashes"). Then in your profile copy the link going after "Vanity Id", and paste it where you were going to log in. I think it should work. OR: click "Use your own URL to log in" and copy the link from the second tag.
{ "pile_set_name": "StackExchange" }
Q: Is there a better way to write this SQL query in sybase? I have a stored procedure with the following query. Based on the @range parameter I am adding more conditions to the where clause. The query below is giving me the correct results. I was wondering if I can avoid repeating the previous "Idx", "IdxType" as the range increases. Is there a better way to write this query? SELECT TOP 1 * FROM MyTable WHERE ID1 = @Id1 and Id1Type = @Id1Type and ( (@range = 2 and ID2 = @Id2 and ID2Type = @Id2Type) or (@range = 3 and ID2 = @Id2 and ID2Type = @Id2Type and ID3 = @Id3 and ID3Type = @Id3Type) or (@range = 4 and ID2 = Id2 and ID2Type = @Id2Type and ID3 = @Id3 and ID3Type = @Id3Type and ID4 = @Id4 and ID4Type = @Id4Type) or (@range = 5 and ID2 = @Id2 and ID2Type = @Id2Type and ID3 = @Id3 and ID3Type = @Id3Type and ID4 = @Id4 and ID4Type = @Id4Type and ID5 = @Id5 and ID5Type = @Id5Type) ) A: What you can do is to regroup terms atleast using simple boolean logic SELECT TOP 1 * FROM MyTable WHERE ID1 = @Id1 and Id1Type = @Id1Type and (@range < 2 or ID2 = @Id2 and ID2Type = @Id2Type) and (@range < 3 or ID3 = @Id3 and ID3Type = @Id3Type) and (@range < 4 or ID4 = @Id4 and ID4Type = @Id4Type) and (@range < 5 or ID5 = @Id5 and ID5Type = @Id5Type)
{ "pile_set_name": "StackExchange" }
Q: Executing Python application built with Pyinstaller gives "Failed to execute script main" I have a python program that uses tkinter for the GUI. My python project is a PyCharm project. It is organized as Project\main.py Project\my_class.py Project\images\favicon.ico Project\common\util\util1.py Project\common\util\util2.py Project\venv Inside the terminal I move to C:\..\Desktop\Project folder and run pyinstaller --windowed main.py If someone wonders what is the output in the terminal here it is 62 INFO: PyInstaller: 3.5 62 INFO: Python: 3.7.5 62 INFO: Platform: Windows-10-10.0.17763-SP0 62 INFO: wrote C:\Users\User\Desktop\Project\main.spec 62 INFO: UPX is not available. 62 INFO: Extending PYTHONPATH with paths ['C:\\Users\\User\\Desktop\\Project', 'C:\\Users\\User\\Desktop\\Project'] 62 INFO: checking Analysis 78 INFO: Building Analysis because Analysis-00.toc is non existent 78 INFO: Initializing module dependency graph... 78 INFO: Initializing module graph hooks... 78 INFO: Analyzing base_library.zip ... 2124 INFO: running Analysis Analysis-00.toc 2124 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\users\user\appdata\local\programs\python\python37\python.exe 3900 INFO: Caching module hooks... 3900 INFO: Analyzing C:\Users\User\Desktop\Project\main.py 4306 INFO: Processing pre-find module path hook distutils 5040 INFO: Processing pre-find module path hook site 5040 INFO: site: retargeting to fake-dir 'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\fake-modules' 5925 INFO: Processing pre-safe import module hook setuptools.extern.six.moves 7668 INFO: Loading module hooks... 7668 INFO: Loading module hook "hook-distutils.py"... 7671 INFO: Loading module hook "hook-encodings.py"... 7743 INFO: Loading module hook "hook-lib2to3.py"... 7747 INFO: Loading module hook "hook-numpy.core.py"... 7845 INFO: Loading module hook "hook-numpy.py"... 7846 INFO: Loading module hook "hook-pkg_resources.py"... 8092 INFO: Processing pre-safe import module hook win32com Traceback (most recent call last): File "<string>", line 2, in <module> ModuleNotFoundError: No module named 'win32com' 8150 INFO: Processing pre-safe import module hook win32com Traceback (most recent call last): File "<string>", line 2, in <module> ModuleNotFoundError: No module named 'win32com' 8327 INFO: Loading module hook "hook-pydoc.py"... 8328 INFO: Loading module hook "hook-setuptools.py"... 8742 INFO: Loading module hook "hook-sysconfig.py"... 8742 INFO: Loading module hook "hook-xml.dom.domreg.py"... 8742 INFO: Loading module hook "hook-xml.py"... 8742 INFO: Loading module hook "hook-_tkinter.py"... 9133 INFO: checking Tree 9133 INFO: Building Tree because Tree-00.toc is non existent 9148 INFO: Building Tree Tree-00.toc 9211 INFO: checking Tree 9211 INFO: Building Tree because Tree-01.toc is non existent 9211 INFO: Building Tree Tree-01.toc 9258 INFO: Looking for ctypes DLLs 9273 INFO: Analyzing run-time hooks ... 9273 INFO: Including run-time hook 'pyi_rth_pkgres.py' 9289 INFO: Including run-time hook 'pyi_rth_multiprocessing.py' 9289 INFO: Including run-time hook 'pyi_rth__tkinter.py' 9289 INFO: Looking for dynamic libraries 18180 INFO: Looking for eggs 18180 INFO: Using Python library c:\users\user\appdata\local\programs\python\python37\python37.dll 18180 INFO: Found binding redirects: [] 18180 INFO: Warnings written to C:\Users\User\Desktop\Project\build\main\warn-main.txt 18445 INFO: Graph cross-reference written to C:\Users\User\Desktop\Project\build\main\xref-main.html 18492 INFO: checking PYZ 18492 INFO: Building PYZ because PYZ-00.toc is non existent 18492 INFO: Building PYZ (ZlibArchive) C:\Users\User\Desktop\Project\build\main\PYZ-00.pyz 19259 INFO: Building PYZ (ZlibArchive) C:\Users\User\Desktop\Project\build\main\PYZ-00.pyz completed successfully. 19274 INFO: checking PKG 19274 INFO: Building PKG because PKG-00.toc is non existent 19274 INFO: Building PKG (CArchive) PKG-00.pkg 19290 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully. 19290 INFO: Bootloader c:\users\user\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\bootloader\Windows-64bit\runw.exe 19290 INFO: checking EXE 19290 INFO: Building EXE because EXE-00.toc is non existent 19290 INFO: Building EXE from EXE-00.toc 19290 INFO: Appending archive to EXE C:\Users\User\Desktop\Project\build\main\main.exe 19306 INFO: Building EXE from EXE-00.toc completed successfully. 19306 INFO: checking COLLECT 19306 INFO: Building COLLECT because COLLECT-00.toc is non existent 19306 INFO: Building COLLECT COLLECT-00.toc 22581 INFO: Building COLLECT COLLECT-00.toc completed successfully. And here the error How can I solve this problem? Have you any idea? A: Solved - install pywin32 to fix the ModuleNotFoundError: No module named 'win32com' in the venv\Lib\site-packages folder of the Project - install tornado in the venv\Lib\site-packages folder of the Project - open terminal and move to the project folder - run setlocal - run set PATH=C:\Users\User\AppData\Local\Programs\Python\Python37\;%PATH% <br> - runpyinstaller -y -D --paths "C:\Windows\System32\downlevel" --paths "C:\Users\User\Desktop\Project\venv\Lib\site-packages" main.py<br> - copied theimagesfolder fromProjectinto thedistfolder made bypyinstallerto get thefavicon.ico` in my GUI Now I can run it either from the terminal or by double-clicking
{ "pile_set_name": "StackExchange" }
Q: Teamcity trigger builds for github pull-requests I want to build each pull request merged with master. I have setup teamcity the following way: http://blog.jetbrains.com/teamcity/2013/02/automatically-building-pull-requests-from-github-with-teamcity/ Branch specification: +:refs/pull/(*/merge) Default branch: master I have setup github teamcity Service Hook. http://www.jaxzin.com/2011/02/teamcity-build-triggering-by-github.html When I enable the teamcity hook. The job recognizes the change but the build stays in 'pending' and is not triggered. Do I need to setup a VCS Trigger? I tried setting-up without the teamcity service hook, but builds for all the Pull-Requests are re-triggered whenever a new PR is submitted. The builds also get triggered on PRs which are closed. Can someone please share their configuration to trigger the build only once and not build any closed PRs? A: There is no need in TeamCity GitHub hook, you can go with simple VCS trigger. All active branches will be triggered on first start. From docs: A branch considered active if: it is present in the VCS repository and has recent commits (i.e. commits with the age less than the value of teamcity.activeVcsBranch.age.days parameter, 7 days by default). or it has recent builds (i.e. builds with the age less than the value of teamcity.activeBuildBranch.age.hours parameter, 24 hours by default). Try to just wait until it's done or cancel all builds. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: How to in PHP / HTML to pass a specific class name to specific tag I'm still new to Front End Development and working on my first really big site / wordpress blog. So my question is this, I have a Menu that will be the same on all pages on the site. However each section will have it's name highlighted in the Menu Nav. Current Nav_Bar markup: <div id="nav_bar"> <ul class="nav"> <li class="nav_li"><a href="../index.html">Home</a></li> <li class="nav_li"><a href="#">About</a></li> <li class="nav_li selected"><a href="#blog_content">Blog</a></li> <li class="nav_li"><a href="#">Book</a></li> <li class="nav_li"><a href="#">Media</a></li> <li class="nav_li"><a href="#">Events</a></li> <li class="nav_li"><a href="#">Services</a></li> <li class="nav_li"><a href="#">Contact</a></li> <li class="search"> <input type="text" onfocus="if(this.value == 'Search') { this.value = ''; }" value="Search" /> </li> <li class="search_btn"> <a href="#" title="Lets find it!"><div class="search_button">Go</div></a> </li> </ul> </div><!-- nav_bar --> Now I've build pages before using this simple PHP code: <?php include("menu.php"); ?> However, how would you guys 1st: organize this menu to accept and incoming value, like menu.php+select="home" and 2nd how would you pass in that value to add a class of selected to one of the Menu items? A: Before the include, set a value in some parameter, like $page = 'blog' and then in the menu.php <li class="nav_li<?php echo $page === 'blog' ? " selected='selected'" : "" ?>"><a href="#blog_content">Blog</a></li>
{ "pile_set_name": "StackExchange" }
Q: Automounting SD card when inserted in Ubuntu I am trying to write a BASH script that automounts an SD card once it is inserted in the card reader, then move all pictures to a folder in the HDD and renaming each file to the date and time the picture was taken at. Any ideas how to achieve that? I am using Ubuntu 12.04 with no GUI Thanks :) A: Just to provide a full answer for you: Auto mount and copy over data Advanced Way (how you should do it) You will want to use UDEV rules that are specific to the UUID of your device (pardon my above type of udid). Lazy Way (how you could do it) Run a CRON Job to execute your script at a specified interval. You would obviously need the script to verify that the SD is plugged in and/or mounted before executing the rest). Rename / Move To get EXIF data $ identify -verbose imageFile.jpg That spits out loads of goodies, so let's suppose you want the creation date from that - let's filter that down: $ identify -verbose imageFile.jpg | awk '/exif:/' (or grep exif) Update: OP requested another method in the comments: You are asking to nest folders instead, for example November 20, 2012 would be ~/2012/11/20/*.jpg's Here is the script I made to try this, it works with EXIF now (the initial items for you were based on creation date, which would be floating as you move or copy the file). It's hosted on my blank site for you and I will post a screenshot too (since it's a lot of effort to make it formatted here). imageByEXIF.sh I would recommend you test this on a limited scale before implementing it. I put in Command Line Args for testing, so I was doing ~/Pictures to ~/Documents (although it prefers the full path)
{ "pile_set_name": "StackExchange" }
Q: Spring MockMvc Passing Nested Form Parameters I have the following form public class MyForm { private Account account; } public class Account { private String firstName; } How do I pass firstName parameter? (The following approach does not work) mockMvc.perform(post("/xyz") .param("account.firstName", "John")) .andExpect(model().hasErrors()) .andExpect(view().name("/xyz")) .andExpect(status().isOk()) A: Finally I resolved this issue. Since I am using standalone setup I had to define validator and messagesource. void setupTest() { MockitoAnnotations.initMocks(this) this.mockMvc = MockMvcBuilders.standaloneSetup(getController()) .setValidator(getValidator()) .alwaysDo(MockMvcResultHandlers.print()) .build() } private MessageSource getMessageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); messageSource.setUseCodeAsDefaultMessage(true); return messageSource; } private LocalValidatorFactoryBean getValidator() { def validator = new LocalValidatorFactoryBean() validator.setValidationMessageSource(getMessageSource()); return validator; }
{ "pile_set_name": "StackExchange" }
Q: Using Subversion with Visual Basic 6 My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions: What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...) Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.) A: I would agree that Tortoise SVN in Windows Explorer would be the best way to use SVN with VB6. The biggest change you will find migrating to SVN is the idea of "Check out" and "Check in" aren't exactly the same as "Update" and "Commit". . . thus, any IDE integration with VB6 is limited because VB6 supports MSSCCI, a check-out/check-in mechanism. I once used TamTam SVN (http://www.daveswebsite.com/software/tamtamsvn/index.shtml) with Visual Studio 2003, but stopped since I found it limiting. Merging/branching/blaming, etc. are very powerful features Tortoise SVN provides that weren't in TamTam. Tigris also has http://svnvb6.tigris.org/, but I have not tried it. Again, while you quite possibly get an IDE to work with VB6, I would not recommend it since the greatest strength of migrating to SVN is to break the Source Safe philosophy of check-in/check-out. A: Since Subversion uses an update/edit/commit cycle (rather than checkin/checkout), you will need to be especially careful with binary files. Most forms in VB6 consist of two files: MyForm.frm and MyForm.frx. The *.frx files are binary, and thus cannot be merged. Given that, I would set up Subversion to require "locking" on .frx files. This means that only one person can check the file out at a time. By doing so, you will enforce that only one developer can modify these files at a time, and it is always clear who that person currently is. If you don't do this, you are setting yourself up for some major headaches. A: Depending how much you're planning to do on these legacy projects I would consider not switching. I would really advise you to switch to SVN. I know of a few projects that lost source code because the VSS database became corrupted. I think there are tools that perform the migration from SourceSafe to SVN. (Yes-- a quick Google search confirmed it.) That way you wouldn't be losing the revision history.
{ "pile_set_name": "StackExchange" }
Q: Routing error in devise gem? I have updates my route.rb like:- devise_for :authorizes devise_scope :authorizes do get '/alogin' => 'devise/sessions#new' get '/alogout' => 'devise/sessions#destroy' end devise_for :hrs devise_scope :hrs do get '/hlogin' => 'devise/sessions#new' get '/hlogout' => 'devise/sessions#destroy' end devise_for :employes devise_scope :employes do get '/elogin' => 'devise/sessions#new' get '/elogout' => 'devise/sessions#destroy' end ERROR Could not find devise mapping for path "/alogin". This may happen for two reasons: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user]` A: When you use devise_scope, you should use singular for your model, i.e. :authorize (not :authorizes) Just try the following code: devise_for :authorizes devise_scope :authorize do get '/alogin' => 'devise/sessions#new' get '/alogout' => 'devise/sessions#destroy' end devise_for :hrs devise_scope :hr do get '/hlogin' => 'devise/sessions#new' get '/hlogout' => 'devise/sessions#destroy' end devise_for :employes devise_scope :employe do get '/elogin' => 'devise/sessions#new' get '/elogout' => 'devise/sessions#destroy' end
{ "pile_set_name": "StackExchange" }
Q: Folium of Descartes How to fill region on Folium of Descartes like this: Here is my codes: \documentclass[10pt]{article} \usepackage{pstricks-add} \usepackage{pst-func} \pagestyle{empty} \begin{document} \begin{figure}[!ht] \centering \psset{algebraic=true,dimen=middle,dotstyle=o,linewidth=0.8pt,arrowsize=3pt 2,arrowinset=0.25,unit=4} \begin{pspicture*}(-.5,-.5)(2,2) \psaxes[linecolor=gray,xAxis=true,yAxis=true,labels=none,ticks=none]{->}(0,0)(-.5,-.5)(2,2) \psplotImp[linecolor=blue,linewidth=1.5pt,plotpoints=500](0,0)(2,2){y^3-3*x*y+x^3} \end{pspicture*} \caption{Folium Descartes} \end{figure} \end{document} A: You can fill if you use \parametricplot: \documentclass[10pt,x11names]{article} \usepackage{pstricks-add} \usepackage{auto-pst-pdf} \pagestyle{empty} \begin{document} \begin{figure}[!ht] \centering \psset{algebraic=true,dimen=middle,dotstyle=o,linewidth=0.8pt,arrowsize=3pt 2,arrowinset=0.25,unit=3,plotpoints=2000} \begin{pspicture*}(-2,-2)(2,2) \psset{linecolor=SteelBlue4, linewidth=1.2pt} \pscustom[fillstyle=solid, fillcolor=lightgray!25!LightSteelBlue2!10!]{ \parametricplot{-0.99}{0}{3*t/(1 + t^3) | 3*t^2/(1 + t^3)} \parametricplot{-600}{-1.01}{3*t/(1 + t^3) | 3*t^2/(1 + t^3)} } \pscustom[fillstyle=solid, fillcolor=LightSteelBlue2!25! ]{ \parametricplot{0}{200}{3*t/(1 + t^3) | 3*t^2/(1 + t^3)} } \psline[linewidth=0.4pt, linecolor=black](-2.5; 45)(2.5 ; 45) \psline[linewidth=0.4pt, linecolor=black](-2,1)(2,-3) \psaxes[linecolor=gray,xAxis=true,yAxis=true,labels=none,ticks=none]{->}(0,0)(-2,-2)(2,2) \end{pspicture*} \caption{Folium of Descartes} \end{figure} \end{document} A: Done with mfpic, a LaTeX interface to MetaPost. To draw the folium you can use the cartesian form directly, thanks to the handy \levelcurve command of this package, so long as you write it as an inequation and you provide a point that verifies this inequation (here (1, 1)). The resulting curve is filled with the \gfill command with the desired color as an option. \documentclass{standalone} \usepackage[metapost]{mfpic} \setlength{\mfpicunit}{1cm} \opengraphsfile{\jobname} \begin{document} \begin{mfpic}[2]{-0.5}{2}{-0.5}{2} \draw\gfill[blue+green]\levelcurve{(1, 1), 0.01}{y**3 - 3x*y + x**3 < 0} \doaxes{xy} \end{mfpic} \closegraphsfile \end{document} To be compiled first with (PDF)LaTeX, then with MetaPost, and finally with (PDF)LaTeX. The result is as follows: A: In Metapost, you could just make the folium a closed path and fill it. I've used the (rather simpler) polar form of the equation below. prologues := 3; outputtemplate := "%j%c.eps"; beginfig(1); u := 2cm; path xx, yy, folium; xx = (1/2 left -- 2 right) scaled u; yy = (1/2 down -- 2 up) scaled u; drawarrow xx withcolor .4 white; drawarrow yy withcolor .4 white; folium = (origin for theta=1 step 1 until 89: -- (3*sind(theta)*cosd(theta)/(sind(theta)**3+cosd(theta)**3),0) rotated theta endfor -- cycle) scaled u; fill folium withcolor .9[blue,white]; draw folium withcolor .67 blue; endfig; end. And here's a fuller version, with the equation moved to a function, and showing how to extend the folium and pick out the loop as a sub path of it. prologues := 3; outputtemplate := "%j%c.eps"; beginfig(2); u := 2cm; path xx, yy, folium, loop, asymptote; xx = (2 left -- 2 right) scaled u; yy = (2 down -- 2 up) scaled u; drawarrow xx withcolor .4 white; drawarrow yy withcolor .4 white; % "a" is the scale factor a = 1; vardef r(expr t) = right scaled (3*a*sind(t)*cosd(t)/(sind(t)**3+cosd(t)**3)) rotated t enddef; % define the folium with some wings b = 30; % should be less than 45 folium = (r(-b) for theta=1-b step 1 until 89+b: -- r(theta) endfor -- r(90+b)) scaled u; % define the loop to be the part from theta=0 to theta=90 loop = subpath(b,b+89) of folium -- cycle; % define an appropriate segment of the asymptote asymptote = ( xpart point 0 of folium, -xpart point 0 of folium-a*u) -- (-ypart point infinity of folium-a*u, ypart point infinity of folium ); % now draw them fill loop withcolor .9[blue,white]; draw folium withcolor .67 blue; draw asymptote dashed evenly; endfig; end.
{ "pile_set_name": "StackExchange" }
Q: How do I set an Ember.js select view's value when using objects for options? I'm having some trouble figuring out how to get Ember's select view to update the dom when using objects instead of strings. This example behaves how I would expect: http://jsfiddle.net/XZ9b7/ Using only an array of strings for values, setting the bound property's value to a new value by clicking the buttons will automatically update the dom and set the dropdown to the same value. When using objects in this example however: http://jsfiddle.net/pRBKt/ I tried setting the bound property's value to the id, value, and a copy of the option object itself, and I can't get it to affect the select view. I just need a way to set the value of a select view when using objects for options A: I've added an other button in your fiddle: <div><button onclick="App.someObject.set('letterSelection', App.someOptions.objectAt(0));">real a</button></div> http://jsfiddle.net/Sly7/BYjk6/#base I think you have to use the same object, but not a copy. So in your case you have to pick up the object from the array bound to the Ember.Select's content property. EDIT: jsfiddle using #each and {{action}}. I think it cleans up the template and the code. http://jsfiddle.net/Sly7/sCr8T/ <script type="text/x-handlebars"> {{view Ember.Select contentBinding="App.someOptions" selectionBinding="App.someObject.letterSelection" optionLabelPath="content.val" optionValuePath="content.id" }} {{App.someObject.letterSelection.val}} {{#each option in App.someOptions}} <div> <button {{action "updateSelection" target="App.someObject" context="option"}}>{{option.val}}</button> </div> {{/each}} </script> JavaScript: window.App = Ember.Application.create(); App.someObject= Ember.Object.create({ title: "Some Title", letterSelection: null, updateSelection: function(event){ var newSelection = event.context; this.set('letterSelection', newSelection); } }); App.someOptions = [ {'id':'id_a','val':'a'}, {'id':'id_b','val':'b'}, {'id':'id_c','val':'c'}, {'id':'id_d','val':'d'} ];
{ "pile_set_name": "StackExchange" }
Q: Proof of Fourier series Theorem (k-continuous derivatives) Here's the theorem: Theorem: If $f$ is periodic with Fourier coefficients $a_n,b_n$ and if the series $$\sum_{n=1}^\infty (|n^{k}a_n|+|n^{k}b_n|)$$ converges for some integer $k \geq 1$, then f has continuous derivatives $f',...,f^{(k)}$ whose Fourier series are differentiated series of $f$. $\blacksquare$ So we know that $f(x)=\sum_{n=0}^\infty a_ncos(nx)+b_nsin(nx)$ on the interval $[-\pi,\pi]$. What needs to be done next is proving that the derivative of our series $f$ converges uniformly on our interval. I know how to prove the inequality $$\sum_{n=1}^\infty [a_n(cos(nx))^{(h)}+b_n(sin(nx))^{(h)}] \leq \sum_{n=1}^\infty (|n^{h}a_n|+|n^{h}b_n|) \leq \sum_{n=1}^\infty (|n^{k}a_n|+|n^{k}b_n|)$$ for all $ h \in [1,k]$ via the Weierstrass M-Test. Using induction, is it sufficient to show $f'$ is uniformly convergent and work my way up from there to the $f^{(k)}$ case, where assume the convergence of the $(k-1)^{th}$ derivative of our series to be equal to $f^{(k-1)}$? Will that ultimately show that $$f^{(k)}(x)=\sum_{n=1}^\infty [a_n(cos(nx))^{(k)}+b_n(sin(nx))^{(k)}]?$$ If this is the case (which I'm almost positive it is based on the way uniform convergence is defined), then here is my attempt at a proof of this. If anyone could tell me if I did this even remotely correctly, I would quite grateful! Attempted proof: Consider $$f(x)=a_0 + \sum_{n=1}^\infty [a_ncos(nx)+b_nsin(nx)]$$ which is $2\pi$-periodic. Differentiating $f$, we obtain $$f'(x) \sim \frac{d}{dx}(\sum_{n=1}^\infty [a_ncos(nx)+b_nsin(nx)]).$$ Recalling that $a_n=\int_{-\pi}^{\pi}f(x)cos(nx)dx$ and $b_n=\int_{-\pi}^{\pi}f(x)sin(nx)dx$, it using integration by parts that $$a_n'=\int_{-\pi}^{\pi}f'(x)cos(nx)dx=nb_n$$ and $$b_n'=\int_{-\pi}^{\pi}f'(x)sin(nx)dx=-na_n$$ $$\implies f'(x) \sim \frac{d}{dx}(\sum_{n=1}^\infty [a_ncos(nx)+b_nsin(nx)])$$ $$=\sum_{n=1}^\infty [-na_nsin(nx)+nb_ncos(nx)]$$ $$\equiv \sum_{n=1}^\infty [a_n\frac{d}{dx}(cos(nx))+b_n\frac{d}{dx}(sin(nx))].$$ Let's show that $\sum_{n=1}^\infty [-na_nsin(nx)+nb_ncos(nx)]$ is uniformly convergent on $[-\pi,\pi]$, which will show that that our differentiated Fourier series converges to $f'$ on $[-\pi,\pi]$. Recall that $|cos(x)| \leq 1$ which extends to $|cos(nx)| \leq 1$ and $|sin(x)| \leq 1$ which extends to $|sin(nx)| \leq 1$. Thus, $$\sum_{n=1}^\infty [-na_nsin(nx)+nb_ncos(nx)]$$ $$\leq |\sum_{n=1}^\infty [-na_nsin(nx)+nb_ncos(nx)]|$$ $$\leq \sum_{n=1}^\infty |-na_nsin(nx)+nb_ncos(nx)|$$ $$\leq \sum_{n=1}^\infty [|-na_nsin(nx)|+|nb_ncos(nx)|]$$ $$\leq \sum_{n=1}^\infty (|na_n|+|nb_n|)$$ $$ \equiv \sum_{n=0}^\infty (|n^1a_n|+|n^1b_n|)]$$ so we see our series is uniformly convergent on $[-\pi,\pi]$ by the Weierstrass M-Test, which implies that $f'$ represents our series on $[-\pi,\pi]$ and we have proved the case of $k=1$. Now suppose $$f^{(k-1)}(x)=\frac{d^{(k-1)}}{dx^{(k-1)}}(\sum_{n=1}^\infty [a_ncos(nx)+b_nsin(nx)])$$ $$\equiv \sum_{n=1}^\infty [a_n\frac{d^{(k-1)}}{dx^{(k-1)}}(cos(nx))+b_n\frac{d^{(k-1)}}{dx^{(k-1)}}(sin(nx))]$$ on the interval $[-\pi,\pi]$. We have currently have, since we don't know if the k-th derivative of $f$'s Fourier series converges to $f^{(k)}$, $$f^{(k)} \sim \sum_{n=1}^\infty [a_n\frac{d^{(k)}}{dx^{(k)}}(cos(nx))+b_n\frac{d^{(k)}}{dx^{(k)}}(sin(nx))].$$ This part of the proof is actually proven in an older post on stackexchange, which I link here: "Proving that $\sum_{n=1}^\infty{[a_ncos(nx)]^{(m)}+[b_nsin(nx)]^{(m)}} \leq \sum_{n=1}^\infty{(|a_nn^m| + |b_nn^m|)}$" It follows, finally, that $$f^{(k)}=\sum_{n=1}^\infty [a_n\frac{d^{(k)}}{dx^{(k)}}(cos(nx))+b_n\frac{d^{(k)}}{dx^{(k)}}(sin(nx))]$$ on the interval $[-\pi,\pi]$, so by the Principle of Mathematical Induction, we see that $f$ has $k$-continuous derivatives given the conditions imposed. $$\blacksquare$$ A: The proof is correct but so wordy... How about this: There is a standard theorem in real analysis: if $\sum f_n'$ converges uniformly on some interval $I$ and $\sum f_n$ converges at some point of $I$, then $\sum f_n$ converges uniformly on $I$, its sum $f$ is differentiable, and $f'=\sum f_n'$. The hypotheses in 1 apply to $f_n(x)=a_n\cos nx+b_n\sin nx$, because of the estimate $$|f_n'(x)| = |-n a_n \sin nx + nb_n\cos nx| \le | n a_n \sin nx| + |nb_n\cos nx| \\ \le |n a_n|+|n b_n|$$ and the Weierstrass M-test. The case $k=1$ has been proved. The general case follows by induction.
{ "pile_set_name": "StackExchange" }
Q: Send Option in Android Application? I have a application that has a text field, something like a sample notepad application. I want to have send option where I need to create intent to send the text to all possible applications like gmail, sms, facebook, twitter, etc... and i also want the other way also. I mean when the user clicks on send from other application they need to see my application as a option to receive text . And In this operation if the application is a mail application for sending text to, example the gmail application, I want to have few files from my sd card attached to the mail. Please let me how to do this in my application. Thank you for your help and time. A: For registering your app as a receiver you have to use an intent as this: <intent-filter> <action android:name="android.intent.action.SEND" /> <data android:mimeType="text/plain" /> </intent-filter> About sharing look at the documentation: http://developer.android.com/reference/android/content/Intent.html You should wrap it in a chooser (createChooser(Intent, CharSequence)) example: Intent i=new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_SUBJECT, "hi"); i.putExtra(Intent.EXTRA_TEXT, "your data"); startActivity(Intent.createChooser(i, "example"));
{ "pile_set_name": "StackExchange" }
Q: Cocoa: Scaling a view down for master/detail Keynote-like app I’m new to Cocoa and am trying to create a very simple keynote clone. For my slides, in the detail view, I use an NSStackView comprised of Textfields set with NSAttributedString. This part works pretty well. My master section is where I have problems. I thought I could clone a “slide” View using archive/unarchive, add all the slides to an NSStaxkView and then somehow scale down the sidebar (master) slides. Problems I have: 1) for the life of me I can’t figure out how to scale the view down to 10% size. 2) I tried using NSBox to create the “card” effect in the sidebar that keynote uses, but am unable to render the view content inside an NSBox for some reason. Am I going about the architecture all wrong? Any general guidance? I’m currently reading through https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaBindings/Tasks/masterdetail.html A: As already mentioned in the comments the best way to mirror the detail view to the side bar is by capturing an image of the detail view to present it in the sidebar. Capturing should be triggered any time a change in the detail view has been applied. There are different possibilities to capture an image of a view and one of them is explained here. Get Image from CALayer or NSView (swift 3)
{ "pile_set_name": "StackExchange" }
Q: gmail api oauth two accounts possible issue I have been working on a grails demo site which covers various methods of using gmail api mail plugin to send emails using standard,multiple To recipients, html emails, inline image(s). As well as a method to override or use different gmail accounts. This can all be found here Whilst doing the tests I noticed a strange behaviour with oauth, it is explained on the bottom of the README on that provided link Unsure about this bit a little confusing as to how it works. lets say I generated client_secret.json under gmail account username Bob When for the very first email that needs to be confirmed via this site on a given account a one off process. During that 1 off process if i log in to gmail with another account of Bill The key is verified and emails then appear to come from bill@gmail.com Even though I had not visited / configured Bill's account to use the client_secret.json file. So in short if I generate a secret.json file from account1, when sending the very first email from that account. If I happen to be logged in from account2. The storedCredentials file generated by google (there on) the 'me' account becomes my 2nd account. Even though everything to generate the key etc was done on account1. Does it make sense is this normal behaviour or a bug ? A: The client_secret.json file only needs to be generated once per application. It is how the application identifies itself to Google, and generating it does not grant any API access to any accounts. The same client secrets file is used to perform the OAuth flow for all the users that want to grant the application access to their data.
{ "pile_set_name": "StackExchange" }
Q: Hardware to do i/o to and from external devices I've got a potential client who wants a database driven app, either in Java or Python driving MySQL or PostgreSQL, but we need to get input from an external machine, such that every time this external machine closes a microswitch, a value in the database gets decremented and it shows up on the app. Also, when that value in the database reaches zero, we want to turn on a light on the external machine until the operator does something in the GUI, and then we want to turn off the light. My client's proposed solution is to wire the microswitch into one of the keys on the keyboard and just avoid using that key for anything else (he suggested the F12 button), and to control the light by playing a sound file through the left channel to start it, and the right channel to stop it. That seems a little cheesy to me, especially the wires going into the keyboard - and not just cheesy, but also a potential source of hardware problems if the operator accidentally pulls out a wire. I'd much rather something that either went into the USB port or possibly an internal card, just to keep the wiring around the back and away from the operator. But since the client hopes to sell a lot of these, he wants to keep the price down. I realize this isn't strictly "programming", but it's to solve a problem in a program I'm writing. So I'm asking you: is there a cheap hardware device that would do what I want? A: Cheap hardware device: Arduino It's small, cheap, programmable, and very easy to learn how to program for (pretty much C++). It can interface with either USB or Serial depending on the board you get. It's the hardware hacker's wet dream when it comes to tinkering around with wierd projects that need to interface with a computer somehow. You could even wire up an LED for notifying the technician directly to the arduino. Pros: Very little hardware knowledge needed to complete your project. All the wiring for reading a switch and lighting an LED are on the arduino project's site. Cons: Learning how to interface your software with the Arduino Library might take a little bit of time. A: To expand on Marcelo's answer, in case you want to prototype this quickly, FTDI does make a standalone board, the UB232R, which is about US$20 in single quantities. You could use the CTS pin as an input (with an appropriate pullup, e.g. 10K) from your device to the PC. All you need besides one of these is a USB cable and a way to connect the board to your microswitch. (not sure whether a solderless breadboard would be appropriate / robust enough, but it's a quick & dirty solution since the UB232R has a DIP8 footprint) No external power supplies, no need to make a custom PC board, no need to program anything other than your PC, no need to learn any hardware drivers beyond the basic communication port services, assuming your PC's communication libraries include features to read the CTS pin status. edit: for an output, you can use the RTS pin. If you have more inputs and outputs than this, you'll want to think a little more carefully....
{ "pile_set_name": "StackExchange" }
Q: How to pass params to one component with routerLink? I ran into impossibility to pass/get params with routerLink. I have app.component.ts/html: <header></header> <router-outlet></router-outlet> <footer class="flux-container"> ... <a routerLink="/info/1" routerLinkActive="active">Privacy Policy</a> <a routerLink="/info/2" routerLinkActive="active">Terms & Conditions</a> ... </footer> and info.component.ts: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-info', templateUrl: './info.component.html', styleUrls: ['./info.component.css'] }) export class InfoComponent implements OnInit { order : number; constructor(private activatedRoute: ActivatedRoute) { } ngOnInit() { this.order = this.activatedRoute.snapshot.params.id; console.log('this.activatedRoute.snapshot.params ', this.activatedRoute.snapshot.params); } } routing.ts { path : 'info/:id', canActivate : [AccountGuard, AppEnter], pathMatch : 'full', component : InfoComponent }, by cliking /info/1 or /info/2 i can't get this.activatedRoute.snapshot.params.id and use it, only by refresh page. Just simple move. help please A: order$: Observable<string>; this.order$ = this.activatedRoute.paramMap.pipe(map(resp => resp.get("id")));
{ "pile_set_name": "StackExchange" }
Q: How to boot with customized image without the text to Console Autologin I want to customize the Raspbian OS in such a way that when boots no text is displayed on the screen but a custom image instead. What I have is web based application and I start it with chromium in kiosk mode. The raspberry boot to the console and starts x from ~/.bashrc (startx). Then the chromium runs in kiosk mode when X starts. I found a solution to this but it is not sufficient for my needs. By editing /boot/cmdline.txt some text can be pointed to console=tty3. However this is not only text that appears. When X server starts and when automatically loging to the console as user pi I also get some text displayed on the screen (1-2 sec). Also I get some texts when I use reboot or shutdown (when X stops). By using asplashscreen I can display customized image/video, but is not in the same way as default image when it is incorporated in the kernel. Thanks in advance! A: I resolved the problem in half. In order to display an image on the framebuffer console when raspberry pi boots you need to compile the kernel with your image. The default image is located at: ~/linux/drivers/video/logo/logo_linux_clut224.ppm You need to have your image in jpeg/png etc. then you need to use netpbm to convert the image to ppm. Use the following commands: convert logo.jpg logo.png pngtopnm /path/to/logo.png | ppmquant -fs 223 | pnmtoplainpnm > logo_linux_clut224.ppm Copy the new logo: cp /path/to/logo_linux_clut224.ppm ~/linux/drivers/video/logo/logo_linux_clut224.ppm Then compile the kernel. That will replace the default logo. However when the logo is on full screen then the text on boot will appear on top of it. I have managed to disable the kernel messages when the system boots in /boot/cmdline.txt. Anyway there is still little text that can appear on the screen when shutting down or booting to the console(starting x session). I'm looking to complete solution which will disable all text to the framebuffer console. If anyone has a solution to that please share!
{ "pile_set_name": "StackExchange" }
Q: Is single float assignment an atomic operation on the iPhone? I assume that on a 32-bit device like the iPhone, assigning a short float is an atomic, thread-safe operation. I want to make sure it is. I have a C function that I want to call from an Objective-C thread, and I don't want to acquire a lock before calling it: void setFloatValue(float value) { globalFloat = value; } A: In 32-bit ARM, the function above will be compiled to ldr r2, [pc, #0x??] ; to retrieve the address of globalFloat str r0, [r2] ; store value into globalFloat As there are 2 instructions, and the CPU is free to perform anything between them, but only the second instruction str r0, [r2] affects memory. Unless globalFloat is unaligned, the CPU can perform single-copy atomic write to it. The assignment can be non-atomic when the global pointer is unaligned. It is also non-atomic if you are writing to a larger structure e.g. CGRect. Being atomic is not enough for thread safety. Due to caching and instruction reordering, your change may not be visible to other CPU cores. You may need to insert an OSMemoryBarrier() to "publish" the change. Atomic operations are usually interesting when it involves compound operations (e.g. globalFloat += value). You may want to check out the built-in OSAtomic library for it. A: Yes, it will be atomic. On a 32-bit architecture, any store operation on a primitive datatype that is 32-bits or smaller (char, short, int, long, float, etc.) will be atomic.
{ "pile_set_name": "StackExchange" }
Q: does not name a type Possible Duplicate: Resolve circular dependencies in c++ What is forward declaration in c++? I have two classes A and B. I need to have a field in each which is a pointer to an object of the other class. I get "does not name a type" since the definition of the class is yet to appear. For example: class A{ B* b; } class B{ A* a; } gets me "B "does not name a type" at the second line. A: Use forward declarations: class B; class A { B* b; }; class B { A* a; }; This way you're telling the compiler that B is going to be declared later on and that it should not worry. See this for more info: Forward declaration
{ "pile_set_name": "StackExchange" }
Q: How to completely wipe and rebuild drupal menus? A while ago I found a cool blog post that detailed how to empty the menu tables, and rebuild the menu system with a drush php call, a necessity since the site will be unusable after emptying those mysql tables. This way, you could reset your menus like it was a new Drupal site. Can anyone detail this technique or do you have the link for that blog? A: I have been looking a while for a solution to the problem to rebuild Drupal menus until I stumbled upon a Drupal issue that helped me. My solution (in a php script) is the following: db_query("DELETE FROM {menu_links} WHERE module = 'system'"); db_query("DELETE FROM {menu_links} WHERE menu_name = 'management'"); menu_rebuild(); This could also be done by entering the queries through phpmyadmin or something alike: DELETE FROM {menu_links} WHERE module = 'system' DELETE FROM {menu_links} WHERE menu_name = 'management' And then rebuilding the menu structure. If you use the devel module, you can achieve that by visiting the page /devel/menu/reset. I you don't have the devel module, I'm not sure how to rebuild the menu structure. Don't forget to backup your database before you try this. A: I have answered this question here How do I call the menu_rebuild function in Drupal 7? It worked for me just fine.
{ "pile_set_name": "StackExchange" }
Q: XML Variables don't allow inspection in IntelliJ 11 Flex Debugger I recently upgraded to IntelliJ 11 and the version 10 debugger used to allow for E4X / XML debugging. I was able to expand the children and inspect elements/attributes of XML but now I can't get that to work. Has something changed/broken? Does anyone know how to fix it? A: Turns out that this was a configuration error in my IntelliJ project. I had to make sure to have the SDK set properly. I deleted the SDK I had set on this project and recreated it. Then I went into each module and set it to the correct SDK (not project sdk) and things started working.
{ "pile_set_name": "StackExchange" }
Q: gluLookAt glitch I drew an object consisting of 2 tangent spheres, which is itself tangent to a wall (schema below). Using gluLookAt(), I set the camera in x point (first sphere center), looking to y point (second sphere center), so practically I see along the wall. But then, I can see a bit inside the wall (some of ']'s). [ ] (x)[ ] (y)[ ] [ ] Does anyone know what the problem could be? Observation: if I move the spheres a bit further from the wall, the glitch disappears, however I don't understand why it is present when the spheres are very close to the wall. A: Sounds to me like it's a clipping artefact - how far away from the wall is the camera, and where is the near clip plane? If the clip-plane is far enough out to extend into the wall, the wall will be clipped and you will see through (or into) it.
{ "pile_set_name": "StackExchange" }
Q: Does it matter where I put the declaration of a variable? Suppose I have the following two examples, will there be any difference between putting the variable declaration outside of the loop VS inside the loop, especially performance wise? Note: A new object is always being created inside the loop. Method 1: foreach (string name in nameList) { Person person1 = new Person(); person1.fullname = name; } Method 2: Person person1 = null; foreach (string name in nameList) { person1 = new Person(); person1.fullname = name; } A: It's a micro-optimization. So no, performance wise, it doesn't really matter. Any difference in performance will be made irrelevant in practically all non-trivial programs. And it's entirely possible that an optimizer would convert the less efficient form to the more efficient form (don't ask me which is which). I'd prefer the first since it's slightly less code and limiting variable scope as much as possible is generally considered good practice. Actually, to be more similar to method 1, method 2 should look like this: Person person1 = null; foreach (string name in nameList) { person1 = new Person(); person1.fullname = name; } person1 = null; Because after the loop, person1 will still point to the object created in the last iteration, the garbage collector will only be able to free that object once person1 leaves scope or is assigned a different value (i.e. null). If this is in a terminating code block that doesn't do much else, it will leave scope at the end of the block, thus the null assignment is not really necessary.
{ "pile_set_name": "StackExchange" }
Q: Ada Access to parameterless procedure "wrong convention" I have the following binding: function atexit(proc : access Procedure) return Integer with Import, Convention => C; As well as the procedure: procedure Exiting is begin Put_Line("Exiting"); end Exiting; When I try to call it like: I : Integer := atexit(Exiting'Access); it fails with subprogram "Exited" has wrong convention however providing my own (incompatable) atexit which accepts a parameter, and modifying Exiting to use that same parameter, allows passing the procedure just fine. So it seems like the issue is passing a parameterless procedure as an access type. I've tried giving a named access type like type Procedure_Access is access Procedure; But the result is exactly the same. How can I pass a parameterless procedure then? A: You might have forgotten the Convention aspects in the declarations of Exiting and Procedure_Access. The following works in GNAT CE 2018: foo.c int _atexit(void (*f)(void)) { (*f)(); return 0; } main.adb with Ada.Text_IO; use Ada.Text_IO; with Interfaces.C; use Interfaces.C; procedure Main is type proc_ptr is access procedure with Convention => C; function atexit(proc : proc_ptr) return int with Import, Convention => C, Link_Name => "_atexit"; procedure Exiting with Convention => C; procedure Exiting is begin Put_Line("Exiting"); end Exiting; I : Integer := Integer (atexit (Exiting'Access)); begin Put_Line("atexit returned " & I'Image); end Main; default.gpr project Default is for Source_Dirs use ("src"); for Object_Dir use "obj"; for Main use ("main.adb"); for Languages use ("Ada", "C"); end Default; output Exiting atexit returned 0
{ "pile_set_name": "StackExchange" }
Q: Apache Lucene: Creating an index between strings and doing intelligent searching My problem is as follows: Let's say I have three files. A, B, and C. Each of these files contains 100-150M strings (one per line). Each string is in the format of a hierarchical path like /e/d/f. For example: File A (RTL): /arbiter/par0/unit1/sigA /arbiter/par0/unit1/sigB ... /arbiter/par0/unit2/sigA File B (SCH) /arbiter_sch/par0/unit1/sigA /arbiter_sch/par0/unit1/sigB ... /arbiter_sch/par0/unit2/sigA File C (Layout) /top/arbiter/par0/unit1/sigA /top/arbiter/par0/unit1/sigB ... /top/arbiter/par0/unit2/sigA We can think of file A corresponding to circuit signals in a hardware modeling language. File B corresponding to circuit signals in a schematic netlist. File C corresponding to circuit signals in a layout (for manufacturing). Now a signal will have a mapping between File A <-> File B <-> File C. For example in this case, /arbiter/par0/unit1/sigA == /arbiter_sch/par0/unit1/sigA == /top/arbiter/par0/unit1/sigA. Of course, this association (equivalence) is established by me, and I don't expect the matcher to figure this out for me. Now say, I give '/arbiter/par0/unit1/sigA'. In this case, the matcher should return a direct match from file A since it is found. For file B/C a direct match is not possible. So it should return the best possible matches (i.e., edit distance?) So in this example, it can give /arbiter_sch/par0/unit1/sigA from file B and /top/arbiter/par0/unit1/sigA from file C. Instead of giving a full string search, I could also give something like *par0*unit1*sigA and it should give me all the possible matches from fileA/B/C. I am looking for solutions, and came across Apache Lucene. However, I am not totally sure if this would work. I am going through the docs to get some idea. My main requirements are the following: There will be 3 text files with full path to signals. (I can adjust the format to make it more compact if it helps building the indexer more quickly). Building the index should be fairly fast (take a couple of hours). The files above are static (no modifications). Searching should be comprehensive. It is OK if it takes ~1s / search but the matching should support direct match, regex match, and edit distance matching. The main challenge is each file can have 100-150 million signals. Can someone tell me if such a use case can be easily addressed by Lucene? What would be the correct way to go about building a index and doing quick/fast searching? I would like to write some proof-of-concept code and test the performance. Thanks. A: i think based on your requirements the best solution would be a PoC with a given test set of entries. Based on this it should be possible to evaluate the target indexing time you like to achieve. Because you only use static informations it's easier, because do don't have to care about topics like NRT (near-real-time searches). Personally i never used lucene for such a big information set but i think lucene is able to handle this. How i would do it: Read tutorials and best practices about lucene, indexing, searching and understand how it works Define an data set for indexing lets say 1000 lines for each file Define your lucene document structure this is really important because based on this you will apply your searches. take care about analyzer tasks like tokanization if needed and how. If you need fulltext search care about a TextField. Write code for simple indexing Run small tests with indexing and inspect your index with Luke Write code for simple searching Define queries and your expected results. execute searches and check results. Try to structure your code. separate indexing and searching -> it will be easier to refactor.
{ "pile_set_name": "StackExchange" }
Q: Python find value of view state given source I am trying to write a program to decode view state given a url. I know similar programs exist but this is more of an excursive than a project. Given the html source of a page, how can I get the value of the view state form element. I started by doing this: def get_viewstate(html): i = html.index('id="__VIEWSTATE" value="') somedata = html[i+len('id="__VIEWSTATE" value="'):] But I couldn't figure out an efficient way to only retrieve the value of the element up to the end tag. What is the most efficient way to retrieve the value of this form element? A: Using lxml with css selector: import lxml.html root = lxml.html.fromstring(html) matched = root.cssselect('#__VIEWSTATE') if matched: value = matched[0].get('value') Using BeautifulSoup: from bs4 import BeautifulSoup soup = BeautifulSoup(html) matched = soup.select('#__VIEWSTATE') if matched: value = matched[0].get('value')
{ "pile_set_name": "StackExchange" }
Q: ASP.NET MVC jQuery UI Checkboxradio tick disapear after checked I'm doing an ASP.NET MVC website. Which needs a feature let admin set if the membership of each clubs member joined are valid still. After a bit survey, I figure jQuery UI Checkboxradio quite fit my demand. When I check the checkbox it seems fine, ticked and the background becomes blue. However, when I move the mouse out the tick disappears while the background remains blue. Then if I move the mouse over it, the tick will show up again but only when the cursor remains on the widget. I check the post value of viewmodel which is correct and if I comment //$("input[type=checkbox]").checkboxradio(); The original checkboxes work as expected.(tick won't disapear) So I think it should be a frontend problem. Here is the part of my View <div class="form-group"> @Html.LabelFor(model => model.ClubMultiChosen.Clubs, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @for (int i = 0; i < Model.ClubMultiChosen.SelectedClubs.Count; i++) { var memberships = Model.ClubMultiChosen.SelectedClubs; @Html.Label(@memberships[i].Club.Abbr, new { @for = $"cbxClub{i}" }) @Html.CheckBox($"ClubMultiChosen.SelectedClubs[{i}].IsActive", @memberships[i].IsActive, new { id = $"cbxClub{i}" }); } </div> </div> At the same page I have included bootstrap 3.3.7 bootstrap-chosen 1.0.0 jQuery 3.1.1 jQuery UI 1.12.1 And My mvc version is 5.2.3.0 Not sure if I provided enough info. Any suggestion or question will be appreciated! A: I figured it out myself. For some reason when it is checked(class=ui-state-active). It uses ui-icons_ffffff_256x240.png as background which is white yet the background of checkbox(span) is white as well, so it looks like the tick was disappeared. After I override it with #form1 .ui-state-active .ui-icon, #form1 .ui-button:active .ui-icon { background-image: url("/Content/themes/base/images/ui-icons_555555_256x240.png"); } It works as I expected.
{ "pile_set_name": "StackExchange" }
Q: Purchasing a Domain from a Domain Squatter A few years ago, I purchased a .org domain. Presumably, the .com version was taken by a domain squatter because it was registered the day after I registered it and it only hosts one of those typical ad pages. I recently decided that I want the .com version as well if it's cheap, and I'd like to know: What price do they typically charge, and are there any ways to get them to lower this price? A: If you're visiting the domain you want to buy, and it's hosting ads. IMMEDIATELY STOP VISITING IT. Domain squatters are able to determine value based on traffic. If the site is getting zero traffic and you come in and say you want to build a website about your pet cat on that domain, odds are good they'd be willing to sell it cheap to recoup the registration fee they paid for it. However if they are getting even a few clicks on the ads, showing regular traffic from you visiting it, and you make the mistake of saying you're going to build some huge awesome website that will make you millions, good luck getting it for anything less than $500. Keep in mind, the squatter is always willing to wait longer than you are for the deal to go through. Also odds are high about you being ripped off if not using a 3rd party to verify the transfer. If you're the unfortunately soul that purchased your domain through goDaddy and noticed your .com version is being squatted, odds are it's the goDaddy squatter team and you're in for a very very expensive situation to get it from them. I would just give up and look for a new domain unless you have some deep pockets. A: The price would depend on the greed of the domain owner and perceived value of the domain. I've seen instances in the past where domain squatters have demanded anything from £1,000 to £10,000 for a .co.uk domain (they cost £6 for two years). Needless to say we have found alternative domains. If you can prove a trademark on company name/product/brand it does change the game a little since you can legally take back a domain name that infringes on a trademark. However in practical terms it would cost a lot of time and money to release a domain that you felt was being held unethically by using your company name/branding in order to sell. If you care to read more search for "trademarks and domain names". Practical advice: it is likely the person holding the domain will demand an unrealistic price initially to test the water. Have a maximum price in mind before hand and never go over this value. Wait for the initial price demand from the domain owner and if it is in excess of your figure (almost certain to be), make your offer and wait a while. If they have no other offers on the table their greed may get the better of them and they may come back and accept the offer. Otherwise, get another domain name. It would be great to see domain squatters stopped, but unfortunately this is unlikely to happen any time soon.
{ "pile_set_name": "StackExchange" }
Q: How to put texts in image via WordCloud in Jupyter Notebook I have a problem about showing texts put in image via WordCloud in Jupyter Notebook. Here is my image shown below. The output of figure is based on the results of text in rectangle not showing in defined text in image. Here is the output How can I fix it? Here is my code snippet defined below. plt.figure(figsize=[15,15]) char_mask = np.array(Image.open("images/netflix.png")) image_colors = ImageColorGenerator(char_mask) wordcloud = WordCloud(stopwords=STOPWORDS,background_color = 'white', width = 1000, height = 1000, max_words =300, mask=char_mask).generate(' '.join(netflix_df['title'])) wordcloud.recolor(color_func=image_colors) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.title('Most Popular Words in Title',fontsize = 30) plt.show() A: If you want to put result inside word NETFLIX then create black NETFLIX on white background. It is easier to do it in any photo editor (like GIMP or Photoshop) (BTW: I added contour_width= and contour_color= to see if code found NETFLIX on image) Image: Result: Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from PIL import Image, ImageOps from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator netflix_df = pd.DataFrame({'title': ['King Kong', 'Rambo', 'Rambo II', 'Rambo III', 'James Bond',]}) text = ' '.join(netflix_df['title'] char_mask = np.array(Image.open("netflix.png")) # black NETFLIX on white background wordcloud = WordCloud(stopwords=STOPWORDS, background_color='white', #width=1000, #height=1000, max_words=300, mask=char_mask, contour_width=3, contour_color='steelblue', ).generate(text)) #image_colors = ImageColorGenerator(np.array(image)) #wordcloud.recolor(color_func=image_colors) plt.figure(figsize=[15, 15]) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.title('Most Popular Words in Title', fontsize=30) plt.show() Documentation: Masked wordcloud With your original image (red NETFLIX on black bacground) you can try to convert to grayscale and invert it. from PIL import Image, ImageOps image = Image.open("netflix.jpg") # red NETFLIX on white background image_gray = image.convert('L') image_invert = ImageOps.invert(image_gray) #image_invert.show() # it shows result char_mask = np.array(image_invert) #im = Image.fromarray(char_mask) #im.show() But original jpg image has many different values for red color and mask is not perfect. It needs more work - ie. filter colors in ranges. char_mask[ char_mask < 200 ] = 0 char_mask[ char_mask > 200 ] = 255 Result: Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from PIL import Image, ImageOps from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator netflix_df = pd.DataFrame({'title': ['King Kong', 'Rambo', 'Rambo II', 'Rambo III', 'James Bond',]}) text = ' '.join(netflix_df['title'] image = Image.open("netflix.jpg") # red NETFLIX on black background image_gray = image.convert('L') image_invert = ImageOps.invert(image_gray) #image_invert.show() char_mask = np.array(image_invert) char_mask[ char_mask < 200 ] = 0 char_mask[ char_mask > 200 ] = 255 #print(char_mask) #im = Image.fromarray(char_mask) #im.show() wordcloud = WordCloud(stopwords=STOPWORDS, background_color='white', #width=1000, #height=1000, max_words=300, mask=char_mask, contour_width=3, contour_color='steelblue', ).generate(text)) image_colors = ImageColorGenerator(np.array(image)) wordcloud.recolor(color_func=image_colors) plt.figure(figsize=[15,15]) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.title('Most Popular Words in Title',fontsize = 30) plt.show() BTW: if you create white NETFLIX on black background Then you can get Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from PIL import Image, ImageOps from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator netflix_df = pd.DataFrame({'title': ['King Kong', 'Rambo', 'Rambo II', 'Rambo III', 'James Bond',]}) text = ' '.join(netflix_df['title'] image = Image.open("netflix.jpg") # red NETFLIX on black background image_gray = image.convert('L') #image_gray.show() char_mask = np.array(image_gray) char_mask[ char_mask < 50 ] = 0 char_mask[ char_mask > 50 ] = 255 print(char_mask) #im = Image.fromarray(char_mask) #im.show() wordcloud = WordCloud(stopwords=STOPWORDS, background_color='white', #width=1000, #height=1000, max_words=300, mask=char_mask, contour_width=3, contour_color='steelblue', ).generate(text)) image_colors = ImageColorGenerator(np.array(image)) wordcloud.recolor(color_func=image_colors) plt.figure(figsize=[15,15]) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.title('Most Popular Words in Title',fontsize = 30) plt.show() BTW: to invert gray scale image you can also use char_mask = ~char_mask # invert gray scale
{ "pile_set_name": "StackExchange" }
Q: How can I merge and process multiple rows from a file to produce a report using perl I am new perl just tried with little messy code. cat input1.txt ##gff-version 2 ##source-version geneious 5.6.4 Xm_ABL1 Geneious CDS 1 168 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 169 334 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 335 628 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 629 901 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 902 985 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 986 1165 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 1166 1350 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious CDS 1351 1504 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 Xm_ABL1 Geneious BLAST Hit 169 334 . + . Xm_ABL1 Geneious extracted region 1 168 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="351297 -> 351464" Xm_ABL1 Geneious extracted region 169 334 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="371785 -> 371950" Xm_ABL1 Geneious extracted region 335 628 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="372554 -> 372847" Xm_ABL1 Geneious extracted region 629 901 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="374760 -> 375032" Xm_ABL1 Geneious extracted region 902 985 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="375230 -> 375313" Xm_ABL1 Geneious extracted region 986 1165 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="375992 -> 376171" Xm_ABL1 Geneious extracted region 1166 1350 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="376575 -> 376759" Xm_ABL1 Geneious extracted region 1351 1504 . + . Name=Extracted region from gi|371443098|gb|JH556762.1|;Extracted interval="376914 -> 377067" If input file containg (->) forward arrow.I want output like if($array[7]=~/.*interval=\"\d+ -> \d+\"$/gm){ $array[5]="+"; } cat output1.txt gi_371443098_gb_JH556762.1 gene 351297 377067 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 351297 351464 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 371785 371950 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 372554 372847 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 374760 375032 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 375230 375313 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 375992 376171 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 376575 376759 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 376914 377067 . + . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 ### cat output1.txt If input file containg (<-) reverse arrow. if($array[7]=~/.*interval=\"\d+ <- \d+\"$/gm){ $array[5]="-"; } gi_371443098_gb_JH556762.1 gene 351297 377067 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 351297 351464 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 371785 371950 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 372554 372847 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 374760 375032 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 375230 375313 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 375992 376171 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 376575 376759 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 gi_371443098_gb_JH556762.1 CDS 376914 377067 . - . Name=Xm_ABL1;created by=User;modified by=User;ID=w0IVHutPuN4H4FVDCg4sFVRaJjQ.1340919460469.4 ### I have tried with little messy code, as I am beginner. #usr/bin/perl; use strict; open(FH,"$ARGV[0]"); while(<FH>){ chomp $_; my @array=split("\t"); my $key="$array[2]-$array[0]-$array[1]-$array[2]-$array[3]"; if($array[1] eq "CDS"){ $cds_cnt{$key}++; $cds{$key}="$array[4]\t$array[5]\t$array[6]\t$array[7]"; } if($array[1] eq "extracted region"){ (my $pos1,my $pos2)=($array[7]=~/.*interval=\"(\d+) -> (\d+)\"$/gm); $extract_cnt{$key}++; $extract{$key}="$pos1\t$pos2"; } } foreach $i ( sort {$a<=>$b} keys %cds){ my $a=$i; #print "$i\n"; $a=~s/CDS/extracted region/g; if($cds_cnt{$i} == $extract_cnt{$a}){ #print "$i\t$cds{$i}\n$a\t$extract{$a}\n"; my @array=split /\-/,$i; my @pos=split "\t",$extract{$a}; print "$array[1]\t$array[2]\t$pos[0]\t$pos[1]\t$cds{$i}\n"; } } print "###"; Update What I need to modify in my code 1.To get value from the row of extracted region, (i.e array[7]=/gi|371443098|gb|JH556762.1|/) it can be any value, add underscore to it (i.e gi_371443098_gb_JH556762.1) and print in array[0] in the output1.txt as shown. 2.Add new line as first row while printing (gi_371443098_gb_JH556762.1 gene), in column 3 get starting value of CDS (i.e 351297) and get ending value of CDS in column 4 (i.e 377067) and print as in the first row as shown in ouput1.txt 3.If /extracted region/ block-all rows for.e.g.Extracted interval="351297 -> 351464" (i.e forward arrow) print array[5] as "+" symbol including gene header in the output. if e.g.Extracted interval="351297 <- 351464" (reverse arrow) print array[5] as "-" symbol including gene header in the output. A: It looks like what you're trying to achieve is to merge the details from the line labelled CDS with the matching line labelled extracted region, and then print the merged results with a leading summary header, based on some minimum and maximum values, grouped by Name. Is that correct? I'm going to assume that what you call $array[0] (Xm_ABL1 Geneious) and $array[2] (169, 335 etc) is sufficient to marry them together, but that's not very clear in your example. Your first question is just a regexp, which I think you've got the general hang of. I think the issue is how you've gone about capturing your data. To do the second thing you ask, capture the hi and lo values in your first pass, and store them. I wasn't planning on writing a complete solution, yet here it is... use strict; use warnings; my $metadata = {}; # hashref to store CDS info in.. my $group = {}; # hashref to store summary/detail in.. my $arrow = { "->" => '+', "<-" => '-' }; # decode arrow to pos/neg open(FH,"$ARGV[0]"); while(<FH>){ chomp; next if /^#/; my @array=split("\t"); my $key = join(":", $array[0], $array[2]); if ($array[1] =~ /CDS/){ $metadata->{$key} = $array[7]; } if ($array[1] =~ /extracted region/){ #assert CDS already processed.. die "No CDS record for $key!\n" unless $metadata->{$key}; (my $label = $array[7]) =~ s/.*region from (.*)\|;.*/$1/; $label =~ s/\|/_/g; $group->{$label} ||= { #seed summary if not exists pos1 => 1e10, pos2 => 0, metadata => $metadata->{$key}, sequences => [], }; (my $pos1, my $arr, my $pos2) = ($array[7]=~/.*interval=\"(\d+) (<?->?) (\d+)\"$/gm); # capture hi/lo values for group $group->{$label}->{pos1} = $pos1 if $pos1 < $group->{$label}->{pos1}; $group->{$label}->{pos2} = $pos2 if $pos2 > $group->{$label}->{pos2}; # push this sequence onto the group's array push(@{ $group->{$label}->{sequences} }, [ $pos1, $pos2, $arrow->{$arr} ]); } } for my $gene (sort keys %{ $group }){ #write out header printf "%s\t%s\t%d\t%d\t.\t%s\t.\t%s\n", $gene, 'gene', $group->{$gene}->{pos1}, $group->{$gene}->{pos2}, $group->{$gene}->{sequences}->[0]->[2], $group->{$gene}->{metadata}; foreach my $sequence ( @{ $group->{$gene}->{sequences} } ){ # write out details printf "%s\t%s\t%d\t%d\t.\t%s\t.\t%s\n", $gene, 'CDS', $sequence->[0], $sequence->[1], $sequence->[2], $group->{$gene}->{metadata}; } } print "###\n"; I hope that's sufficiently commented to make sense. Written like this, it will be a lot easier to maintain if you have to come back and modify it after six months has passed. UPDATE I've modified this code following the 4th comment. The $array[7] regexp block now captures the value of $array[5] and stores it in the sequence arrayref. UPDATE #2 Note use of $arrow hashref to decode -> and <- to the symbols you require. (line 6) Gene header shows + or - based on value in 3rd field of first sequence. There's an assumption that all sequences for a gene have the same direction. (11 lines from end) I think we've strayed off the Q&A highway and into the Free Software Development Bureau now. What I've written is not complex code, it has comments and structure. It's time for you to come to grips with the logic of it. And up-vote my answer.
{ "pile_set_name": "StackExchange" }
Q: Strict convex function? I try to prove that $g(x)= K |x|^2/2 + z(x)$ is strictly convex, given that $z(x) \geq - m(1 + |x|^p)$ with $m \geq 0$, $0 \leq p \leq 2$, forall $x \in \mathbb{R}^n$, provided $K$ is sufficiently large. How to show that? A: The conclusion is false. For example, let $n=1$ and $z(x)=x^2(1+\sin x)\ge 0$. Then no matter how large $K$ is, $f''((2k+\frac{1}{2})\pi)<0$ when $k\in\mathbb{N}$ is large.
{ "pile_set_name": "StackExchange" }
Q: Crypto++ and garbage at end of string after performing AES decryption I am integrating Crypto++ into my C++ app and so far it's working, almost. The encryption works perfect. The output matches what I would expect it to. However, when I go to decrypt, it's adding square characters on the end. Here is my Encrypt function: string Encryption::EncryptAES(const string &text, const string &key) { string cipher; AES::Encryption aes((byte *) key.c_str(), 32); ECB_Mode_ExternalCipher::Encryption ecb(aes); StreamTransformationFilter encrypt(ecb, new StringSink(cipher), StreamTransformationFilter::ZEROS_PADDING); encrypt.Put(reinterpret_cast<const unsigned char *>( text.c_str()), text.length() + 1); encrypt.MessageEnd(); return Base64::Encode(cipher); } Here is my Decrypt function: string Encryption::DecryptAES(const string &text, const string &key) { string decoded; Base64::Decode(text, decoded); string decrypted; AES::Decryption aes((byte *) key.c_str(), 32); ECB_Mode_ExternalCipher::Decryption ecb(aes); StreamTransformationFilter decrypt(ecb, new StringSink(decrypted), StreamTransformationFilter::ZEROS_PADDING); decrypt.Put(reinterpret_cast<const unsigned char *>( decoded.c_str()), decoded.length()); decrypt.MessageEnd(); return decrypted; } I'm using the following for the Base64 Encode/Decode: Base64 Encode/Decode Here is the code I call to encrypt/decrypt: string encryptedPass = EncryptAES(value, key); cout << "Encrypted Text: " << encryptedPass << endl; string decryptedPass = DecryptAES(encryptedPass, key); cout << "Decryped Text: " << decryptedPass << endl; Here is the output: When I copy and past the output into Notepad++, it's a bunch of spaces. I have a feeling it deals with the ZEROS_PADDING, but I need that in there to match our other applications that we are using. I'm not sure how to actually try to fix this. Thoughts? A: Based on the comments I was able to figure out what was at the end of the string. I knew it had to deal with zero padding, but due to being new at C++, I didn't fully understand what was going on. I ran this to get the ascii value of the character: for(char& c : s){ cout << "Char:" << (int)c << endl; } This resulted in the following at the end of the string: Char:0 Char:0 Char:0 Char:0 Char:0 Char:0 And according to the ASCII table it's NUL So, the simple solution for this is to do this: std::string(value.c_str());
{ "pile_set_name": "StackExchange" }
Q: Update Data Source and DataSet reference for SSRS 2012 Deployment from C# EDIT: I think I can simplify this question a bit to ask for only what is needed to know: I am working with C# using the SSRS 2010 Web Service: 'ReportService2010.asmx' http://technet.microsoft.com/en-us/library/ee640743.aspx I can use the method 'CreateDataSource' to create a Datasource on an instance of an SSRS Server http:// (servername)/ReportServer. I can also use the method 'CreateCatalogItem' to create a report on a server from referencing a project's RDL local file to serialize it to a byte array and then pass that as a 'Definition' to the method to create it on the server. Now everything I do works with a caveat, and a major one. I can only deploy everything to the same folder. If I deploy a Data Source to say the 'Data Sources' folder and then a report to say: 'Test Reports', the report does not know it has a shared data source to reference at a different location. So I dug a little at the technet articles and have tried to 'GetItemDataSources' method but it only gives a name and a type for the ReportingService2010.DataSource return type. Does anyone know the method to link up a 'Report' or 'Dataset's CatalogItem property of 'DataSource', so it points to a reference in a different folder on the SSRS Server when deploying? There has to be a way to do it as I know I can deploy from Business Intelligence Development Studio and it can do this. A: I've had similar issues when deploying report files; when deploying through rs.exe or code you run into these issues where reports lose their link to a Data Source. We solved this by explicitly pointing the report to the server-side Data Source immediately after being deployed by our application; is this similar to what you're trying to do? Anyway, here's the slightly adapted code we use in our report deployment application: static void SetReportDataSource(string reportPath) { string dsPath = CombinePath(DataSourcePath, DataSourceFolder, DataSourceName); DataSourceReference dsRef = new DataSourceReference() { Reference = dsPath }; DataSource ds = new DataSource(); ds.Item = dsRef as DataSourceDefinitionOrReference; ds.Name = DataSourceName; var rptDataSources = Server.GetItemDataSources(reportPath); foreach (var rptDs in rptDataSources) { Server.SetItemDataSources(filePath, new DataSource[] { ds }); } } So, basically we have variables that define information like the Data Source name, Data Source location on server, and the same for a report. They can be in different folders. Based on this, we create a new reference to a Data Source and then repoint the report to this using SetItemDataSources. This sorted out the Data Source issue for me, anyway. Not sure about Shared Datasets and how they handle all of this, but hopefully this will be of some help. Also, just thought that this would be using the ReportService2005 endpoint, but it's probably not too different for ReportService2010. Edit: For the paths mentioned here, these are relative to the server, e.g. /Reports/. You don't need the fully qualified name as you define the Url property of the ReportService2010 object which contains the destination.
{ "pile_set_name": "StackExchange" }
Q: Codeginiter: Get the a URI segment of a page and add it to the URL of its redirect page So I have these 2 pages IF the URL of page1 is: http://localhost/project/page1/page1/5 And there's a link in that page that redirects to page2 with the URL: http://localhost/project/page2/page2/2 (its 3rd segment - 2 is from dropdown value selected) Is it possible to make the redirected page - page2 with a URL like this: http://localhost/project/page2/page2/5/2 -so that I could do something with page1's value, like querying dynamically in the database. VIEW in page1: <div class="form-group form-inline"> <select id="p2_val"> <?php foreach($v_p2 as $row) { ?> <option value="<?php echo base_url('page2/page2/').$row->p2_val;?>"> <?php echo $row->p2_num; ?> </option> <?php } ?> </select> <input class="SubmitButton" type="submit" name="SUBMITBUTTON" value="Submit" /> </div> Controller in page1: class Page1 extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('page1_model'); } public function page1(){ if($this->session->userdata('logged')){ $this->load->model('page1_model'); $data["v_p2"] = $this->page1_model->v_p2($this->session->userdata('user_id')); $this->load->view('pages/page1', $data); $this->load->view('templates/footer'); } } Controller of page2: class Page2 extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('page2_model'); } public function page2(){ if($this->session->userdata('logged')){ $this->load->model('page2_model'); $data["get_p2"] = $this->page2_model->get_p2($this->session->userdata('user_id')); $this->load->view('pages/page2', $data); $this->load->view('templates/footer'); } } A: I changed view of page1 into: <option value="<?php echo base_url('page2/page2/').$row->p1_val.'/'.$row->p2_val;?>"> <?php echo $row->p2_num; ?> </option> No change in the controllers, just worked around with models by using: $this->uri->segment(); - Most changes were then in the db queries I made. - Since I added additional segment in page2, I added " ../ " to the paths of the assets. sample - model for page2: function v_p2($data){ $p1_val = $this->uri->segment(3); $p2_val = $this->uri->segment(4); //DO smth with $p1_val & $p2_val //These values were used for querying }
{ "pile_set_name": "StackExchange" }
Q: How to provide reasonable default bounds for Google Places API's getAutocompletePredictions() method? I am using this method: Places.GeoDataApi.getAutocompletePredictions(googleApiClient, query, bounds, AutocompleteFilter.create(null)) It requires a LatLntBounds object with a northeast and a southwest LatLng points as the bounds of the query, but I dont want to provide any. Tried with null, but got a null pointer exception Tried with: LatLng southWest = new LatLng(85, -180); LatLng northEast = new LatLng(-85, 180); LatLngBounds bounds = new LatLngBounds(southWest, northEast); but got IllegalArgumentException: southern latitude exceeds northern latitude (85.0 > -85.0) So how do I: a) get the current user location's reasonable bounds b) get the world bounds so that I can kickstart this API A: It requires the bounds to work. Just create them. import com.google.maps.android.SphericalUtil; final double HEADING_NORTH_EAST = 45; final double HEADING_SOUTH_WEST = 215; final double diagonalBoundsSize = 1000; // 1km LatLng centre = new LatLng(85, -180); LatLng northEast = SphericalUtil.computeOffset(centre, diagonalBoundsSize / 2, HEADING_NORTH_EAST); LatLng southWest = SphericalUtil.computeOffset(centre, diagonalBoundsSize / 2, HEADING_SOUTH_WEST); LatLngBounds bounds = new LatLngBounds(southWest, northEast);
{ "pile_set_name": "StackExchange" }
Q: Can micronaut work with gateways like zuul or spring cloud gateway? The main issue is the compatibility of the registry. If not, how to deal with gateway issues? A: Depends what you mean. You can use Zuul or Spring Cloud Gateway as your gateway solution in front of a Micronaut application. Ultimately a Micronaut application will register itself with Eureka or Consul and then Zuul or SCG will discovery the service via service discovery and route requests to the Micronaut app over HTTP.
{ "pile_set_name": "StackExchange" }
Q: Transfer function of boost converter When I have gone through some books I have found the expression of the DC Gain of the the boost converter in current mode is given by H0=(RL/Ri)*1/(2*M+(RL*Tsw)/(L*M^2)*(1/2+Sa/Sn)) But I did not find out what is the expression of the M, please can you give me the expression of this M and from where does it come?? Here is attached the final expression given by OnSemiconductor A: The answer of Verbal Kint makes most sense. If you multiply the DC gain on slide 35 by \$ \frac{R_L}{R_L} \$ $$H_0 = \frac{k_0-k_i}{g_f - (g_0+g_i) - g_r - \frac{1}{R_L} } \frac{R_L}{R_L} $$ and substitute the equations given in slide 27 into the term \$k_0-k_i\$, then \$H_0\$ evaluates to $$H_0 = R_L \frac{\frac{1-D}{R_i}}{g_f R_L - (g_0+g_i) R_L - g_r R_L - 1 } = \frac{R_L}{R_i} \frac{1-D}{g_f R_L - (g_0+g_i) R_L - g_r R_L - 1 } $$ Using \$M=\frac{1}{1-D}\$ it looks more and more to the DC gain \$H_0\$ given on slide 50: $$H_0 = \frac{R_L}{R_i} \frac{1}{M (g_f R_L - (g_0+g_i) R_L - g_r R_L - 1) } $$
{ "pile_set_name": "StackExchange" }
Q: jquery drag drop - draggable is not enabled after drop outside designated drop areas & disabling designated areas after drop is completed I need help with 2 issues: 1) draggability is disabled if a draggable element didn't drop on one of designated drop areas (e.g. if a user released left-mouse button unintentionally). In all other cases drag and drop works as expected: clone is created and is available for dragging and dropping into any of designated drop areas. I tried to "disabled: false" draggable but it didn't help. 2) only one answer should be accepted/allowed per "dropContainer" (e.g. .dropTarget_m_1_1_a should accept only one drop regardless the answer is correct or wrong). I tried to provide a more specific name via associative array (linking dropContainer and specific drop elements' id's) with no luck. I can hardcode it to disable a specific class i.e. $(".dropTarget_m_1_1_a").droppable("disable"); Unfortunately I need iteration e.g. going through each .dropTargetxxxxx class or each dropContainerxxx id. Thank you very much in advance!!! That's what I have so far: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.js"></script> <script src="js/jquery-ui.js"></script> <style> ul { list-style-type: none; } li.draggable { list-style:none; } #button_list_1a li { display: inline-block; list-style-type: none; width: 60px; height: 10px; margin-top: 70px; } #m_1_l_3 { position: absolute; top: 25px; left: 80px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:blue; } #m_1_l_2 { position: absolute; top: 40px; left: 80px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:red; } #m_1_l_1 { position: absolute; top: 55px; left: 80px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:yellow; } #m_2_l_3 { position: absolute; top: 25px; left: 210px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:blue; } #m_2_l_2 { position: absolute; top: 40px; left: 210px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:red; } #m_2_l_1 { position: absolute; top: 55px; left: 210px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:yellow; } #m_3_l_3 { position: absolute; top: 25px; left: 350px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:blue; } #m_3_l_2 { position: absolute; top: 40px; left: 350px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:red; } #m_3_l_1 { position: absolute; top: 55px; left: 350px; height: 15px; width: 110px; display:flex; align-items:center; z-index: 10; opacity: 0.3; -moz-opacity: 0.3; filter: alpha(opacity=30); background-color:yellow; } </style> </head> <body> <div id="dropContainer_m_1"> <div id="m_1_l_3" class= "dropTarget_m_1_1_a droppable_1_a"></div> <div id="m_1_l_2" class= "dropTarget_m_1_1_a droppable_1_a"></div> <div id="m_1_l_1" class= "dropTarget_m_1_1_a droppable_1_a"></div> <div id="dropContainer_m_2"> <div id="m_2_l_3" class= "dropTarget_m_2_1_a droppable_1_a"></div> <div id="m_2_l_2" class= "dropTarget_m_2_1_a droppable_1_a"></div> <div id="m_2_l_1" class= "dropTarget_m_2_1_a droppable_1_a"></div> <div id="dropContainer_m_3"> <div id="m_3_l_3" class= "dropTarget_m_3_1_a droppable_1_a"></div> <div id="m_3_l_2" class= "dropTarget_m_3_1_a droppable_1_a"> </div> <div id="m_3_l_1" class= "dropTarget_m_3_1_a droppable_1_a"></div> </div> <ul id = "button_list_1a"> <!--// answers 1 a --> <li class = "button_small draggable_1_a" id = "image#1" draggable="true">Image#1</li><!-- --><li class = "button_small draggable_1_a" id = "image#2" draggable="true">Image#2</li><!-- --><li class = "button_small draggable_1_a" id = "image#3" draggable="true">Image#3</li> </ul> <script> $(document).ready(function a_1_dnd(){ $(".draggable_1_a").draggable({ cursorAt: { top: 5, left: 30 }, cursor : 'pointer', revert : 'invalid', opacity: 0.35, helper: function (event) { var id = $(this).attr('id'); var ret = $(this).clone(); ret.attr('dragId', id); console.log('dragId: ', ret.attr('dragId')); return ret; }, start : function (event, ui) { }, // end start drag : function (event, ui) { }, // end drag stop : function(event, ui){ ui.helper.clone().appendTo ($(this).parent()); ui.helper.clone().disabled; } }); $(".droppable_1_a").droppable({ accept: ".draggable_1_a", tolerance: 'pointer', drop: function (event,ui) { var draggable_id = ui.draggable.attr("id"); var droppable_id = $(this).attr("id"); var correctAnswer = { m_1_l_1 : "image#1", m_1_l_3 : "image#1", m_2_l_2 : "image#2", m_3_l_1 : "image#3" }; if(correctAnswer[droppable_id] === draggable_id) { console.log(ui); $(ui.draggable).attr('id', $(ui.helper).attr('id')); console.log(droppable_id); localStorage.totalCorrectAnswers = parseFloat(localStorage.totalCorrectAnswers) + 1.0; } else { console.log(ui.helper.attr( "dragId" )); console.log("Wrong!!!"); console.log(droppable_id); } } }); }); </script> </body> </html> A: The first thing you should look at is a clone you create. After «mouseup» event in the area which is not area for dropping the clone is moving on the place where original droppable element is. And the clone is the thing which prevents your element from being clicked. In fact, you click on the clone, not on the droppable element So I would recommend you to attach the clone to the droppable element which means to move these lines ui.helper.clone().appendTo ($(this).parent()); ui.helper.clone().disabled; to the «drop» event handler of the droppable element instead of draggable. Thus you will create a clone only if draggable element was dropped in the one of three containers. Take into account that you will need to modify your CSS to get the clone visible. The second issue might me solved in the same handler, you should put something like $(this).parent().find(".droppable_1_a").droppable({ disabled: true }); there. This line will disable all droppable elements in one parent container
{ "pile_set_name": "StackExchange" }
Q: Create an "all-in-one" function using DS in C# In my web app I use several asmx (Web Services) from the same provider, they have one for this, other for that, but all require a SOAP Header with Authentication. It is simple to add the Authentication: public static SoCredentialsHeader AttachCredentialHeader() { SoCredentialsHeader ch = new SoCredentialsHeader(); ch.AuthenticationType = SoAuthenticationType.CRM5; ch.UserId = "myUsername"; ch.Secret = apUtilities.CalculateCredentialsSecret( SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword"); return ch; } The problem is this SoCredentialsHeader come (derivation) from ONE webservice and I need to add the same code to the others, like: public static wsContact.SoCredentialsHeader AttachContactCredentialHeader() { wsContact.SoCredentialsHeader ch = new wsContact.SoCredentialsHeader(); ch.AuthenticationType = wsContact.SoAuthenticationType.CRM5; ch.UserId = "myUsername"; ch.Secret = apUtilities.CalculateCredentialsSecret( wsContact.SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword"); return ch; } public static wsDiary.SoCredentialsHeader AttachDiaryCredentialHeader() { wsDiary.SoCredentialsHeader ch = new wsDiary.SoCredentialsHeader(); ch.AuthenticationType = wsDiary.SoAuthenticationType.CRM5; ch.UserId = "myUsername"; ch.Secret = apUtilities.CalculateCredentialsSecret( wsDiary.SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword"); return ch; } Is there a way to implement a design pattern in order to use only one function but that suits all webServices? sometimes I see the T letter, is this a case for that? if yes, how can I accomplish such feature? P.S. I could pass an enum and use a switch to check the enum name and apply the correct Header but everytime I need to add a new WebService, I need to add the enum and the code, I'm searcging for an advanced technique for this. Thank you. A: Create a file called whatever.tt (the trick is the .tt extension) anywhere in your VS solution and paste the following code: using System; namespace Whatever { public static class Howdy { <# string[] webServices = new string[] {"wsContact", "wsDiary"}; foreach (string wsName in webServices) { #> public static <#=wsName#>.SoCredentialsHeader AttachContactCredentialHeader() { <#=wsName#>.SoCredentialsHeader ch = new <#=wsName#>.SoCredentialsHeader(); ch.AuthenticationType = <#=wsName#>.SoAuthenticationType.CRM5; ch.UserId = "myUsername"; ch.Secret = apUtilities.CalculateCredentialsSecret(<#=wsName#>.SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword"); return ch; } } <# } #> } Then watch as a whatever.cs magically appears with the desired code snippets.These are called T4 templates for code generation in VS. You'll want to turn these into partial classes or extension methods or something. The above code will not function "as is" but you get the idea.
{ "pile_set_name": "StackExchange" }
Q: Получение элемента вне класса браузер на pyqt5. В ответ на сигнал QWebEngineView(обычный класс который унаследовал его, в нем изменена функция createWindow) urlChanged нужно изменить адрессную строку и положить туды url. Но вот вопрос: как получить доступ к адресной строке?(QLineEdit) A: Какие-то сложные ответы. Почему бы не передать ссылку на адресную строку в __ init __ спасибо тебе, ув. eri!
{ "pile_set_name": "StackExchange" }
Q: Excel macro to get SEPARATE graphs of many Ys with the same Xs I have a data set in which the first column is the x but the other columns (> 50) are the Ys. There are 6 rows. I know I can plot all the Ys on the same axis in the same chart, but I need separate graphs of Y all with the same x. However, I am clueless if it is possible to have an excel macro that will allow me to plot DIFFERENT bar graphs for as many Ys all at once. Doing it manually is a pain because I have many datasets with these dimensions. Any help would be greatly appreciated. Below is the code I used but it plotted all the bars in a single graph. Found this code online and tweaked it Sheets("sheet1").Select ActiveSheet.Shapes.AddChart.Select With ActiveChart .ChartType = xlColumnClustered .SetSourceData Source:=Sheets("sheet1").Range("A1:D7") 'sets source data for graph including labels .SetElement (msoElementLegendRight) 'including legend .HasTitle = True 'dimentions & location: .Parent.Left = 47 'defines the coordinates for the left side of the chart .Parent.Height = 300 .Parent.Width = 600 .ChartTitle.Text = "Yield by group " & intGraphStart End With A sample A: The procedure below create a chart in a separated sheet for each of the columns from B to L using column A as a common horizontal axis. Sub Rng_Charts_Add_Multiple() Const kChrTtl As String = "Yield by group " Dim Wbk As Workbook, WshSrc As Worksheet Dim rSrc As Range, Chrt As Chart Dim sCol As String, bCol As Byte Rem Application Settings Application.EnableEvents = False Application.DisplayAlerts = False Application.ScreenUpdating = False Set Wbk = ThisWorkbook Set WshSrc = Wbk.Sheets("Sht(1)") Application.Goto WshSrc.Cells(1), 1 Set rSrc = WshSrc.Cells(1).CurrentRegion For bCol = 2 To rSrc.Columns.Count Rem Add Chart in a New Sheet sCol = rSrc.Cells(1, bCol).Value2 With Wbk On Error Resume Next .Sheets("Chart " & sCol).Delete On Error GoTo 0 Application.Goto WshSrc.UsedRange.SpecialCells(xlCellTypeLastCell).Offset(2, 2) Set Chrt = .Charts.Add2(After:=.Sheets(.Sheets.Count), NewLayout:=1) End With Rem Chart Settings With Chrt .name = "Chart " & sCol .ApplyLayout (1) .ChartTitle.Text = kChrTtl & sCol .ChartType = xlColumnClustered .SetSourceData Source:=Union(rSrc.Columns(1), rSrc.Columns(bCol)) End With: Next Rem Application Settings Application.EnableEvents = True Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub Suggest to visit the following pages: Variables & Constants, Application Object (Excel), Excel Objects With Statement, For...Next Statement, Range Object (Excel) Worksheet Object (Excel), ChartObjects Members (Excel)
{ "pile_set_name": "StackExchange" }
Q: Future of Tire technology Why do tire producing companies still produce tubulars? Isn`t Tubeless the technology of the future? A: I'm not sure you know what tubular tires are (they are relatively rare), but I'll describe the 3 basic tire systems for bicycles: The most common is the good old clincher tire. (Image from Wikipedia: Bicycle Tire) The tire (4=bead,6=casing,7=tread) hooks into the rim (1) via the bead (4). The air is held through an inner tube (5) which is protected from the spoke nipples by a rim strip (2). Theres a lot of reasons for using this: If you have a flat, you can easily swap the tube and/or tire, no mess required. Tubes are repairable. Tires sometimes repairable. Everyone knows how to deal with them and stocks them. The rim doesn't have to be anything special. Cheap, cause everyone's been using them forever. However, there are some disadvantages: Tubes do have some weight to them. At low pressures, you can pinch the tube and get a flat. A tubular tire is basically a tube wrapped in the casing and then glued onto the rim. A picture is given below: (From this question) According to Sheldon Brown: Lighter tires and rims than similar clinchers Less likely to pinch flat But on the other hand, Hard to repair Expensive Can roll off the rim if you don't glue them properly Higher rolling resistance Not always as round/true as a clincher. Rare -- pretty much only certain racers use them (road, cyclocross). Finally, we come to tubeless. The mounting system is the same as whats given for the clincher tire, except you don't have an inner tube (5) or rim tape necessarily (2) [Depending on the rim, you may need some tape to make it airtight]. We can distinguish between tubeless rims+tires and tubeless-ready rims+tires (the latter requiring using a liquid sealant with the tire+rim in order to seal the tire, while the former it is optional). The good things are: You can run lower pressures since theres no tube to flat (better traction) Lower rolling resistance The sealant provides some puncture protection for sealing The bad is: Installing the tire is a lot longer than a tubed tire (Schwalbe notes that it may take up to 3 days for the sealant to seal the tire) Messier to replace a tire since you have to clean out the sealant You may need to carry around a spare tube anyway, if something happens to stick in the tire and keep moving. One may argue that tubeless are lighter or heavier than clinchers, but that depends on the system of tubeless tire, so I've left that out. These things are primarily advantageous for mountain bikers. For road bikers, not so much. The big reason why I think a lot of people still ride clincher tires is cause they're easy to maintain, cheap, and everybody knows how to deal with them and has the parts. Mountain bikers see real advantages with tubeless, while road bikers don't really see advantages, so they do ride tubeless fairly often, but still, the tube is not leaving us any time soon.
{ "pile_set_name": "StackExchange" }
Q: Does 4-wheel alignment involve taking wheels off? I was wondering if a 4-wheel alignment involves taking off all the wheels. I called NTB to check whether their wheel alignment includes tire rotation and they said it didn't. But if they have to take all the wheels off, why would it matter which wheel they put on which rotor, i.e. doesn't make any difference to them? If they can do it without taking the wheels off, then I would understand. A: An alignment does not require removing the wheels. The equipment is attached to the wheels while they are in place. I often wondered about the shops that will do a free brake inspection but then charge $20 for tire rotation.
{ "pile_set_name": "StackExchange" }
Q: Can Pentax and Canon mounts on Tamron lenses be swapped? I have two Tamron lenses. Lens A has a mount ring for Canon, and Lens B has a mount ring for Pentax. Lens A is broken. Can I swap the mount rings and use lens B for my Canon camera? A: If your lenses are older Tamron Adaptall style lenses, then yes, you can remove the Canon FD ring and replace it with the Pentax K-mount ring and use the lens with pentax cameras.
{ "pile_set_name": "StackExchange" }
Q: Minimum Gower's distance for two data frames I am looking for an implementation that determines the minimum value of Gower's distance for all records in one (say, test) data frame to any record in a second (say, training) data frame. The result is a vector with one element for each row in test. The data are categorical with unordered categorical attributes, and can be generated, for example, like this: set.seed(20130926L) DIMS <- 12 CATS <- 2 create.data <- function(SPARSITY) { sparse.data <- rbinom(CATS ** DIMS, 1, SPARSITY) sparse.array <- array(sparse.data, dim=rep(CATS, DIMS)) sparse.table <- as.table(sparse.array) sparse.df <- as.data.frame(sparse.table) sparse.df <- subset(sparse.df, Freq > 0, select=-Freq) sparse.df } data.train <- create.data(0.001) data.test <- create.data(0.01) head(data.train, 3) ## Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10 Var11 Var12 ## 745 A A A B A B B B A B A A ## 1156 B B A A A A A B A A B A ## 1574 B A B A A B A A A B B A summary(data.test) ## Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10 ## A:24 A:31 A:23 A:20 A:30 A:27 A:22 A:20 A:26 A:23 ## B:24 B:17 B:25 B:28 B:18 B:21 B:26 B:28 B:22 B:25 ## Var11 Var12 ## A:24 A:22 ## B:24 B:26 How do I find, for all rows in data.test, the row in data.training where Gower's distance is minimal (or at least the distance to that particular row)? The code below works, but needs too much memory already for 20 attributes or for more than 2 categories: nrow(data.test) ## [1] 48 library(StatMatch, quietly=T, warn.conflicts=F) apply(gower.dist(data.train, data.test), 2, min) ## [1] 0.3333 0.4167 0.2500 0.5000 0.3333 0.4167 0.2500 0.3333 0.2500 0.4167 ## [11] 0.5000 0.3333 0.3333 0.3333 0.4167 0.4167 0.2500 0.4167 0.1667 0.3333 ## [21] 0.4167 0.3333 0.4167 0.5000 0.3333 0.5000 0.5000 0.4167 0.3333 0.3333 ## [31] 0.2500 0.4167 0.5000 0.4167 0.3333 0.5000 0.3333 0.4167 0.3333 0.3333 ## [41] 0.5000 0.5833 0.5000 0.2500 0.3333 0.4167 0.3333 0.5000 The function cluster::daisy() also returns a matrix of distances. Similar: How to calculate Euclidean distance (and save only summaries) for large data frames. There, it is suggested to call the distance function several times for subsets of data.train. I can do that, but the computation time is still prohibitive. After all, the definition of Gower's distance permits a more efficient algorithm, perhaps a recursive divide-and-conquer approach that operates attribute by attribute and calls itself on subsets. Recall that Gower's distance is a (weighted) sum of attribute-wise distances, which is defined for categorical attributes: 0 if equal, 1 otherwise for ordered attributes: 0 if equal, proportional to rank distance otherwise for continuous attributes (not needed here): proportional to ratio of distance and range of the attribute The following is a simple demonstration where Gower's distance between (A, A) and all combinations of A and B is computed. Rows that differ on one attribute have a distance of 0.5, the row that differs on both attribute gets the maximal distance of 1.0: (ex.train <- expand.grid(Var1=LETTERS[1:2], Var2=LETTERS[1:2])) ## Var1 Var2 ## 1 A A ## 2 B A ## 3 A B ## 4 B B ex.test <- ex.train[1, ] gower.dist(ex.train, ex.test) ## [,1] ## [1,] 0.0 ## [2,] 0.5 ## [3,] 0.5 ## [4,] 1.0 If both train.data and test.data are analyzed column-wise, a possible implementation might look like this: For all value levels v of the first column choose subset of test.data where first column has value v choose subset of train.data where first column has value v call procedure recursively to obtain an upper bound for the minimum choose subset of train.data where first column has value <> v call procedure recursively using the previously obtained upper bound for early cut-off Is there really no implementation around, or perhaps a paper that describes such an algorithm? A: I'm not familiar with Gower's distance, but from what you describe, it appears that, for unordered categorical attributes, Gower's distance is equivalent to the Hamming distance divided by the length of the vector. In other words, the Gower distance between vectors x and y is simply mean(x!=y). In this situation, you can save a significant amount of computation time by avoiding computing the entire distance matrix, and instead using colSums. Here is an example, with three levels and 10000 training rows: > set.seed(123) > train.rows<-10000 > test.rows<-100 > cols<-20 > levels<-c("a","b","c") > train.set<-sample(levels,train.rows*cols,T) > dim(train.set)<-c(train.rows,cols) > test.set<-sample(levels,test.rows*cols,T) > dim(test.set)<-c(test.rows,cols) > system.time(gdist<-apply(gower.dist(train.set,test.set),2,min)) user system elapsed 13.396 0.324 13.745 > system.time(hdist<-apply(test.set,1,function(x) min(colSums(x!=t(train.set))/cols))) user system elapsed 0.492 0.008 0.504 > identical(hdist,gdist) [1] TRUE If the data is not discrete and unordered, then the formula for Gower's distance is different, but I suspect that there is a similar way to compute this more efficiently without computing the entire distance matrix via gower.dist. Update: this can be made more efficient by using @Frank's suggestion, and generating t(train.set) upfront rather than within the function: require(microbenchmark) ttrain.set<-t(train.set) microbenchmark( a=apply(test.set,1,function(x) min(colSums(x!=t(train.set))/cols)), b=apply(test.set,1,function(x) min(colSums(x!=ttrain.set)/cols))) ## Unit: milliseconds ## expr min lq median uq max neval ## a 523.3781 533.2950 589.0048 620.4411 725.0183 100 ## b 367.5428 371.6004 396.7590 408.9804 496.4001 100
{ "pile_set_name": "StackExchange" }
Q: Merging a vector layer with a Raster layer I have a Tiff file that has an aerial view and also a shapefile which has contours of the same area. How can I put the contours in the tiff file so that you can view the TIFF and see them both in one picture. I am using QGIS. A: Bring in a shapefile of your contours and make sure they have an elevation attribute with them. Go to Raster > Conversion > Rasterize and select your shapefile, the elevation attribute, and then your existing Tiff file you want to put the contours on. Press run and you will get a tiff with the contours on top of the layer. The following link is very helpful to accomplish this : How to control line width when merging vector files into raster? . Thank you @Pooneil
{ "pile_set_name": "StackExchange" }
Q: UIControl Subclass - Events called twice I'm currently working on a custom UIControl Subclass. To track the touches I use the following Method: - (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event { NSLog(@"Start"); CGPoint location = [touch locationInView:self]; if ([self touchIsInside:location] == YES) { //Touch Down [self sendActionsForControlEvents:UIControlEventTouchDown]; return YES; } else { return NO; } } This works as expected and @"Start" is loged exactely once. The next step is that I add a Target and a Selector with UIControlEventTouchDown. [markItem addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; This works also and the action: method is called. But that's my problem. The action is called twice. What am I doing wrong? I just use [self sendActionsForControlEvents:UIControlEventTouchDown]; once and the target action is called twice. What's wrong with my code? Sandro Meier A: The first call to the action method happens automatically by the event dispatcher once you've called: [markItem addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; to register the handler. So when you then call: //Touch Down [self sendActionsForControlEvents:UIControlEventTouchDown]; you are generating the second call to your handler (and any others that are hooked up). So it seems like you don't need both the action handler and the beginTracking - use one or the other. Update: Given your comment and further thought: since you are a subclass of UIControl, I think you probably don't want to be registering for event handlers for yourself. Instead you should exclusively use: - (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event; - (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event; - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event; - (void)cancelTrackingWithEvent:(UIEvent *)event; // event may be nil if cancelled for non-event reasons, e.g. removed from window Also the tracking instance variable. So I think you should not be posting events or listening to events. Further, is it actually possible to get a beginTrackingWithTouch event if it's not in your view? Doesn't seem like it would be. So I don't think you need the testing to see if it's in your view. So I think it might be worth stepping back and thinking about what you are trying to do and re-reading UIControl documentation. Specifically: Subclassing Notes You may want to extend a UIControl subclass for either of two reasons: To observe or modify the dispatch of action messages to targets for particular events To do this, override sendAction:to:forEvent:, evaluate the passed-in selector, target object, or UIControlEvents bit mask, and proceed as required. To provide custom tracking behavior (for example, to change the highlight appearance) To do this, override one or all of the following methods: beginTrackingWithTouch:withEvent:, continueTrackingWithTouch:withEvent:, endTrackingWithTouch:withEvent:. The first part is for having your UIControl subclass do non-standard handling of target action processing for clients or users of your control (that doesn't sound like what you are trying to do, though you didn't really give a high-level description). The second part sounds more like what you are wanting to do - custom tracking within your UIControl subclass.
{ "pile_set_name": "StackExchange" }