qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
8,258,128
every body. I am getting this error: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '14:37:41)' at line 1` for this piece of code ``` public String addName() { // TODO Auto-generated method stub try { java.util.Date dt = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(dt); String name = "RandomName"; Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost", "ericman", "ericman"); Statement stat = (Statement) connect.createStatement(); String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES ('" + name + "', " + currentTime + ")"; stat.executeUpdate(insert); } catch (Exception e) { System.out.println(e); } return "Name Updated"; } ``` Any suggestion of why this happening, I suck on structured language just so you know :)
2011/11/24
[ "https://Stackoverflow.com/questions/8258128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/847085/" ]
Use `PreparedStatement`. ``` String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES (?,?)"; PreparedStatement ps=connect.prepareStatement(insert); ps.setString(1,name); ps.setTimeStamp(2,TimeStamp.valueOf(currentTime)); ps.executeUpdate(); ```
You are missing `'` characters around your currentTime in the insert statement. However, you really should be using a prepared statement for such things, to guard against SQL injection attacks.
40,167,354
I know we can create a auto partition discovery table via ``` CREATE TABLE my_table USING com.databricks.spark.avro OPTIONS (path "/path/to/table"); ``` But this requires change the data path to **partition\_key=partition\_value** format ``` /path/to/table/dt=2016-10-09 /path/to/table/dt=2016-10-10 /path/to/table/dt=2016-10-11 ``` But the data structure looks like: ``` /path/to/table/2016-10-09 /path/to/table/2016-10-10 /path/to/table/2016-10-11 ``` I don't want to change existing data structure, so I am trying to do it like Hive way, which I just create a partition table, then I can add these partitions by myself, so I don't need to change existing data structure to **partition\_key=partition\_value** format. But the SQL below didn't work: ``` CREATE TABLE my_table USING com.databricks.spark.avro PARTITIONED BY (dt) OPTIONS (path "/path/to/table"); ``` The SQL command line tool will throw exception: `Error in query: cannot recognize input near 'thrive_event_pt' 'USING' 'com' in table name; line 2 pos 0` Does Spark SQL support to create a partitioned table in this way? or there is something else I am missing?
2016/10/21
[ "https://Stackoverflow.com/questions/40167354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3015140/" ]
I think what you're asking for is how to return the information for all the images where the height is greater than the width. In which case, I think you want something like this: ``` select * from <table name> where high > wide ; ```
in ormlite can use ".le("picture\_width", new ColumnArg("picture\_height")) "
3,647,869
> > Let $\displaystyle I=\int\_a^b(x^4−2x^2)\,\mathrm dx$, then $I$ reaches the minimum when the ordered pair $(a,b)$ is:$$(-\sqrt2,0)\quad(0,\sqrt2)\quad(\sqrt2,-\sqrt2)\quad( -\sqrt2, \sqrt2)$$ > > > I solved the integration and got $\dfrac{b^5}{5}-\dfrac{2b^3}{3}-\dfrac{a^5}{5}+\dfrac{2a^3}{3}$. If I put $( -\sqrt2,0)$ or $ (0, \sqrt2)$, I get $\frac{(\sqrt2)^5}{5}-\frac{2(\sqrt2)^3}{3}$. Let this be $P$. If I put $( \sqrt2, -\sqrt2)$, I get $-2P$. If I put $( -\sqrt2, \sqrt2)$, I get $2P$. And since $P$ is negative, so the minimum is $2P$. So, the answer is $( -\sqrt2, \sqrt2)$. But this is quite a time consuming method. I wish if there was a quicker way to solve it (by observation or by graph or something, without so much calculation.)
2020/04/28
[ "https://math.stackexchange.com/questions/3647869", "https://math.stackexchange.com", "https://math.stackexchange.com/users/87430/" ]
It's easy to sketch the graph of $$x^4-2x^2=x^2(x^2-2)=x^2(x-\sqrt2)(x+\sqrt2)$$ This is an even function, with a double root at $0$ which is a local maximum, and also roots of $-\sqrt2$ and $\sqrt2$. It goes to $\infty$ as $|x| \to \infty$. [![enter image description here](https://i.stack.imgur.com/iF0rk.png)](https://i.stack.imgur.com/iF0rk.png) We would pick $(-\sqrt{2}, \sqrt2)$ as it covers the whole negative region. Checking that this is a better option compared to the other options: The first option would only cover half of the region, it's the same for the second option though it covers another half. The third solution would flip the region around and you will get a positive answer instead. Remark: The global minimum for all real $a$ and $b$ indeed does not exists as we can let $a$ be arbitrarily large and $b$ be arbitrarily small but out of the $4$ options, the last option give the lowest value.
Simply check out the plot of the function that you are integrating, you will see that \begin{equation} (0, \sqrt{2}) \text { or }(-\sqrt{2}, 0) \end{equation} corresponds P which is negative so this is why the answer is: \begin{equation} (-\sqrt{2}, \sqrt{2}) \end{equation} Also, you need to check all the options because the minimum value of integration depends on the interval that is given and the plot is useful for this question because if you know the roots of the function and have a general idea of the behaviour you can guess the result of integration for this question you can simply see that minimum option is a negative integral which eliminates 2 options given.
34,942
I want to either use a module or write a module which allows me to count the number of Anonymous Users that are currently using the site. What is the best method for this to be achieved? I looked at the statistics module but this does not enable me to count the data. I discovered views is capable of this with this setting, "Content statistics: Most recent views". But, there was no option for anonymous data.
2012/06/24
[ "https://drupal.stackexchange.com/questions/34942", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/5795/" ]
The [admin\_menu](https://www.drupal.org/project/admin_menu) module does this, and provides this [function](https://cgit.drupalcode.org/admin_menu/tree/admin_menu.module): ``` /** * Counts how many users are active on the site. * * Counts how many users have sessions which have been active since the * specified time. Can count either anonymous sessions or authenticated * sessions. * * @param $timestamp * A Unix timestamp. Users who have been active since this time will be * counted. The default is 0, which counts all existing sessions. * @param $anonymous * TRUE counts only anonymous users. FALSE counts only authenticated users. * * @return * The number of users with sessions. * * @todo There are mostly no anonymous sessions anymore. Split this into a * separate module providing proper user statistics. */ function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) { $query = db_select('sessions'); $query->addExpression('COUNT(sid)', 'count'); $query->condition('timestamp', $timestamp, '>='); $query->condition('uid', 0, $anonymous ? '=' : '>'); return $query->execute()->fetchField(); } ``` It returns the count of users who have been active in the past (default) 15 minutes like this: ``` function admin_menu_get_user_count() { $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900); $count_anon = admin_menu_session_count($interval, TRUE); $count_auth = admin_menu_session_count($interval, FALSE); return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth)); } ```
For info related to visitors of a website, consider the [visitors](https://www.drupal.org/project/visitors) module as an alternative. One of the things you get from it is a **Visitors Block**, which includes, among others, data about: * Total Visitors. * Unique Visitor. * Registered Users. * ... Combining these 3 numbers is a possible estimate to "calculate" the number of unique not-registered (anonymous) users. This module also comes with some reports & charts (a typical related requirement ...). Its [community docu](https://www.drupal.org/node/2432339) and/or [project page](https://www.drupal.org/project/visitors) contains some more details. However its documentation pages still need quite some work to get completed. Refer to [issue #2432369](https://www.drupal.org/node/2432369), for various topics that still need to be included somehow. The child issues of this issue already contain some pointers to documentation contained in existing issues. Testing the module in your own environment is a possible approach to find out what the module's capabilities really are. Disclosure: I'm the [new](https://www.drupal.org/node/2380441#comment-9651615) maintainer of this module, I hope this does not violate the site's [policy on self-promotion](https://drupal.stackexchange.com/faq#promotion).
28,882,691
While looking for how to enable scrolling with the mouse wheel in Sencha Touch, I came across [this](https://stackoverflow.com/questions/24397159/adding-mousewheel-to-sencha-desktop-app) answer. However, I am relatively new to Sencha Touch and the codebase I was given to maintain that uses it. The answer says to put it in the *initialization block of my application*: as far as I can tell, that would be my `app.js` file that is generated by Sencha Cmd (which has a `launch` function). However, I'm lost after this. Would I add the first part of the above answer *in* the `launch` block? Outside of it? How would I make sure that it is automatically called on every page? **Edit**: Here is my `app.js` file, in case it helps. ``` Ext.application({ name: 'App', requires: [ 'Ext.MessageBox', 'Ext.direct.*' ], models:[ "..." ], controllers: [ '...', '...', '...' ], icon: { '57': 'resources/icons/Icon.png', '72': 'resources/icons/Icon~ipad.png', '114': 'resources/icons/Icon@2x.png', '144': 'resources/icons/Icon~ipad@2x.png' }, isIconPrecomposed: true, startupImage: { '320x460': 'resources/startup/320x460.jpg', '640x920': 'resources/startup/640x920.png', '768x1004': 'resources/startup/768x1004.png', '748x1024': 'resources/startup/748x1024.png', '1536x2008': 'resources/startup/1536x2008.png', '1496x2048': 'resources/startup/1496x2048.png' }, profiles: ['Tablet', 'Phone'], launch: function() { ... } .... }); ``` **Edit 2**: I am using Sencha Touch 2.3.
2015/03/05
[ "https://Stackoverflow.com/questions/28882691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991710/" ]
The provided code in the other answer is pure Javascript and not ExtJs code, it runs in a global scope so you can add this above Ext.application (outside of ExtJs code, so make it your first bit of JS code that gets run). You could even wrap it inside an Ext.onReady call to make sure ExtJs is also fully loaded before you add it, if needed. This should work, it might be worth looking over the Sencha forums or even on here for a more elegant and updated solution though.
The OP's answer above works, however it throws errors if trying to scroll over elements that do not have indexOf on their className (like SVG elements). Here is the updated code that first checks for the existence of indexOf. I've also extended this method to support horizontal mouse scrolling if the browser supports wheelDeltaX and wheelDeltaY. Otherwise it defaults to using the more widely available wheelDelta and only scrolls in the Y direction. Note that you can embed this code in a function and simply call it during the launch of your app. No need to put it at the top of the app.js file. ```html var mouseWheelHandler = function (e) { var e = window.event || e, el = e.target, cmp, offset, scroller, deltaY, deltaX, _results = []; e.preventDefault(); // prevent scrolling when in iframe while (el !== document.body) { if (el && el.className && el.className.indexOf && el.className.indexOf('x-container') >= 0) { cmp = Ext.getCmp(el.id); if (cmp && typeof cmp.getScrollable == 'function' && cmp.getScrollable()) { scroller = cmp.getScrollable().getScroller(); if (scroller) { deltaY = e.detail ? e.detail * (-120) : e.hasOwnProperty('wheelDeltaY') ? e.wheelDeltaY : e.wheelDelta; deltaX = e.detail ? e.detail * (-120) : e.hasOwnProperty('wheelDeltaX') ? e.wheelDeltaX : 0; offset = {x: -deltaX * 0.5, y: -deltaY * 0.5}; scroller.fireEvent('scrollstart', scroller, scroller.position.x, scroller.position.y, e); scroller.scrollBy(offset.x, offset.y); scroller.snapToBoundary(); scroller.fireEvent('scrollend', scroller, scroller.position.x + offset.x, scroller.position.y - offset.y); break; } } } _results.push(el = el.parentNode); } return _results; }; if (document.addEventListener) { // IE9, Chrome, Safari, Opera document.addEventListener('mousewheel', mouseWheelHandler, false); // Firefox document.addEventListener('DOMMouseScroll', mouseWheelHandler, false); } else { // IE 6/7/8 document.attachEvent('onmousewheel', mouseWheelHandler); } } ```
14,236,813
After the app starts, and I press the start button, it s "lagg" but I used this code into viewdidload and viewdidappear too: ``` gombhang = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"button4" ofType:@"mp3"]]; gombha = [[AVAudioPlayer alloc] initWithContentsOfURL:gombhang error:nil]; [gombha prepareToPlay]; gombha.delegate = self; ``` How can I fix this lagg? If I can t fix it apple will reject it?
2013/01/09
[ "https://Stackoverflow.com/questions/14236813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580269/" ]
Even in languages like FORTRAN, where there is still a GOTO, it's not usually recommended that you use it: <http://books.google.com/books?id=D0HOaW-5svQC&pg=PA63&lpg=PA63&dq=fortran+scientists+and+engineers+goto&source=bl&ots=NWYj9wa2y3&sig=TH0NEPkqNtNQgprVpBn912WHJAQ&hl=en&sa=X&ei=WoftUKiJDcuv0AGM-4DYCQ&ved=0CDQQ6AEwAQ#v=onepage&q=fortran%20scientists%20and%20engineers%20goto&f=false>
Python saw the error in their ways, and added a [goto](http://entrian.com/goto/download.html)! **Just Kidding - please don't use in real code** It was released as an April Fools Joke.
31,564
I'm developing a prototype that uses a quadrature encoder to measure it's linear displacement. The encoder is attached to the prototype body and has a wheel in it's shaft. As the prototype moves straight forward the encoder measure the linear distance. All the trouble around the conversion between linear/angular units have been worked out. The reason to measure the distance with an encoder is that i NEED to know everytime that the prototype has traveled exacly 1 mm (1 millimeter = 0.0393 in). Everytime it moves 1 mm, PIC activates another system. The way it has been done before I started working on it is by reading the encoder with a PIC (16F688) in it's I/O ports. It was kindda ok but when I added some features to the PIC code, if the prototype linear speed is greater than ~1.77 in/s (~45 mm/s) PIC starts missing the encoder count. I've tried using the IOC (interrupt on change) from portA to read the quadrature signal (channels A and B) but it wasn't effective. I know that there are dsPIC's but I need to solve this in my board and I have only 14 pins to do so lol. So i found this PIC16F1825 which has a higher (4x) freq. Could that (my PIC low freq) be my main problem?? I'm was thinking about using the [LFLS7183](http://www.usdigital.com/products/interfaces/ics/lfls7183-s) UP/DOWN signals with the timer/counter from PIC or another counter IC so that would reduce the amount of signaling to PIC. Would that work? Which counter should I use? I don't have 8 pins in my PIC to use as in those <http://goo.gl/2Wc3d>. My encoder isn't my problem, I've checked and it can track as far as 76 feet/s for my wheel radius.
2012/05/09
[ "https://electronics.stackexchange.com/questions/31564", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/9165/" ]
I know you explicitly said that you only have 14 pins to solve your problem but I don't understand if this is related to the amount of real state you have on the PCB or if this is a legacy board. If this is due to real state, you could use a [dsPIC33FJ12MC201](http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en520468), which is a 20 pin part, not very far from your 14 pin limit, and it includes a QEI module which would make your life much easier; maybe you can squeeze this part in your board. Hope this helps.
Was your PIC ISR simple? * > > compute jump based on Quadrature value > > > * > > return +1 or -1 or 0 > > > * > > then add to present value. > > > It should be able to handle it, I think... ....any metastates? then latch the input values. If still nogo. Then use a CPLD with Up/down counters and shift out to PIC on a serial I/O pin. Choose binary or decimal as you wish.
839,683
Let's suppose we have a subversion repository which looks like ``` /original/0.1 /original/0.2 /variantA/trunk /variantA/branches/who/branch_for_xxx /variantA/branches/she/branch_for_yyy /variantB/trunk /variantB/branches/who/branch_for_zzz (... 30 or 40 alike) ``` where variantA and variantB are forks of the original software. I am looking for a method for migrating this repository into a distributed version control system: a method * not necessarily wigh a single command * for any one of well-known distributed version control systems * making the dvcs think of them branches: /official/{0.1,0.2} trees, /variantA/trunk tree, ... * making the dvcs aware of the inheritance relation of those trees
2009/05/08
[ "https://Stackoverflow.com/questions/839683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103518/" ]
Mercurial comes with a convert extension which should do what you want. See the [convert extension details on the Mercurial web site.](http://www.selenic.com/mercurial/wiki/ConvertExtension)
$ bzr svn-import --layout trunk1 *svn-root-url* bzr.repo Should do the right thing. You need to have the bzr-svn plugin installed in order to be able to do this.
7,137,545
Is there any way by which i could know exactly which server a POST request has originated from ? I'm trying to implement a method wherein i could check that a specific request has originated from my website, and hence this will help me keep my website secure Thanks
2011/08/21
[ "https://Stackoverflow.com/questions/7137545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/807757/" ]
Take a look at this: <http://en.wikipedia.org/wiki/Cross-site_request_forgery#Prevention>
I think you need to read this: <http://www.cyberciti.biz/faq/how-to-determine-retrieve-visitors-ip-address-use-php-code-programming/>
50,948,412
[![Not actual screenshot of the code. But error is same](https://i.stack.imgur.com/R7piT.png)](https://i.stack.imgur.com/R7piT.png) Error: **Looks like the app doesn't have the permission to access location. Add the following line to your app's AndroidManifest.xml** Even though I have added the permissions in manifest.xml and asking for runtime permissions I cannot access GPS. My AndroidManifest.xml ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.location"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ..... ..... ``` complete code: ```jsx import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, PermissionsAndroid } from 'react-native'; export default class App extends Component { async requestLocationPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { 'title': 'Location Access Permission', 'message': 'Expensify would like to use your location ' + 'so you we track you.' } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log("You can use the location") } else { console.log("Location permission denied") } } catch (err) { console.warn(err) } } componentDidMount() { console.log("compdidmount"); this.requestLocationPermission(); //Crashes here on getCurrentPosition navigator.geolocation.getCurrentPosition( (position) => { console.log(position.coords.latitude); }, (error) => { console.log(error) }, {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000} ); } render() { return ( <View style> <Text style> Tracking App </Text> </View> ); } } ```
2018/06/20
[ "https://Stackoverflow.com/questions/50948412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9212055/" ]
Maybe not the answer you were hoping for, but I think these timings are useful. Run on a directory with 15,424 directories totalling 102,799 files (of which 3059 are .py files). Python 3.6: ``` import os import glob def walk(): pys = [] for p, d, f in os.walk('.'): for file in f: if file.endswith('.py'): pys.append(file) return pys def iglob(): pys = [] for file in glob.iglob('**/*', recursive=True): if file.endswith('.py'): pys.append(file) return pys def iglob2(): pys = [] for file in glob.iglob('**/*.py', recursive=True): pys.append(file) return pys # I also tried pathlib.Path.glob but it was slow and error prone, sadly %timeit walk() 3.95 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit iglob() 5.01 s ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit iglob2() 4.36 s ± 34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) ``` Using GNU find (4.6.0) on cygwin (4.6.0-1) **Edit: The below is on WINDOWS, on LINUX I found `find` to be about 25% faster** ``` $ time find . -name '*.py' > /dev/null real 0m8.827s user 0m1.482s sys 0m7.284s ``` --- Seems like `os.walk` is as good as you can get on windows.
os.walk() uses scandir which is the fastest and we get the file object that can be used for many other purposes as well like, below I am getting the modified time. Below code implement recursive serach using os.scandir() ``` import os import time def scantree(path): """Recursively yield DirEntry objects for given directory.""" for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): yield from scantree(entry.path) else: yield entry for entry in scantree('/home/'): if entry.is_file(): print(entry.path,time.ctime(entry.stat().st_mtime)) ```
16,204,523
I am creating an application that allows users to make comments on project postings created. I followed this [Railscast](http://railscasts.com/episodes/154-polymorphic-association?) to set up polymorphic associations. Based on the tutorial, the index page in the controller is set up as detailed below takes you to localhost:3000/projects/1/comments. **Question: How do I route it and adjust the def index in the controller so that I can instead route index to localhost:3000/comments because I want to create a view that lists all comments regardless of which project it was posted on? Because right now, based on the routes and code below, when I go to localhost:3000/comments, I get the following error:** ``` ActiveRecord::RecordNotFound in CommentsController#index Couldn't find Comment without an ID app/controllers/comments_controller.rb:32:in `load_commentable' ``` /app/controllers/comments\_controller.rb ``` class CommentsController < ApplicationController before_filter :load_commentable def index @comments = @commentable.comments end private def load_commentable resource, id = request.path.split('/')[1,2] @commentable = resource.singularize.classify.constantize.find(id) end end ``` routes.rb ``` resources :projects do resources :comments end resources :comments ```
2013/04/25
[ "https://Stackoverflow.com/questions/16204523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281142/" ]
With awk : ``` awk '/^StringB/ { if(lastline ~ /^StringA/) {print lastline }} {lastline=$0}' $file ``` StringA and StringB can be regular expressions.
This might work for you (GNU sed): ``` sed ':a;$!N;/^StringA/!D;/^\(StringA\).*\n\1/D;/.*StringB/!ba;P;D' file ``` This removes duplicate `StringA` lines retaining the last and when encountering a `StringB` line prints out the first string in the pattern space.
3,314,203
I saw the formula below in this paper: <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.331.6329&rep=rep1&type=pdf> It said Assume that $\mathbf H$ is a complex matrix of size $n \times m $,having full column rank $\mathbf S$ is a complex matrix of size $n \times t$,having full column rank the well-known formula to build an orthogonal projection whose range is $<\mathbf H>$ is $\mathbf P\_H=\mathbf H (\mathbf H^H \mathbf H)^{-1}\mathbf H^H-----(a)$ Now if we examine the matrix $(\mathbf H \mathbf S)$,the orthogonal projection onto the linear subspace $<\mathbf H \mathbf S>$ is $$ \mathbf P\_{HS}=(\mathbf H \mathbf S)\begin{pmatrix} \mathbf H^H \mathbf H & \mathbf H^H \mathbf S\\ \mathbf S^H \mathbf H & \mathbf S^H \mathbf S\\ \end{pmatrix}^{-1}\begin{pmatrix}\mathbf H^H \\ \mathbf S^H\end{pmatrix} -------(b) $$ I want to ask is that how does the (a) come?because in my thinking,the orthogonal projection is like $proj\_\mathbf u(\mathbf v)=\frac{<\mathbf v, \mathbf u,>}{<\mathbf u, \mathbf u,>}\mathbf u$ Second,$\mathbf H$ become $\mathbf H \mathbf S$,so $H^H$ become\begin{pmatrix}\mathbf H^H \\ \mathbf S^H\end{pmatrix},i can also understand.However,why will the $(\mathbf H^H \mathbf H)^{-1}$ become $$ \begin{pmatrix} \mathbf H^H \mathbf H & \mathbf H^H \mathbf S\\ \mathbf S^H \mathbf H & \mathbf S^H \mathbf S\\ \end{pmatrix}^{-1} $$
2019/08/05
[ "https://math.stackexchange.com/questions/3314203", "https://math.stackexchange.com", "https://math.stackexchange.com/users/693697/" ]
Your formula for $proj\_u$ is correct when you project along the line defined by $u$. Here we are projecting in a subspace spanned by the column of $H$. You start from the property that $v - proj\_{H}(v)$ is orthogonal to any vector spanned by the columns of $H$: $$ H^T \left( v - proj\_{H}(v) \right) = 0 $$ or $$ H^T v = H^T proj\_{H}(v) $$ But $proj\_{H}(v) = H x$ as it is spanned by the columns of $H$ $$ H^T H x = H^T v \quad \Rightarrow \quad x = (H^T H)^{-1} H^T v $$ And you get $$ proj\_{H}(v) = H x = H (H^T H)^{-1} H^T v $$ Based on your dimensions, $\mathbf{HS}$ denotes $\left[ \mathbf{H}, \; \mathbf{S} \right]$ the matrix of dimension $n \times (m + t)$. The rest of the derivation is correct assuming that $\left[ \mathbf{H}, \; \mathbf{S} \right]$ remains full rank.
If $\ \mathbf{z}\ $ is any $\ n\times 1\ $ column vector, then $\ \mathbf{z}\_P=\mathbf{P}\_H \mathbf{z}\ $ is in the column space of $\ \mathbf{H}\ $, and $$ \left\langle \mathbf{z}\_P,\,\mathbf{z}- \mathbf{z}\_P\right\rangle=\left\langle \mathbf{P}\_H \mathbf{z},\,\mathbf{z}-\mathbf{P}\_H \mathbf{z}\right\rangle = \left\langle \mathbf{z},\, \mathbf{P}\_H\mathbf{z}-\mathbf{P}\_H ^{\,2}\mathbf{z}\right\rangle = 0\ , $$ because $\ \mathbf{P}\_H\ $ is hermitian, and $\ \mathbf{P}\_H ^{\,2}=\mathbf{P}\_H\ $. So $\ \mathbf{z}\_P\ $ is the orthogonal projection of the vector $\ \ \mathbf{z}\ $ onto the column space of $\ \mathbf{H}\ $. Your example of $\ proj\_{\mathbf{u}}\left(\mathbf{v}\right)\ $ is just the special case of when $\ m=1\ $, and the column space of $\ \mathbf{H}\ $ is one-dimensional—spanned by $\ \mathbf{u}\ $.
39,535,917
If I have several divs in my HTML like this ``` <div id="div_1"></div> <div id="div_2"></div> <div id="div_3"></div> ``` In my JavaScript, how can I reference them using a variable? ``` // Using Jquery to assign the element to the variable name $div_1 = $(div_1); $div_2 = $(div_2); $div_3 = $(div_3); // set the CSS for each div for (i = 1; i <= 3; i++) { $div_[i].css({'left': 100 +'px'}); } ```
2016/09/16
[ "https://Stackoverflow.com/questions/39535917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721815/" ]
You can create variable holding all elements, use `.filter()` to select an element having a specific full `id`, or `id` ending with specific digit or letter characters ``` // all `div` elements having `id` beginning with `"div"` var divs = $("div[id^=div]"); // select element having `id` ending with `"2"`:`"div_2"` from `divs` collection var div_2 = divs.filter("[id$=2]"); ```
You can use the "id" attribute of your divs and obtain a reference like below: ``` $div_1 = $("#div_1"); ```
1,761,109
I recently had a debate with a colleague who is not a fan of [OOP](http://en.wikipedia.org/wiki/Object-oriented_programming). What took my attention was what he said: "What's the point of doing my coding in objects? If it's reuse then I can just create a library and call whatever functions I need for whatever task is at hand. Do I need these concepts of polymorphism, inheritance, interfaces, patterns or whatever?" We are in a small company developing small projects for e-commerce sites and real estate. How can I take advantage of OOP in an "everyday, real-world" setup? Or was OOP really meant to solve complex problems and not intended for "everyday" development?
2009/11/19
[ "https://Stackoverflow.com/questions/1761109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737290/" ]
The good things about OOP come from tying a set of data to a set of behaviors. So, if you need to do many related operations on a related set of data, you can write many functions that operate on a struct, or you can use an object. Objects give you some code reuse help in the form of inheritance. IME, it is easier to work with an object with a known set of attributes and methods that it is to keep a set of complex structs and the functions that operate on them. Some people will go on about inheritance and polymorphism. These are valuable, but the real value in OOP (in my opinion) comes from the nice way it encapsulates and associates data with behaviors. Should you use OOP on your projects? That depends on how well your language supports OOP. That depends on the types of problems you need to solve. But, if you are doing small websites, you are still talking about enough complexity that I would use OOP design given proper support in the development language.
My personally view: context When you program in OOP you have a greater awareness of the context. It helps you to organize the code in such a way that it is easier to understand because the real world is also object oriented.
72,181,408
I have written the code and according to me code should be working but it is not working. It is giving me runtime error. can anybody check my ques my help me with the same? Here is my code ``` #include <bits/stdc++.h> using namespace std; string replaceSpaces(string str){ int spaces_count = 0; int length = str.length(); for(int i = 0 ; i < str.length() ; i++){ if(str[i] == ' ' ){ spaces_count++; } } int new_length = length + spaces_count * 2 + 1; int index = new_length - 1; str[index] = '\0'; index--; for(int j = length - 1 ; j >=0 ; j--){ if(str[j] == ' '){ str[index] = '0'; str[index-1] = '4'; str[index-2] = '@'; index = index - 3; } else{ str[index] = str[j]; index--; } } return str; } int main() { cout << replaceSpaces("My name is Khan"); } ```
2022/05/10
[ "https://Stackoverflow.com/questions/72181408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19082967/" ]
std::string creates a buffer for the size of the string, when you re-size it, you are using more space, and that is overflowing the allocated buffer. Typically the best pattern for this sort of code, is not to do an in-space modification, but to create a new string which takes the output.
you can do following: ``` #include <bits/stdc++.h> using namespace std; string replaceSpaces(string str){ int n = str.size(); string tmp; for(int i=0; i<n; i++) { if(str[i] == ' ') { tmp.push_back('@'); tmp.push_back('4'); tmp.push_back('0'); } else { tmp.push_back(str[i]); } } return tmp; } int main() { cout << replaceSpaces("My name is Khan"); } ```
86,266
I have a couple of ebooks as PDFs with passwords, however my ebook reader (sony prs600) doesn't seem to support PDFs with passwords. What is the easiest of removing the password from a PDF (I know the password, which presumably helps a lot). It's a bit annoying buying a book and then only being able to read it in front of a computer.
2009/12/21
[ "https://superuser.com/questions/86266", "https://superuser.com", "https://superuser.com/users/10217/" ]
With **[A-PDF Restrictions Remover](http://download.cnet.com/A-PDF-Restrictions-Remover/3000-10743_4-10598299.html?tag=mncol)**, you can remove the password and other restrictions in a few seconds. *A-PDF Restrictions Remover is shareware ($10), try before you buy.*
On GNU/Linux, use the [`qpdf`](http://qpdf.sourceforge.net/) utility: ``` qpdf --password=YOUR_PASSWORD_HERE --decrypt your_input.pdf your_output.pdf ``` this is also easy to automate with a shell script to decrypt multiple PDF files. `qpdf` is available as a package on many/most GNU/Linux distributions. For example, on Debian/Ubuntu-based distributions, you would get it by running: ``` sudo apt install qpdf ``` Caveat: If you specify your password on the command-line, your shell may place it, as plain-text, in your command history file.
657,488
If there are like 1,000,000 individual files (mostly 100k in size) in a single directory, flatly (no other directories and files in them), is there going to be any compromises in efficiency or disadvantages in any other possible ways?
2009/03/18
[ "https://Stackoverflow.com/questions/657488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49318/" ]
ARG\_MAX is going to take issue with that... for instance, rm -rf \* (while in the directory) is going to say "too many arguments". Utilities that want to do some kind of globbing (or a shell) will have some functionality break. If that directory is available to the public (lets say via ftp, or web server) you may encounter additional problems. The effect on any given file system depends entirely on that file system. How frequently are these files accessed, what is the file system? Remember, Linux (by default) prefers keeping recently accessed files in memory while putting processes into swap, depending on your settings. Is this directory served via http? Is Google going to see and crawl it? If so, you might need to adjust VFS cache pressure and swappiness. **Edit:** ARG\_MAX is a system wide limit to how many arguments can be presented to a program's entry point. So, lets take 'rm', and the example "rm -rf \*" - the shell is going to turn '\*' into a space delimited list of files which in turn becomes the arguments to 'rm'. The same thing is going to happen with ls, and several other tools. For instance, ls foo\* might break if too many files start with 'foo'. I'd advise (no matter what fs is in use) to break it up into smaller directory chunks, just for that reason alone.
When you accidently execute "ls" in that directory, or use tab completion, or want to execute "rm \*", you'll be in big trouble. In addition, there may be performance issues depending on your file system. It's considered good practice to group your files into directories which are named by the first 2 or 3 characters of the filenames, e.g. ``` aaa/ aaavnj78t93ufjw4390 aaavoj78trewrwrwrwenjk983 aaaz84390842092njk423 ... abc/ abckhr89032423 abcnjjkth29085242nw ... ... ```
65,439,177
I have a `SQLite` file and I want to add `2550 empty (NULL)` rows. I am able to add one empty line with this code ``` INSERT INTO my_table DEFAULT VALUES ``` But I need 2550 rows. Is there any shortcut for it? I don't want to execute same code 2550 times.
2020/12/24
[ "https://Stackoverflow.com/questions/65439177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14341558/" ]
If your version of SQLite support it, you could use a recursive CTE to generate a series from 1 to 2550, and then insert "empty" records along that sequence: ```sql WITH RECURSIVE generate_series(value) AS ( SELECT 1 UNION ALL SELECT value + 1 FROM generate_series WHERE value + 1 <= 2550 ) INSERT INTO yourTable (col1, col2, ...) SELECT NULL, NULL, ... FROM generate_series; ``` It is not clear which values, if any, you want to specify for the actual insert. If you omit mention of any column in the insert, then by default SQLite should assign `NULL` or whatever default value be defined for that column.
You can generate numbers using a recursive CTE and then insert . . . but you need to be more explicit about the values being inserted: ``` with cte as ( select 1 as n union all select n + 1 from cte where n < 2550 ) insert into mytable (<something>) select <something> from cte; ``` I think you need to specify the value for at least one column in SQLite.
56,413,405
I have 3 input for select file with this names : ``` docs['selfie'] docs['id_card'] docs['bank_card'] ``` I want to check if `docs['selfie']` had file returned `yes` otherwise returned `no`. But always returns `no` function: ``` public function Document(Request $request) { if ($request->hasFile("docs['selfie']")) { return "yes"; } else { return "no"; } } ``` and form: ``` {{ html()->form('POST', route('frontend.user.send.document'))->class('form-horizontal')->Attribute('enctype','multipart/form-data')->open() }} <div class="row"> <div class="col-md-12"> <div class="form-group row"> <label class="col-form-label col-lg-2">id card</label> <div class="col-lg-10"> <div class="custom-file"> <input type="file" class="custom-file-input" id="National_Card" name="docs['id_Card']"> <label class="custom-file-label" for="docs">chose file</label> </div> </div> </div> </div> <div class="col-md-12"> <div class="form-group row"> <label class="col-form-label col-lg-2">bank card</label> <div class="col-lg-10"> <div class="custom-file"> <input type="file" class="custom-file-input" id="Bank_card" name="docs['bank_card']"> <label class="custom-file-label" for="Bank_card">chose file</label> </div> </div> </div> </div> <div class="col-md-12"> <div class="form-group row"> <label class="col-form-label col-lg-2">selfie</label> <div class="col-lg-8"> <div class="custom-file"> <input type="file" class="custom-file-input" id="Selfie" name="docs['selfie']"> <label class="custom-file-label" for="Selfie">chose file</label> </div> </div> <div class="col-lg-2"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#selfie_modal">see example</button> </div> </div> </div> </div> <div class="row"> <div class="col"> <div class="form-group mb-0 clearfix"> {{ form_submit("send docs" . ' ') }} </div><!--form-group--> </div><!--col--> </div><!--row--> {{ html()->form()->close() }} ```
2019/06/02
[ "https://Stackoverflow.com/questions/56413405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9201031/" ]
As a wrote in my comment, probably you shouldn't worry about performance too much... However, this data structure should fit your needs, let's call it a: Letter X before Y tree. Basically, a tree where each node has children for each letter if the letter appears after the parent nodes letter in the target word For each node you would store a list of all the matches. ``` public class Node { public char Letter { get; set; } public Node[] Children {get;set;} public List<string> CommandNames {get;set;} } ``` You can pre-fill it with all your known names like this ``` p paste a paste s paste .. p/a paste p/s paste p/t paste .. t/e paste .. p/a/s paste .. s/t/e paste ``` Matching your search word simply means traversing your tree for each letter entered by the user, so it boils down to O(n)
I don't know much about its time complexity, yet if we just wish to search for words that must have `a` and `e` in it, we would be starting with an expression similar to the following, then we would optimize for runtime: ``` (?=.*a)(?=.*e).* ``` ### Test ``` using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string pattern = @"(?=.*a)(?=.*e).*"; string input = @"New Open Save Save as Copy Paste Cut Select all"; RegexOptions options = RegexOptions.Multiline; foreach (Match m in Regex.Matches(input, pattern, options)) { Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index); } } } ``` ### [Demo](https://regex101.com/r/Byghzw/1/)
7,764,591
I have a View with `UIButton`, `UITextField`, and a `UIImageView` for Background. in `viewDidLoad` i try animate `UIImageView` from alpha=0 to alpha =1 using block. it's pretty basic, here's the code: ``` [UIView animateWithDuration:1.5 animations:^(void){ ((UIView*)[self.view viewWithTag:123]).alpha = 1; }completion:^(BOOL finished){ }]; ``` which is working fine. but during that 1.5 seconds of animation, my touch in current view seems to be disabled. i can't click any of the buttons or textFields until animation finish. Thanks in Advance
2011/10/14
[ "https://Stackoverflow.com/questions/7764591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554740/" ]
I ended up not doing this. You can't touch a view that still animating. that's my conclusion. Would be happy to hear some thought on this though.
Isn’t it something that happens on standart iOS apps like Settings back button, menu swipe. There is no way to touch to screen while it is animating whereas you can touch in Android.
582,771
I am having trouble printing (or searching) for sequences containing backslashes when using awk For example - ``` echo "test\test" | awk '{ gsub(/\\\\t/, "\\\\&"); print }' ``` will give the result: ``` test est ``` because the \t will be interperted as tab. I want to be able to have the string as is, meaning: ``` test\test ``` The echo command is just another way for me to check a 1 liner for the awk command to see if it can find a pattern such as \t in a file (using a bash script). To be more sprcific - If I want to have an awk cmd that needs to find a sequence of ``` \" ``` I am using the following: ``` awk -v st="$match_string" 'BEGIN {gsub(/\\\\"/,"\\\\&", st)} match($0,st {print;exit}' file.txt ``` but the cmd does not work: for a file with : ``` 547 %$ 236 \" 4523 &* 8876 (* 8756 "/ ... ``` it will output: ``` > \" 8756 "/ ``` What is the right way to use awk to find the ``` 236 \" ``` Thanks
2020/04/27
[ "https://unix.stackexchange.com/questions/582771", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/408984/" ]
Going with your own suggestion of using a shell loop: ```sh for name in ./*/*/???-*.mp4; do filename=${name##*/} # remove directory path filename=${filename#???-} # remove initial three characters and dash # prepend directory path to target filename and rename mv "$name" "${name%/*}/$filename" done ``` This loops over the names that we want to change. For each pathname, the filename portion of the pathname is extracted into the variable `filename` using a standard variable substitution. From that value, the initial three characters and the dash is removed. The original file can then be renamed using this new `$filename` value. If you need to be stricter with matching the filenames, ensuring that the first three characters are digits, replace each `?` in the patterns above with `[0-9]` or `[[:digit:]]`. --- Using the Perl `rename` utility: ``` rename -v 's/...-([^\/]*\.mp4)$/$1/' ./*/*/???-*.mp4 ``` This would apply a Perl substitution to each given filename. The substitution matches the filename but captures only the bit of the name that we want to keep at the end (a string at the very end containing no `/` character, preceded by the three characters and a dash that we'd like to remove). The matched portion of the pathname is replaced by the captured string.
You can use find and invoke a shell using `-exec` ```bsh find . -type f -exec sh -c ' for f; do d=${f##*/} d=${d#*[0-9][0-9][0-9]-} echo mv -v "$f" "${f%'/'*}/$d" done ' _ {} + ``` * The echo is there to tell you how/what is going to be executed, remove it if you think the ouptu is ok The actual output is like this. Output ``` renamed './AFolder/Afolder2/123-01-filename.mp4' -> './AFolder/Afolder2/01-filename.mp4' renamed './BFolder/Bfolder2/512-01-filename.mp4' -> './BFolder/Bfolder2/01-filename.mp4' renamed './CFolder/Cfolder2/881-01-filename.mp4' -> './CFolder/Cfolder2/01-filename.mp4' ```
924,574
I'm looking for a Git alternatives to "svn info". Today I added some information that Subversion gives me with the "svn info" command right into my build, and that is then pushed into a source file that prints this during startup. That way I always know where that build came from and how to get it back again. If you have "svn info" like URL, Repository Root, Repository UUID and the Revision, you have a good link between what is deployed and the buildsystem. And if someone reports a bug you know where that software came from, and since that information was automatically included, the risk of human error is smaller. Now the question is, what information do I need to get from Git so I can later identify where that build came from? And how do I use that information to switch back to exactly that version? (Maybe I need to add some information about the "build computer" as well since Git is distributed.) --- **Update**: Using rev-parse was really useful, and I got something like this: ``` cj@zap:~/git_test$ git rev-parse HEAD 72ce5f3e13c61f76fde5c58cefc85eed91b6f1f8 ``` And with that magic number it is later possible to do: ``` cj@zap:~/git_test$ git checkout 72ce5f3e13c61f76fde5c58cefc85eed91b6f1f8 ``` And I am back where I was. --- **Update**: I think that if I take some parts from that scripts VonC provided and put them into my buildfile I will get the result I was looking for. --- **Update**: A note on "git describe". You need a real tag (tag -a) earlier in you branch history to make this work or you will get something like this. ``` fatal: cannot describe '72ce5f3e13c61f76fde5c58cefc85eed91b6f1f8' ``` The problem is also described in *[Git Tag Does the Wrong Thing by Default](http://www.rockstarprogrammer.org/post/2008/oct/16/git-tag-does-wrong-thing-default/)*. But please note that a checkout seems to work anyway, even though that was an error message. ``` git checkout 72ce5f3e13c61f76fde5c58cefc85eed91b6f1f8 ``` The normal thing though seems to be that you create something like a "ver1.0" tag, and then if you continue to work you get something like this: ``` cj@zap:~/git_test$ git describe ver1.0-2-g4c7a057 cj@zap:~/git_test$ git tag -a ver2.0 cj@zap:~/git_test$ git describe ver2.0 cj@zap:~/git_test$ git commit . -m "something..." Created commit ac38a9d: something... 1 files changed, 1 insertions(+), 0 deletions(-) cj@zap:~/git_test$ git describe ver2.0-1-gac38a9d ``` So when you use `describe` correctly it does work and may produce a more human-readable results, and it can be really useful as well.
2009/05/29
[ "https://Stackoverflow.com/questions/924574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51425/" ]
To complete Charles's answer, you also can make a script displaying "sn info" like information, like [this one](http://blog.inquirylabs.com/2008/06/12/git-info-kinda-like-svn-info/) (already [mentioned there](http://kerneltrap.org/mailarchive/git/2007/11/12/406496)) ```sh #!/bin/bash # author: Duane Johnson # email: duane.johnson@gmail.com # date: 2008 Jun 12 # license: MIT # # Based on discussion at http://kerneltrap.org/mailarchive/git/2007/11/12/406496 pushd . >/dev/null # Find base of git directory while [ ! -d .git ] && [ ! `pwd` = "/" ]; do cd ..; done # Show various information about this git directory if [ -d .git ]; then echo "== Remote URL: `git remote -v`" echo "== Remote Branches: " git branch -r echo echo "== Local Branches:" git branch echo echo "== Configuration (.git/config)" cat .git/config echo echo "== Most Recent Commit" git --no-pager log -n1 echo echo "Type 'git log' for more commits, or 'git show' for full commit details." else echo "Not a git repository." fi --- popd >/dev/null ``` Which would produce something like: ``` == Remote URL: origin git@github.com:canadaduane/my-project.git == Remote Branches: origin/work trunk trunk@1309 trunk@2570 trunk@8 == Local Branches: master * work == Configuration (.git/config) [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [svn-remote "svn"] url = svn+ssh://svn.my-project.com/srv/svn fetch = my-project/trunk:refs/remotes/trunk [remote "origin"] url = git@github.com:canadaduane/my-project.git fetch = refs/heads/*:refs/remotes/origin/* [github] user = canadaduane repo = my-project == Most Recent Commit commit b47dce8b4102faf1cedc8aa3554cb58d76e0cbc1 Author: Duane Johnson <duane.johnson@gmail.com> Date: Wed Jun 11 17:00:33 2008 -0600 Added changes to database schema that will allow decentralization from content pointers table type 'git log' for more, or 'git show' for full commit details. ```
Here's gitinfo.ps1 (or Get-GitInfo.ps1 for the purists), a PowerShell version of Duane Johnson's shell script: ``` # From http://stackoverflow.com/a/924657/990504 # Duane Johnson's script translated to PowerShell by Jonathan Fischer 2015.04.25 Push-Location . # Find base of git directory while ( $true ) { if ( Test-Path -PathType container .git ) { # Show various information about this git directory Write-Output "== Remote URL: $(git remote -v)" Write-Output "`n== Remote Branches: " git branch -r Write-Output "`n== Local Branches:" git branch Write-Output "`n== Configuration (.git/config)" Get-Content .git/config Write-Output "`n== Most Recent Commit" git log --max-count=1 Write-Output "Type 'git log' for more commits, or 'git show' for full commit details." break } # Try parent directory. Set-Location .. # Stop if at root of drive. if ( (Get-Location).Path -match "[A-Z]:\\$" ) { Write-Error "Not a Git repository." break } } # Note: even though the popd was not strictly necessary in the bash version # unless the script was sourced/dotted, PowerShell has the questionable behavior # where scripts modify the current directory (and environment!) of the calling # process. So we need the Pop-Location. Pop-Location ```
12,666
My question is about adding a new language into LaTeX: the [Tajik language](http://en.wikipedia.org/wiki/Tajik_alphabet). There is Russian language support in LaTeX and Russian is written using a modified version of the Cyrillic alphabet. Tajik is also written in the Cyrillic alphabet and its orthography is very close to Russian. So, how can I add Tajik language support in LaTeX? Is there any manual about adding new languages into LaTeX? Thank you
2011/03/04
[ "https://tex.stackexchange.com/questions/12666", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/3148/" ]
`Babel` provides currently a minimal tentative locale which can be used with little effort with XeLaTeX and LuaLaTeX. Download the files under the directory for the Tajik locale in the `babel` [GitHub repository](https://github.com/latex3/babel/tree/main/locale-templates/tg) and move them to a place where LaTeX can find them (eg, in the same folder as the document). Stay tuned to the messages in the log file explaining how to declare captions, if you need them. ```tex \documentclass{article} \usepackage[tajik, provide=*]{babel} \babelfont{rm}{FreeSerif} \begin{document} Абӯалӣ Сино дар рушди илми тибсаҳми бениҳоят арзандае гузоштааст, ки аз таҷрибаҳои худ, илми пизишкии олими грек Гален, метафизикаи Арасту (Сино яке аз шарҳдиҳандагони асосии Арасту буд), илми пизишкии Форс, Байнаннаҳрайн ва Ҳинди қадима сарчашма гирифта, онҳоро ҳамҷоя андӯхтааст. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/UiLBN.jpg)](https://i.stack.imgur.com/UiLBN.jpg) Sadly, it seems no hyphenation patterns are currently available. Feel free to contribute to the improvement of this locale (or any other).
And today I have found out another way to make LaTeX understand Tajik language. I achieved that using two packages: **inputenc** with *utf8* option and **fontenc** with *T2A*(or *T2B*, but not ~~T2C~~) option. ``` \usepackage[utf8]{inputenc} \usepackage[T2A]{fontenc} ``` LaTeX is really great!
33,446,814
I have attempted using a nested if in the following code. I have initialized variables but the compiler is telling me that the variable named 'bill' is not initialized even though it has been. Why is the compiler not recognizing the value assigned to the variable? Please see the notes in the code below. ``` package killMe; import java.util.Scanner; public class Kill_Me { static Scanner console = new Scanner(System.in); static double PREMIUM_SERVICE = 55.00; static double PREMIUM_DAY_OVERTIME_MIN = 0.20; static double PREMIUM_NIGHT_OVERTIME_MIN = 0.15; static double REGULAR_SERVICE = 30.00; static double REGULAR_OVERTIME_MIN = 0.40; public static void main(String[] args) { int acctNumber; double premiumDayMin; double premiumNightMin; double bill; double minutes; String name; String premium = "PREMIUM"; String regular = "REGULAR"; System.out.println("What is the Account Number? "); acctNumber = console.nextInt(); System.out.println("What is the Customer Name? "); name = console.next(); System.out.println("Is the Service Code Premium or Regular? "); String strService = console.next(); String strServiceCAP = strService.toUpperCase(); if(strServiceCAP.compareTo(premium) == 0) { System.out.println("How many Day Minutes were used? "); premiumDayMin = console.nextDouble(); System.out.println("How many Night Minutes were used? "); premiumNightMin = console.nextDouble(); if(premiumDayMin <0 && premiumNightMin <0) { System.out.println("Minutes cannot be less than 0 "); } else if(premiumDayMin <= 75 && premiumNightMin <= 100) { bill = PREMIUM_SERVICE; } else bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100) * PREMIUM_NIGHT_OVERTIME_MIN; minutes = premiumDayMin + premiumNightMin; System.out.println("Customer Name: " + name); System.out.println("Account Number: " + acctNumber); System.out.println("Service Type: " + strServiceCAP); System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin); System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin); System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized". } else if(strServiceCAP.compareTo(regular) == 0) { System.out.println("How many minutes were used? "); minutes = console.nextDouble(); bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN; System.out.println("Customer Name: " + name); System.out.println("Account Number: " + acctNumber); System.out.println("Service Type: " + strServiceCAP); System.out.println("Minutes Regular Service Used: " + minutes); System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here. } else { System.out.println("Invalid Service Type"); } } // End of main } // End of class ```
2015/10/31
[ "https://Stackoverflow.com/questions/33446814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5327794/" ]
No, `bill` has not been initialized in all cases. Understand this: the Java compiler will never, ever, evaluate boolean expressions; Simplified version: ``` double bill; if (c1) { bill = v1; } else if (c2) { bill = v2; } // try and use bill here ``` Even if, *according to your logic*, boolean expressions `c1` and `c2` may cover all possible cases, the compiler cannot ensure that this is the case. This is the root cause of your error, however deep your if/else, switch, etc statements may be nested.
I'm not sure why it gets this error, but try initialising bill as 0.00 when you declare the variable. Also, if(premiumDayMin <0 && premiumNightMin <0) should probably be changed to if(premiumDayMin <0 || premiumNightMin <0) Because you want to make sure that either minutes is not less then zero. You're program should then probably handle this error, because the rest of the program still executes. But maybe you're getting on to that :-P.
9,390,179
I have a list that contains many objects.I want found an object in this list that every properties equals to an object in list. for example: ``` list.Add(object1,object2,object3,object4); // for example I want found object3 //list.find(object3) ``` and I have a problem I must check every its properties except one. for example object have this properties (int prop1,int prop2,int prop3). I want found object that prop1 and prop2 are equaled with any item of list;
2012/02/22
[ "https://Stackoverflow.com/questions/9390179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129318/" ]
So, seems you like to get the Contains-Method of the List to work for you. Have a look here: [MSDN List.Contains](http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx) According to it, you can implement IEquatable in your object to make it happen. Hope that helps. Cheers Sascha
There's always the [Linq](http://msdn.microsoft.com/en-us/library/system.linq.aspx) way of doing things. For example: ``` var haystack = new List<Tuple<int, bool, string>>() { new Tuple<int, bool, string>(1, true, "one"), new Tuple<int, bool, string>(2, false, "two"), new Tuple<int, bool, string>(3, true, "three"), new Tuple<int, bool, string>(4, true, "four") }; var needle = new Tuple<int, bool, string>(3, true, "three"); var found = haystack.FirstOrDefault( t => t.Item1 == needle.Item1 && t.Item2 == needle.Item2 && t.Item3 == needle.Item3); Assert.AreSame(haystack[2], found); ``` The `Assert.AreSame` test passes when I run this.
244,406
Could receiving in a text or an email, a URL link just like <https://security.stackexchange.com/questions/ask> of a website, which could be a pernicious one, ever pose a security problem at all? What I am asking is that: if I receive such a link but do NOT click on it, will it ever do harm to my account, computer or other website I will ever visit? --- **Edit**: As a specific example, I would like to ask about the situation for receiving a link, `https://down[.]nnjah68[.]me/app.php/Mjl1to`, in WhatsApp.
2021/02/07
[ "https://security.stackexchange.com/questions/244406", "https://security.stackexchange.com", "https://security.stackexchange.com/users/250614/" ]
Some software will automatically fetch any URL it sees, even if you don't click it. A few examples: * Browsers that are configured to pre-fetch certain URLs so that they load instantly after clicking (this isn't default on any major browser I'm aware of, but I've seen it). * Messaging clients that show a preview of the page (text and/or image thumbnail) when you send or receive a message with a link. * Browser extensions that pre-fetch certain links to check the page for malware (part of some AV suites). In any of these cases, a vulnerability in the HTTP client (browser, AV software, messaging app or server, etc.) could be exploited by an attacker. However, such vulnerabilities are relatively rare unless the client supports JS (it is very hard to make a JS engine fully secure, though of course the developers try) and often sandboxed to limit the damage even if they are vulnerable. Also, note that - in an ideal world where everything works correctly - fetching a URL would always be safe (it shouldn't be possible for fetching a URL to do anything harmful) and wouldn't even be state-changing (GET *should* be idempotent). Obviously, the real world is not nearly so ideal, since both software vulnerabilities and websites that ignore various standards exist. However, *because* those things exist, and for privacy reasons (fetching a URL always exposes, at a minimum, an IP address), automatically fetching URLs is relatively rare. Just *looking at* a link (without fetching/visiting it) isn't going to be dangerous unless your text rendering library has some seriously wacky bugs, and most likely they could be set off by non-link text in a situation like that anyhow.
**Yes** We can be pretty sure this can happen, because something very similar to it did: <https://www.nbcnews.com/tech/security/android-flaw-could-let-hackers-take-over-phone-text-n399016> **Stage-fright**: There was a bug that got named Stage-fright which was in the image or video-processing on Android. Because some apps will "view" media automatically to generate a preview, the app automatically runs the media through the buggy library without the need for user intervention. **Back to your question**: Currently, many messaging apps, including Discord, generate a preview of links that are sent to you. If a similar bug were to come back, it would almost certainly affect people who view the link without opening it, since the app needs to render the link preview.
43,775
Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
2008/09/04
[ "https://Stackoverflow.com/questions/43775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876/" ]
Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1). e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3
As explained in other answers, there are many choices for a modulo operation with negative values. In general different languages (and different machine architectures) will give a different result. According to the [Python reference manual](http://docs.python.org/ref/binary.html), > > The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand. > > > is the choice taken by Python. Basically modulo is defined so that this always holds: ``` x == (x/y)*y + (x%y) ``` so it makes sense that (-2)%5 = -2 - (-2/5)\*5 = 3
5,872,799
I am trying to execute the following code as part of a migration in a transaction, but the code fails unless I put the `GO` statement after the `ADD CONSTRAINT` statement: ``` ALTER TABLE T ADD C INT NULL ALTER TABLE T ADD CONSTRAINT DF_T_C DEFAULT ((1)) FOR C GO UPDATE T SET C = DEFAULT ALTER TABLE T ALTER COLUMN C INT NOT NULL ``` If I leave out the `GO` statement I get the following error: > > Invalid column name 'C'. > > > The code executing the migration cannot handle the `GO` statement, how can I get this to work in a single transaction?
2011/05/03
[ "https://Stackoverflow.com/questions/5872799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4830/" ]
You can use `EXEC` for the problematic statements so they get compiled as a different batch. ``` EXEC('UPDATE T SET C = DEFAULT; ALTER TABLE T ALTER COLUMN C INT NOT NULL') ``` But you can also do ``` ALTER TABLE T ADD C INT NOT NULL CONSTRAINT DF_T_C DEFAULT ((1)) ``` Rather than doing all these individual steps yourself.
``` SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; SET XACT_ABORT ON; BEGIN TRANSACTION; ALTER TABLE T ADD C INT NULL; ALTER TABLE T ADD CONSTRAINT DF_T_C DEFAULT ((1)) FOR C; EXEC ('UPDATE T SET C = DEFAULT'); ALTER TABLE T ALTER COLUMN C INT NOT NULL; COMMIT TRANSACTION; ```
19,452,943
In the following usable example code I define two dictionaries `a` and `b` which I want to combine ``` a = {'device': {'version': '1.2.3'}} b = {'device': {'name': 'testdevice'}} c = {'other': {'cost': '1000'}} q = {} q.update(a) q.update(b) q.update(c) print q p = {} p = dict(p.items() + a.items()) p = dict(p.items() + b.items()) p = dict(p.items() + c.items()) print p ``` i.e. the resulting dictionary should be equal to ``` result = {'device': {'name': 'testdevice', 'version': '1.2.3'}, 'other': {'cost':'1000'}} ``` but the two examples in the code always give: ``` {'device': {'name': 'testdevice'}, 'other': {'cost':'1000'}} ``` Is there a simple way (without classes/functions) to achieve this? I want to combine the dictionary entries of the same level. It can be assumed there are only two levels. The example code itself can be simplified, but it will be used later in a loop where many dictionaries might be 'added/merged' together.
2013/10/18
[ "https://Stackoverflow.com/questions/19452943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1581090/" ]
As explained by Rohit [here](https://stackoverflow.com/questions/14789478/strange-java-null-behavior-in-method-overloading/14789492#14789492), > > That is because String class extends from Object and hence is more > specific to Object. So, compiler decides to invoke that method. > Remember, Compiler always chooses the most specific method to invoke. > > > If more than one member method is both accessible and applicable to a > method invocation, it is necessary to choose one to provide the > descriptor for the run-time method dispatch. The Java programming > language uses the rule that the most specific method is chosen. > > > The informal intuition is that one method is more specific than > another if any invocation handled by the first method could be passed > on to the other one without a compile-time type error. > > > However, if you have two methods with parameter - String, and Integer, > then you would get ambiguity error for null, as compiler cannot decide > which one is more specific, as they are non-covariant types. > > > As described in Section [15.12.5](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5) of JLS > > >
public void method1(String str) will get executed because object is string supperclass so the string method will be called.
1,543
I'm currently rebuilding our entire intranet from scratch, mostly because the tech behind is out-dated and it has been proved that a lot of information is difficult to find. Though that is beside the point, what I am wondering is what would be the optimum amount of users to use for qualitative and quantitative testing with a userbase of around 1000 users? Is there a general rule of thumb for both based on the total number of users you have? or is it just say 5 for qualitative and 10 for quantitative? What would be the best approach?
2010/09/17
[ "https://ux.stackexchange.com/questions/1543", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/128/" ]
Something else to consider is where the result of your usability report is going. How much work can the people downstream from you fix - and what will the effect of those fixes be? Say I run a test with fifteen people. After the first three I've spotted problems A B C. By the end of the fifteen I've also spotted problems D E F G. The problem is that the team downstream from me only have time to fix A and B. Even worse - once we've fixed A and B the system has changed, and the next most serious usability issues may well not be C-G. So I'd look at the whole cycle time of your product development folk - and only do just enough usability testing to fill the queue of work. Any more than that is likely to be waste. It's been my experience that doing more usability tests with fewer partipants (even just one)spread throughout the development process is far more effective than few large tests.
For quantitative testing, it's possible to be more explicit about the effect of the sample size on your results but the number of users you need depends on the particular tests or analyses you are considering (examples could be determining the proportion of participants successfully completing a task, estimating the average time-on-task, comparing two versions with a questionnaire like the SUMI or the SUS…) It's therefore difficult to give a rule of thumb that would be useful for all situations but there are techniques to find out the sample size you need in a given situation. Now, if you don't want to go over all this trouble and actually estimate things like confidence intervals and statistical power, there are still two important conclusions to remember. The first one is that the precision of the estimate and therefore the number of users you need to achieve a given level of precision do *not* depend on the size of your user base, at least as long as this user base is much larger than your test sample. The second one is that the bigger your sample size is, the smaller the improvement you can expect from additional test users will be. Thus, going from 10 to 110 is a huge improvement, going from 1000 to 1100 not so much. That's why opinion polls often have samples of about 1000 participants, even when the population of interest includes several millions people. In fact, the sample size for a pre-election poll will typically be very similar in countries with 5, 80 or 200 millions inhabitants. As long as your sample is random and the population is much larger, it does not matter if you are asking only 1%, 0.1% or 0.00001% of the total number of voters. Both of these conclusions are still true for other things than percentages: for example comparisons between ratings on a satisfaction questionnaire or analyses of the time it takes to complete a task. If you want to go futher, one good starting point is Jeff Sauro's website <http://www.measuringusability.com/>
56,050,352
I'm trying to run a function when the location path is changed OR an object via a service is changed. I can't see to fire the function at all. ``` var settings = { value : service.cache.MY_VALUE, location: $location.path() } $scope.$watchCollection(function(){ return settings; }, function(newValue, oldValue){ console.log('New value detected in settings'); }); ``` Why isn't the console getting triggered when I go to a new URL or change the cached value?
2019/05/08
[ "https://Stackoverflow.com/questions/56050352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866206/" ]
When initializing a variable with an object literal, any function inside that literal is invoked only once: > > ERRONEOUS > > > > ``` > var settings = { > value : service.cache.MY_VALUE, > location: $location.path() > } > > ``` > > The `$location.path()` function needs to be invoked every digest cycle: ``` function settingsFn() { return { value : service.cache.MY_VALUE, location: $location.path() } } $scope.$watchCollection( settingsFn, function(newValue, oldValue){ console.log('New value detected in settings', newValue); }); ``` By placing the object literal inside the `settingsFn` function, the `$location.path()` function is invoked each time the `settingsFn` function is invoked.
Might be a silly question, but how are you changing those values? If you're expecting settings.value to change when your service cache changes, or settings.location to change when your path changes, it won't affect $scope.settings at all. Otherwise, what you want is a deep watch. Use $watch instead of $watchCollection, and add `true` as the 3rd argument. [Watch entire object (deep watch) with AngularJS](https://stackoverflow.com/questions/20277479/watch-entire-object-deep-watch-with-angularjs/20277689)
491,061
The standard System.Windows.Forms.TabControl component draws a border around the TabPages it contains. If you set its Dock to Fill, these borders run up to the edge of the parent control, but they're still there, taking up screen space. In Visual Studio, if you dock two windows in the same place, you get a TabControl-like set of tabs along the bottom, but no borders along the sides. Is it possible to get a TabControl to display its TabPages in this manner, with no wasted screen space at the sides? If possible, I'd like to avoid solutions that involve painting the control myself.
2009/01/29
[ "https://Stackoverflow.com/questions/491061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
Instead of using the Dock property you should try using the Anchor to anchor each of the four sides. Then you need to position the TabControl so it is positioned a couple of pixels bigger on all sides that the parent. That way the borders are hidden because they cannot be drawn when behind the parent control.
Using the standard .NET tab control, this isn't directly possible. What is the ultimate goal for this? Are you trying to simulate the same type of tabbed-MDI style display as Visual Studio? If that's the case, there are several third-party solutions available - some open source and some commercial. The other responses about using the Anchor property in combination with setting the size so it is just a bit larger than the actual window might work, but I think it might look a bit odd visually. It should work regardless of the theme and accessibility settings, but you may end up having to programmatically set the size to be a few pixels larger than the parent.
6,807,800
I have a jQuery .get call that hits a URL which returns true or false based on whether the user is signed in or not. This allows me to redirect the user to a login form if they aren't authenticated rather than the entire page being displayed in a small div (which holds content a signed in user should be able to see) I think there is a problem with my .get syntax: ``` $(document).ready( function () { function logInCheck() { $.get({{ path('signed_in_check') }}, function(data) { var loggedIn = data; alert(loggedIn); }); } logInCheck(); }); ``` This doesn't work, and even if I replace alert(loggedIn) with alert("hello"), the alert doesn't get called.
2011/07/24
[ "https://Stackoverflow.com/questions/6807800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324243/" ]
If you want to wait for the dialog box to close, the "open" property indicates whether the dialog box is open or closed. When it's done, resolve the promise. For synchronization, add a timer to periodically test this property. ``` let d = document.querySelector('dialog') d.showModal() await new Promise((resolve, reject) => { let timer = setInterval(_ => { if (!d.open) { resolve() clearInterval(timer) } }, 500) }) ```
Use `Bootstap' modal Then remove close button and disable model window hide by using below code ``` $('#myModal').modal({backdrop: 'static', keyboard: false}) ``` Bind your function and close event to OK button of that modal window.
19,444,267
Can we regenerate .java file from .class file using javap tool of jdk? I used `javap classsfile` command, it just prints .java file with data member and member functions declaration. If not then what are the appropriate methods to accomplish it...
2013/10/18
[ "https://Stackoverflow.com/questions/19444267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2590102/" ]
generating .java from .class is called decompililng. So you need some decompiler to generate .java from .class here are some of the open source decompiler [link1](http://cavaj-java-decompiler.en.softonic.com/) [link2](http://java.decompiler.free.fr/) [link3](http://downloads.phpnuke.org/en/download-item-view-g-v-v-g-v/DJ+JAVA+DECOMPILER.htm) [link4](http://jdec.sourceforge.net/)
Yes its possible using java Decompiler.Please download java Decompiler or go through this url <http://jd.benow.ca/>
56,545,582
I am scripting a solution that requires passing %USERPROFILE% to the registry in local\_machine. For example ``` DotJetFolder=%USERPROFILE%\JetFolder ``` But it seems like registry doesn't understand this format. Looking for ideas on how to implement it. This for an RDS solution where we can't pre-determine the user profile. Is there any way to pass this sort of variable to the registry.
2019/06/11
[ "https://Stackoverflow.com/questions/56545582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2782109/" ]
You need to create the value as a REG\_EXPAND\_SZ value if you want environment variables in the string to be expanded when Windows reads the value. In PowerShell the creation of such a value would look somewhat like this: ```bsh $key = 'HKLM:\some\where' $name = 'DotJetFolder' $value = '%USERPROFILE%\JetFolder' Set-ItemProperty -Path $key -Name $name -Value $value -Type ExpandString ```
From what I understand, you want to have a sub for "%USERPROFILE%" ``` $temp = "$env:USERPROFILE" + "\Jet" Write-Host $temp ``` Hope it Helps! BR
18,152,153
I have successfully used DP to get optimal solution to a problem. The issue I am facing though is, now if I want to reconstruct the solution, I end up with only one such way to get optimal solution. Is there a way, such that I will be able to backtrack all the ways/choices which could have lead to an optimum result?? e.g If I am selecting a team from players a, b, c, d with skills {1, 2, 2, 1}, I can get that optimum team skill count will be 3 and I can get one possible way to achieve this as {{a, b}, {c, d}}. What I am looking for is, a way so that I can get all the ways in which I can divide the team fairly with team skill count as 3 i.e {{a, c}, {b, d}} and {{a, b}, {c, d}}
2013/08/09
[ "https://Stackoverflow.com/questions/18152153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1072192/" ]
The dispatch to one of the `whatIs`methods is decided by the compiler at compile time. The call to one of the `area`methods is decided at runtime, based on the actual class of the object that is referenced.
Q: Why can the Java compiler accurately distinguish between overridden methods for related objects, but not overloaded methods ... why can Java not handle a situation like this? A: You've got the question backwards. Java *ALLOWS* you to distinguish between "overloading" and "overriding". It doesn't try to second-guess what you *mean*, it gives you a choice to use one or the other.
2,139,798
In development blogs, online code examples and (recently) even a book, I keep stumbling about code like this: ``` var y = x as T; y.SomeMethod(); ``` or, even worse: ``` (x as T).SomeMethod(); ``` That doesn't make sense to me. If you are sure that `x` is of type `T`, you should use a direct cast: `(T)x`. If you are not sure, you can use `as` but need to check for `null` before performing some operation. All that the above code does is to turn a (useful) `InvalidCastException` into a (useless) `NullReferenceException`. Am I the only one who thinks that this a blatant abuse of the `as` keyword? Or did I miss something obvious and the above pattern actually makes sense?
2010/01/26
[ "https://Stackoverflow.com/questions/2139798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87698/" ]
Using 'as' does not apply user defined conversions while the cast will use them where appropriate. That can be an important difference in some cases.
I've often seen references to [this misleading article](http://www.codeproject.com/KB/cs/csharpcasts.aspx) as evidence that "as" is faster than casting. One of the more obvious misleading aspects of this article is the graphic, which does not indicate what is being measured: I suspect it's measuring *failed* casts (where "as" is obviously much faster as no exception is thrown). If you take the time to do the measurements, then you'll see that casting is, as you'd expect, *faster* than "as" when the cast succeeds. I suspect this may be one reason for "cargo cult" use of the as keyword instead of a cast.
205,259
It seems to be that **innovation projects** refer to those projects that are going to innovate current systems or practices with newer things, or generally speaking, bringing something newer to replace existing ones within a given scope. For example, upgrade from 3G network to 4G network, or from 2G to 3G. The process is bringing something newer, but they may be not "new" globally (in the world). However, **innovative projects** mean the projects that want to bring something new (creative) to this world. For example, develop a 5G or 6G network, which has not yet even on the planet. Do I understand right?
2014/10/29
[ "https://english.stackexchange.com/questions/205259", "https://english.stackexchange.com", "https://english.stackexchange.com/users/80485/" ]
My take on these phrases is one of aspiration versus declaration. An "innovative project" has, in fact, produced an innovation. Conversely, an "innovation project" merely hopes to produce an innovation, but it might not have happened yet. As always, the borders of these words are smeared by hyperbolic usages, such as describing a project as being innovative because is has a goal to be innovative. So, take this with a grain of salt.
Looking at the meaning of the two terms, they actually refer to the development of something new, which didn't exist or is significantly different from what existed before. The process you refer to in your definition of 'innovation process' is more an 'upgrade process' or an 'update process'. [Innovation](http://www.businessdictionary.com/definition/innovation.html): > > * **The process of translating an idea or invention into a good or service that creates value or for which customers will pay**. Innovation involves deliberate application of information, imagination and initiative in deriving greater or different values from resources, and includes all processes by which new ideas are generated and converted into useful products. > > > [Innovative](http://www.businessdictionary.com/definition/innovative.html) : > > * the quality of an idea which is new and different. > * characterized by, tending to, or introducing innovations. > > > Source: (businessdictionary)
65,556
A car rental company in Iceland charges extra for two people driving the car. I was wondering what would happen if we pay the fee for only one person, but have an alternate person drive. How will they come to know this? Not just asking to evade fee, but also need to know this for emergency.
2016/03/22
[ "https://travel.stackexchange.com/questions/65556", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/41501/" ]
I usually rent a car to travel with my family during weekends. I would guess if someone else drove the car instead of me, the company would never know *unless* you have some accident. And then you are in serious trouble, because insurance would not cover it - it's in the contract. It is a bit like those european cities where you buy a public transit ticket, but there is usually no one on the bus or train to take it. You keep it in your pocket. Or you simply walk into the train and ride. A lot of times this will work and you'll save some money, but if the ticket man comes, you are fined. In the end it would be a matter of risk versus benefit. My personal rule is the following: *Only ask for a second (unauthorized) driver to take the wheel if the risk of accident with the this driver is significantly lower than yours.* This usually means asking my wife to drive if I am too sleepy or tired - which is not uncommon. But, of course I should not be doing this, because the extra fee is insignificant given the peace of mind. Well, at least in Brazil.
If you buy insurance or a loss/damage waiver (LDW) from the rental-car company, it won't cover any damage that occurs while a non-authorized driver is at the wheel, if they find out. But, *don't* buy insurance or a loss/damage waiver from the rental-car company. It's a scam. I was renting at Alamo and the guy was pressuring me to buy LDW to cover my $1000 deductible, for $25 a day (on a $12-a-day car). I said, "Do you think I get in an accident every 40 days?" The guy just gave me a blank look. "$1000 is $25 a day for 40 days. I get in an accident every 10 years." Alamo sucks. First, see if your own auto-insurance will cover you. In most cases, it *will* in your own country and *won't* in other countries. Next, see if your credit-card will cover you. In most cases, it will. It won't in Italy. Italy sucks. I rented in France. The rental company (Avis) in Marseilles claimed I scratched the hood and billed me $600 for it. I filed a claim with my credit-card (AmEx). AmEx tried to get some sort of explanation out of Avis for six months, and finally gave up and paid me $500. France sucks. Avis sucks too.
61,861,767
Let's say I have this. ``` Words Mark Suffix Happily ly Emotional dom Emotionally Surfdom ``` I want to mark 1 if the word ends with some suffix in the suffix list, and 0 otherwise. ``` Words Mark Suffix Happily 1 ly Emotional 0 dom Emotionally 1 Surfdom 1 ``` I tried `lookup` and `vlookup` but they are incomplete. How can I do this?
2020/05/18
[ "https://Stackoverflow.com/questions/61861767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120443/" ]
I believe you are looking for `COUNTIF` with `OR` construct in itself through wildcards: ``` =SUMPRODUCT(COUNTIF(A2,"*"&C$2:C$3)) ``` Or if you have O365, `=SUM()` instead of `=SUMPRODUCT()`. If you don't need to refer to column C per se, we can create our own array: ``` =SUM(COUNTIF(A2,{"*ly","*dom"})) ``` This would always give you either 1 or 0 since a string can only have one ending =) ---
If those three columns are A,B & C then B2 = `=IF(OR(RIGHT(A2,LEN($C$2))=$C$2,RIGHT(A2,LEN($C$3))=$C$3),1,0)` Above formula gives flexibility, to put any values in C2 and C3 and mark them. You don't have to refer to column C `=IF(OR(RIGHT(A2,2)="ly",RIGHT(A2,3)="dom"),1,0)` This is not suitable if you have a large data in column C. In that case, you may need a VBA solution.
3,448,849
I am trying to write an Object of kind "HashMap" to a file & recover it when my program run again. But I faced with an EOFException when I try to read that object and the Object is not read from the file. I use the flush() & close() methods when I wrote the object for the FileOutputStream & ObjectOutputStream. Also I create OutputStream & InputStream together for my file. here is my code: ``` DataOutputStream outToFile; DataInputStream inFromFile; ObjectOutputStream writeTableToFile; ObjectInputStream readTableFromFile; File tableFile; public DNS(){ try { tableFile = new File("table.txt"); outToFile = new DataOutputStream(new FileOutputStream(tableFile) ); writeTableToFile = new ObjectOutputStream(outToFile); inFromFile = new DataInputStream(new FileInputStream(tableFile)); readTableFromFile = new ObjectInputStream(inFromFile); HashMap table2 = (HashMap) readTableFromFile.readObject(); if (table2 == null) table=new HashMap(100); else table = table2; } catch (FileNotFoundException e) { e.printStackTrace(); }catch(EOFException e){ table=new HashMap(100); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } ``` } and here is code for writing object: ``` table.put(NameField.getText(), IPField.getText()); try { //writeTableToFile.reset(); writeTableToFile.writeObject(table); writeTableToFile.flush(); } catch (IOException e1) { e1.printStackTrace(); } ``` Regards, sajad
2010/08/10
[ "https://Stackoverflow.com/questions/3448849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411186/" ]
I recently stumbled across [this article on Brain.Save()](https://web.archive.org/web/20090617064403/http://hyperthink.net/blog/recycling-appdomains-not-cans/) which talks about exactly this issue from the point of view of hosting WCF (he's Steve Maine - A program manager at Redmond on the Connected Servies Division). They need to be able to do this when a WCF service is hosted inside Asp.Net since they need to be able to shutdown any open listeners so that the WCF engine in the new app domain will be able to open them all up again. As the article demonstrates, the answer is to implement the [IRegisteredObject interface](http://msdn.microsoft.com/en-us/library/system.web.hosting.iregisteredobject.aspx), call `ApplicationManager.CreateObject` to create an instance of your object and then register it with `HostingEnvironment.RegisterObject` (all detailed in the MSDN documentation for the interface). When this object's `IRegisteredObject.Stop(bool)` implementation is called with `false` as the parameter, this is notification that the app domain is being shut down and that the object should be unregistered (kind of like a global dispose) with a call to `HostingEnvironment.UnregisterObject`. When it's called with `true` it means you've not unregistered in good time, and that if you don't Unregister immediately, it'll be done for you. I can certainly use this mechanism to find out, when an exception occurs, if the AppDomain is being killed or not. The nature of the object in question that throws the exception means that if it's not at shutdown, it must be during initial startup. Equally, however, I may well start looking at this persistence mechanism for some of my other more complicated static information! The History ----------- The article also explains some of the history, and rationale, of why you would want to use `IRegisteredObject` rather than **Application\_Start** and **Application\_End** methods in `global.asax`: > > Traditional ASP.NET applications can hook application lifecycle events (application startup/shutdown) by implementing methods like Application\_Start and Application\_Stop in global.asax. However, global.asax is for application code. Infrastructure pieces (of which the WCF hosting system is one) need a mechanism of hooking AppDomain lifecycle events that do not involve dumping infrastructure code in your global.asax file. That space is reserved for you, the user, and it would be rude of use to pollute that with a bunch of hosting goo we need to make the whole thing work. Instead, the ASP.NET folks did some great work during the Whidbey release to open up the hosting API’s and make it easy for people like WCF to come along and hook these lifecycle events in a way that’s invisible to application code. > > >
Not sure exactly what you want to do when the appication pool recycles but if you add the below event handler to Global.asax then the code in it will run when the application is shut down. ``` protected void Application_End(object sender, EventArgs e) { } ```
39,604,329
I have my .css already linked. Cant find how to also link .js propely. ``` <html> <head> <title>Final</title> <link rel="stylesheet" type="text/css" href="final.css"> </head> <body> </body> </html> ```
2016/09/20
[ "https://Stackoverflow.com/questions/39604329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6855411/" ]
By use of the script tag. ([MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)) ``` <script src="filename.js" type="text/javascript"></script> ``` The above is the simple, short answer. Standard practice tends to be, for most JavaScript, to place the script tag at the bottom of the body or to 'defer' it in the head. This is so that the loading of JavaScript does not slow the page itself from loading. To do either of these, see the following: ``` <head> <!-- OTHER HTML STUFF! --> <!-- This particular script will be deferred after document parsing. --> <script src="filename.js" type="text/javascript" defer></script> </head> <body> <!-- STRUCTURE AND SUCH OF PAGE --> <!-- This particular script will load after the body. --> <script src="filename.js" type="text/javascript"></script> </body> ``` There are more strategies with their own advantages and disadvantages, and it's a deeper topic, but the above basics should be good as a standard practice. An excellent and concise summary of the topic can be seen [here](http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html).
``` <script type=“text/javascript" src="filename.js"></script> ```
3,970,746
I use `target="_blank"` to open links in a new tab. But in IE it opens a new window which is completely logical because that is what `_blank` is supposed to do. And i don't know how `target="_blank"` behaves in other browsers. Is there something to force links to open in a new tab. If the browser supports tabs... else make a new window
2010/10/19
[ "https://Stackoverflow.com/questions/3970746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158455/" ]
The way the browser handles new windows vs new tab is set in the browser's options and can only be changed by the user.
You can change the way Safari opens a new page in Safari > Preferences > Tabs > 'Open pages in tabs instead of windows' > 'Automatically'
203,308
With the following code: ``` \documentclass[a4paper]{report} \usepackage{lipsum} \begin{document} a \begin{center} \begin{tabular}{|c|c|c|} \hline Ord & Esplicito (Adam-Bashforth) & Implicito (Adam-Moulton) \\\hline 0 & & $y_{n+1}=y_n+hf_{n+1}$ Eulero implicito \\\hline 1 & $y_{n+1}=y_n+hf_n$, Eulero esplicito & $y_{n+1}=y_n+\frac{h}{2}(f_{n+1}+f_n)$ Greg-Nickolson \\\hline 2 & $y_{n+1}=y_n+\frac{h}{2}(2f_n-f_{n-1})$ & $y_{n+1}=y_n+\frac{h}{12}(5f_{n+1}+8f_n-f_{n-1})$ \\\hline 3 & $y_{n+1}=y_n+\frac{h}{12}(23f_n-16f_{n-1}+5f_{n-2})$ & \\\hline \end{tabular} \end{center} \lipsum[1] \begin{center} \begin{tabular}{|c|c|c|} \hline Ord & Esplicito (Adam-Bashforth) & Implicito (Adam-Moulton) \\\hline 0 & & $y_{n+1}=y_n+hf_{n+1}$ Eulero implicito \\\hline 2 & $y_{n+1}=y_n+\frac{h}{2}(2f_n-f_{n-1})$ & $y_{n+1}=y_n+\frac{h}{12}(5f_{n+1}+8f_n-f_{n-1})$ \\\hline 3 & $y_{n+1}=y_n+\frac{h}{12}(23f_n-16f_{n-1}+5f_{n-2})$ & \\\hline \end{tabular} \end{center} b \begin{center} \begin{tabular}{|c|c|c|} \hline Ord & Esplicito (Adam-Bashforth) & Implicito (Adam-Moulton) \\\hline 0 & & $y_{n+1}=y_n+hf_{n+1}$ Eulero implicito \\\hline 2 & $y_{n+1}=y_n+\frac{h}{2}(2f_n-f_{n-1})$ & $y_{n+1}=y_n+\frac{h}{12}(5f_{n+1}+8f_n-f_{n-1})$ \\\hline \end{tabular} \end{center} c \end{document} ``` I get: ![enter image description here](https://i.stack.imgur.com/bS0j9.png) The examples make me suspect the greater vertical space, which is what troubles me, is due to the overfull `\hbox` generated by the tables with the greater vertical space (which is between text above the table and the table). Why does that happen? Is my suspicion right?
2014/09/26
[ "https://tex.stackexchange.com/questions/203308", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/42315/" ]
The space is obviously caused by the overfull table and it may be fruitful to understand the reason. What you see as an excess vertical space is an empty line. When you do `\\` inside `center` you're closing a paragraph, so the effect is reproducible just by ``` \documentclass{article} \begin{document} a \begin{center}\tracingparagraphs=1 \vrule height 1pt depth 0pt width 1.2\textwidth % an overlong indivisible object \end{center} b \end{document} ``` The `\tracingparagraph=1` will make TeX report in the `.log` file its computations, which are ``` @firstpass [] @\penalty via @@0 b=0 p=0 d=100 @@1: line 1.2 t=100 -> @@0 @secondpass [] @\penalty via @@0 b=0 p=0 d=100 @@1: line 1.2 t=100 -> @@0 | @\par via @@1 b=* p=-10000 d=* @@2: line 2.3- t=100 -> @@1 ``` The first pass over the paragraph, that consists just of the box represented by `|` doesn't obviously succeed. The `[]` bit represents the indentation box (which is 0pt wide). The second pass shows a feasible break at the start of the paragraph (`@@0`, always present, because a new paragraph starts on new line) and then a penalty (which is inserted by the `\item` command implicitly inserted by `\begin{center}`). This penalty provides a line break point, which is then used because it allows a non overfull line to be typeset. However, the overlong rule causes TeX to throw in the towel. A very different situation is when just `\centering` is used: ``` \documentclass{article} \begin{document} a \begingroup\centering \tracingparagraphs=1 \vrule height 1pt depth 0pt width 1.2\textwidth \par\endgroup b \end{document} ``` that reports ``` @firstpass []\OT1/cmr/m/n/10 a @ via @@0 b=0 p=0 d=100 @@1: line 1.2 t=100 -> @@0 @secondpass []\OT1/cmr/m/n/10 a @ via @@0 b=0 p=0 d=100 @@1: line 1.2 t=100 -> @@0 | @\par via @@1 b=* p=-10000 d=* @@2: line 2.3- t=100 -> @@1 ``` Here no penalty is added in the paragraph, so the only feasible break point is at the end. No “vertical space” (actually an empty line) is added. However you shouldn't be making overfull lines to begin with, so the discussion is just academic.
I conjecture that the problem really stems from the `center` environment, which is based on `trivlist` with an opening `\item`. When the first “letter” in the item is too wide to fit on the line, TeX inserts a line break. Suggested solution: ``` \newenvironment{senter}{\par\centering\medskip}{\par\medskip} ``` Then use `senter` instead of `center`. Change the `\medskip`s to something larger or smaller if desired.
38,697,212
I have a string which have following pattern. String will always remain same. Just numbers will be different ``` Showing Results (1 – 15 of 96,831) ``` I want to extract `96,831` from that string. I want to do this with regex. What can be regex for that? I have tried a way where I am using two regex but still not getting required number. ``` "Showing Results (1 – 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ – \d+)/g, '') ``` Its output is as follow. This output contains spaces which are not required. ``` " 96,831" ``` I want a way to do this in python. Can anyone help me?
2016/08/01
[ "https://Stackoverflow.com/questions/38697212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5532516/" ]
This is clear case where you should avoid regex as it just needs simple `strip` and `split`, like so: ``` >>> s = 'Showing Results (1 – 15 of 96,831)' >>> num = s.split()[-1] '96,831)' >>> num.strip(')') '96,831' ``` Or, using `str.rstrip`: ``` >>> num = s.rsplit(maxsplit=1)[-1] >>> num '96,831)' >>> num.strip(')') '96,831' ``` But if you insist on using regex, then this pattern might do the job for you: ``` >>> import re >>> nums = re.findall(r'\d+,?\d*', s) ['1 ', '15 ', '96,831'] >>> nums[-1] '96,831' ``` And if you want to convert it to `float` don't forget to replace `,` with `.`: ``` >>> num '96,831' >>> >>> num = num.replace(',','.') >>> num '96.831' >>> float(num) 96.831 ```
**NOTE:** I assume regex is necessary. ``` import re print (re.findall(re.compile(u'of ([0-9,]+)'), u"Showing Results (1 – 15 of 96,831)")[0].replace(",", "")) ```
52,112,621
I'm working on a map based iOS 11 application and want to make the status bar blurred exactly like it appears in the Apple maps. This is how it looks on the Maps app: [![enter image description here](https://i.stack.imgur.com/64FWq.png)](https://i.stack.imgur.com/64FWq.png) Currently, I'm using UIVisualEffectView to replicate this effect. Here's my code: ``` let blurEffect = UIBlurEffect(style: .regular) blurredStatusBar = UIVisualEffectView(effect: blurEffect) blurredStatusBar?.translatesAutoresizingMaskIntoConstraints = false view.addSubview(blurredStatusBar!) ``` However, whatever UIBlurEffect I use, I'm not able to replicate the effect like Maps app. Here's how it looks for different effects: **.regular** [![enter image description here](https://i.stack.imgur.com/Bw9HO.png)](https://i.stack.imgur.com/Bw9HO.png) **.prominent** [![enter image description here](https://i.stack.imgur.com/9dm2p.png)](https://i.stack.imgur.com/9dm2p.png) **.light** [![enter image description here](https://i.stack.imgur.com/0IBfh.png)](https://i.stack.imgur.com/0IBfh.png) **.extraLight** [![enter image description here](https://i.stack.imgur.com/zibPR.png)](https://i.stack.imgur.com/zibPR.png) **I just want to the blur the status bar, without adding any saturation, vibrancy or any white color tint.** There is an instance property - [backgroundFilters](https://developer.apple.com/documentation/quartzcore/calayer/1410827-backgroundfilters), which, possibly could have helped me but unfortunately it is not available for layers on iOS. One possible solution suggested [here](https://stackoverflow.com/questions/16254444/calayers-backgroundfilters-doesn-nothing-on-uiview) was to capture the UIView content inside an image, then blurring and showing it. However, this is not a feasible solution in my case because I've got a map underneath the status bar which can be panned. It does not makes sense to continuously capture the underneath map as an image and blur it while the map is being panned. I tried using [ILTranslucentView](https://github.com/ivoleko/ILTranslucentView), which is a little subclass of UIView that provide native iOS 7+ blur (translucent) effect. This is how it appeared: [![enter image description here](https://i.stack.imgur.com/BHUUT.png)](https://i.stack.imgur.com/BHUUT.png) I tried a couple of different approaches like [this](https://github.com/FlexMonkey/Blurable), but to no use.
2018/08/31
[ "https://Stackoverflow.com/questions/52112621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409258/" ]
You could try to use `UIToolbar`. It has the same blur effect as `UINavigationBar` and `UITabBar` that cannot be achieved with `UIBlurEffect`.
you can try Following. ``` yourView.backgroundColor = UIColor.clear let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) // Or UIBlurEffectStyle.dark let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = viewAdvancefilter.blurredView.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] yourView.addSubview(blurEffectView) ```
23,943
Is a password like > > wwwwwwwwwwwwwwwwwwwwwwwww9 > > > (25x 'w' and a number) secure? It would be easy to remember.
2012/11/13
[ "https://security.stackexchange.com/questions/23943", "https://security.stackexchange.com", "https://security.stackexchange.com/users/6359/" ]
From a theory stand point, no, it isn't more secure because it lacks randomness. From a practical standpoint, with some slight changes it is pretty good. When your password lacks randomness, you always run the risk that someone could write code that could rapidly find your password. For example, it would be easy enough to alter a popular dictionary attack to try appending strings of letters of various lengths and now you are just looking at 26\*26\*words in dictionary to attack the password. That is much Much MUCH smaller than 36 to the 26th power (which would be the difficulty with true entropy.) That said, from a practical purpose. If you were to put a password at the end of that which was normally too short to provide sufficient entropy, but was still resistant to dictionary attacks, you would make guessing your password practically much harder as long as they don't see you entering it. If someone who could observe you wanted to break your password via brute force however, you would only be marginally more secure than whatever the entropy of the password you put at the end of it is. In terms of general attack scenarios though, most brute force attacks are run against large sets of passwords to try to find the low hanging fruit. Your approach would likely protect you against these kinds of general attacks, but not all that much more than adding probably 3 or 4 random letters, numbers or symbols to the end of your password, which is not that much harder to remember and far easier to type. (That 3 to 4 is based on the fact that in pure entropy terms, it is only 26\*26 or so, which is the equivilent of 2 more random letters. I'm giving it more entropy than that in my approximation based on likelihood of an attacker to use that pattern, which is purely a guess.)
One of the best resources I know of can be found here: [GRC's Password Haystack](https://www.grc.com/haystack.htm) It explains why high entropy *is not* the answer when it comes to passwords. You can make a very secure password that is still easy to remember by doing a couple things. Start with an easy to remember password, such as $0DA (soda, but with some easy substitutions), then add some padding. This could be as simple as adding some periods before and after, but it's recommended you choose a more unique padding scheme, such as <->. Add this a few times to before and after so that your final password looks something like this: <-><->$0DA<-><-> According to the calculator found on the above mentioned site, this password, under a massive cracking scenario of one hundred trillion guesses per second, would take 8.52 hundred thousand centuries to guess.
35,080,258
In SQL there's a query `INSERT IGNORE` which keeps duplicate entries out of the database based on the primary key. But is there a way to achieve this functionality in OrientDB since the primary key concept here is kind of achieved using the `@rid` concept?
2016/01/29
[ "https://Stackoverflow.com/questions/35080258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3341645/" ]
The following rules apply to metric and tag values: 1. Strings are case sensitive, i.e. "Sys.Cpu.User" will be stored separately from "sys.cpu.user" 2. Spaces are not allowed. 3. Only the following characters are allowed: a to z, A to Z, 0 to 9, -, \_, ., / or Unicode letters (as per the specification) **`But in fact, other than above mentioned characters no other is supported by opentsdb.`**
As of opentsdb version 2.3 there is support for specifying additional characters to allow via the config variable (cross posting from [OpenTsdb: Is Space character allowed in Metric and tag information](https://stackoverflow.com/questions/33935320/opentsdb-is-space-character-allowed-in-metric-and-tag-information/) ) ``` tsd.core.tag.allow_specialchars = !@#$%^&*()_+{}|: <>?~`-=[]\;',./° ``` <http://opentsdb.net/docs/build/html/user_guide/configuration.html> gives more details
23,733,674
I have a string `char date[16] ;` I want, that the last two signs are zero. I have tried: ``` date[14] = '0'; date[15] = '0'; date[16] = '\0'; ``` But 0 is same what '\0'. How can I reach what I want?
2014/05/19
[ "https://Stackoverflow.com/questions/23733674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1829473/" ]
Storing the character `'0'` in a character array is principally correct the way you have tried it, **but** you say you have `char date[16]` so the indexes including the terminating `'\0'` go from 0 to 15, you must not assign anything to `date[16]`. Depending on what the complete content of `date` is, it should be either `char date[17]` or ``` date[13] = '0'; date[14] = '0'; date[15] = '\0'; ```
If the array is not fully printed, then maybe there is some garbage `'\0'` in it. Have you initialized the whole array ? ``` #include <stdio.h> int main () { char date[] = { [0 ... 14] = '0', [15] = '\0' }; printf("%s\n", date); return 0; } ``` The output is `000000000000000` as expected.
20,459,982
If I have a list and I want to keep adding lines to it and sorting them alphabetically by their last name, how could this be done? Sorted only seems to rearrange them by the first letter of the string. ``` line = "James Edward" #Example line linesList.append("".join(line)) #Add it to a list linesList = sorted(linesList) #Sort alphabetically ```
2013/12/08
[ "https://Stackoverflow.com/questions/20459982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080274/" ]
If you want fully correct alphabetization (sorted by first name when the last name is the same), you can take advantage of the fact that Python sorting is stable. If you first sort by the default key: ``` lst.sort() ``` and then sort by last name: ``` lst.sort(key=lambda n: n.split()[1]) ``` then the entries with the same last name will wind up in the same order that the first `sort` put them in - which will be correct. You can also do this all at once with `sorted`: ``` linesList = sorted(sorted(linesList), key=lambda n: n.split()[1]) ```
In case you have `three` or `n` names and you want to sort it always by the last part of the name you can do: ``` names = ["John Mc Karter", "John Oliver", "Max Raiden", "Naruto Ho Uzumaki"] print(names.sort(key=lambda x:x.split()[-1])) >>>['John Mc Karter', 'John Oliver', 'Max Raiden', 'Naruto Ho Uzumaki'] ```
5,228
I have an NVIDIA Titan GPU and I'm able to add another card, but I wonder whether Blender will benefit from more than one GPUs? Should I do it as SLI or should I just do it as an added card? I just need some help in understanding how Blender will use either SLI or a second GPU. Note that I only use Cycles.
2013/12/02
[ "https://blender.stackexchange.com/questions/5228", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/1730/" ]
There are lots of good articles out there on this topic, and short of recreating them, I can say that the two cards I use are not in SLI (wrong motherboard for it) and it uses them like two separate cores. It'll render two chunks at a time, if you tell it to use both. Some of the articles say that running in SLI is a little slower than running two separate cards, but I'm not familiar with the principles behind that. I don't know if the rendered preview (in the viewport) benefits at all, but it can't hurt.
I have 3 cards, 2 cards scaled with a factor of 2.0, now the 3rd card scaled something along 1.7-1.9 factor. So 2 cards make a huge difference in cycles. You will for sure cut the render times in half. All articles I've read suggest not using SLI for apps using CUDA/Compute. If you're on Windows you can via drivers enable it or disable it. It's currently not working under Linux AFAIK. So turn it ON when gaming, turn it OFF when rendering with Blender.
115,718
I'm having a problem in some VHDL code I'm writing. I want to drive a signal with two other signals AND'd together like this: ``` mysignal <= "010" and '1'; ``` The result I expected was a bitwise AND, resulting in mysignal receiving the value of "010". Instead, I got a compiler error telling me "No feasible entries for infix operator "and"." When I try: ``` mysignal <= "010" and "111"; ``` it compiles. Is it possible in VHDL to do a bitwise logical operation, without having to alter my signals and make them all the same width?
2014/06/17
[ "https://electronics.stackexchange.com/questions/115718", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/44159/" ]
One way is to simplify generating signals of the right range. For example: `mysignal <= "010" and (mysignal'range => '1');` This creates a new value for the second operand, the correct size, with all bits set to '1',
In order to extend '1' to a vector of specific length, usually I would use `(0 => '1', others => 0)` syntax. for example: ``` mysignal <= "010" and (0 => '1', mysignal'left downto mysignal'right+1 => '0'); ``` This specifies that bit 0 is '1' and the rest are zero, producing "001" Another way is to concatenate the vector with zeros. I usually make a dummy signal called `zeros` as follows: ``` signal zeros : std_logic_vector(31 downto 0) -- or unsigned if you prefer ... zeros <= (others => '0'); ``` Then it's just a matter of concatenating the zeros vector with whatever other vector as you wish. The `&` symbols is the concatenation operator in VHDL: ``` newsignal <= zeros(newsignal'left downto newsignal'right+1) & '1'; ``` If you want to concatenate another signal, then it's even easier: ``` newsignal <= zeors(newsignal'left downto oldsignal'left+1) & oldsignal; ``` This extends `oldsignal` to whatever length `newsignal` is. It won't work if `newsignal` is the same length or smaller than `oldsignal`. "010" becomes "000010", for example. Note: Adding the dummy zeros vector doesn't change the size of your design in any way, the tools will optimise it out in any case and substitute it with all zeros. I just find it a lot easier to write `zeros` and select which range I want. naturally, you need to ensure that you zeros vector is as long as your longest signal. I find 32 bits works for most cases.
12,031,163
I have a batch file that FTPs CSV files from my web server. I need to download only the most current CSV file. How do I do that? This is what I have so far: ``` open 44.44.44.444 username password CD /Client/ABCCompany/ get *.csv quit close() ``` Thanks.
2012/08/20
[ "https://Stackoverflow.com/questions/12031163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516801/" ]
There's no easy way to select the most recent file with the `ftp.exe`. * If you know that the file has today's timestamp in its filename, you can generate the script dynamically with today's timestamp. You can use the `DATE` environment variable, though it has its caveats. A more reliable (and complex) way is to use the `wmic os get LocalDateTime`. See [How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?](https://stackoverflow.com/q/203090/850848) * If you can determine the latest file alphabetically, you can: + run the `ftp.exe` with `ls` command redirected to a file + sort the file by alphabet in descending order + read the first line + generate download script for second `ftp.exe` run. * [WinSCP](https://winscp.net/) can download the latest file, using the `-latest` switch of the [`get` command](https://winscp.net/eng/docs/scriptcommand_get): ``` winscp.com /command ^ "open ftp://username:password@ftp.example.com/" ^ "cd /remote/path" ^ "get -latest *.csv" ^ "exit" ``` See also the guide to [downloading the most recent file with WinSCP](https://winscp.net/eng/docs/script_download_most_recent_file). * WinSCP can also download the files created [within some interval](https://winscp.net/eng/docs/file_mask#size_time), e.g. the last 24-hours (1 day): ``` winscp.com /command ^ "open ftp://username:password@ftp.example.com/" ^ "cd /remote/path" ^ "get *.csv>=1D" ^ "exit" ``` or files created since some point in time, e.g. to download files created since midnight, use [`today` keyword](https://winscp.net/eng/docs/file_mask#today): ``` winscp.com /command ^ "open ftp://username:password@ftp.example.com/" ^ "cd /remote/path" ^ "get *.csv>=today" ^ "exit" ``` For the `today` keyword, make sure you have recent version of WinSCP. * With WinSCP, you can implement a download of a file with a timestamp in filename more easily than with the `DATE` or the `wmic os get LocalDateTime` (as shown above). Use the `%TIMESTAMP%` syntax: ``` winscp.com /command ^ "open ftp://username:password@ftp.example.com/" ^ "cd /remote/path" ^ "get %%TIMESTAMP#yyyy-mm-dd%%.txt" ^ "exit" ``` *(I'm the author of WinSCP)*
The easies way to do this would be to split this into two seperate connections and having a text file in the FTP location which will contain the name of the latest file. ``` open 44.44.44.444 username password CD /Client/ABCCompany/ get latestfile.txt quit close() ``` latestfile.txt will contain the name of the newest file that you need to download. The second script will read the text from the latestfile.txt and pull that file only. ``` for /F "tokens=*" %%A in (latestfile.txt) do [SET FILE = %%A] ``` You'll have to add the above line into the batch file that is calling the secondary FTP script. ``` open 44.44.44.444 username password CD /Client/ABCCompany/ get %FILE% quit close() ```
40,419,519
This is my JQUERY CODE : ``` $("body").on("click keypress", "#admin-username",function(){ if($("#admin-username").hasClass("error")){ $("#admin-username").removeClass("error"); setTimeout("$('.message').slideUp('slow');", 50); } }); ``` i have used an id `#admin-username` i.e only one id in the above JQuery code where as in my Front-end code i have 3 input boxes 1.) `admin-username` 2.) `admin-email` 3.) `admin-password` however i want to achieve something like this ``` $("body").on("click keypress", "#admin-username, #admin-password, #admin-email",function(){ if($("#admin-username").hasClass("error")){ $("#admin-username").removeClass("error"); setTimeout("$('.message').slideUp('slow');", 50); } }); ``` But if i use multiple id's like this then by default it is working only for the first id i.e `#admin-username` can anyone provide me a solution here ?
2016/11/04
[ "https://Stackoverflow.com/questions/40419519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6831355/" ]
Your selector is corrent but you need to use **this**-inside the callback function to access the element that raised the event ``` $("body").on("click keypress", "#admin-username, #admin-password, #admin-email",function() { if($(this).hasClass("error")) { $(this).removeClass("error"); setTimeout(function() { $('.message').slideUp('slow'); }, 50); } }); ``` Also "corrected" the setTimeout with a callback-function.
First you can add same class to the three inputs in your fontend code lets say adminInput, second you can do something like this to eliminate the test you are making, ``` $("body").on("click keypress", ".adminInput.error",function(e) { var $this = $(this); $this.removeClass("error"); setTimeout(function(){$('.message').slideUp('slow');}, 50); }); ``` you you can always do something like ``` $("#admin-password,#admin-username,#admin-email").click(function(e){ var $this = $(this); if($this.hasClass('error')){ $this.removeClass("error"); setTimeout(function(){$('.message').slideUp('slow');}, 50); } }); ``` or ``` $("body").on("click keypress", "#admin-username,#admin-password,#admin-email",function(){ var $this = $(this); if($this.hasClass("error")){ $this.removeClass("error"); setTimeout(function(){$('.message').slideUp('slow');}, 50); } }); ``` I modified the code so if you want you can test the error class on any ids not just the username
63,202,341
``` import urllib.request import time import json import random QUERY = "http://localhost:8080/query?id={}" N = 500 def getDataPoint(quote): stock = quote['stock'] bid_price = float(quote['top_bid']['price']) ask_price = float(quote['top_ask']['price']) price = (bid_price + ask_price)/2 return stock, bid_price, ask_price, price def getRatio(price_a, price_b): if(price_b==0): return return price_a/price_b if __name__ == "__main__": for _ in range(N): quotes = json.loads(urllib.request.urlopen( QUERY.format(random.random())).read()) prices = {} for quote in quotes: stock, bid_price, ask_price, price = getDataPoint(quote) prices[stock] = price print ("Quoted %s at (bid:%s, ask:%s, price:%s)" % (stock, bid_price, ask_price, price)) print ("Ratio %s" % getRatio(prices['ABC'], prices['DEF'])) ``` > > Traceback (most recent call last): > File "C:/Users/AppData/Local/Programs/Python/Python37/ client.py", line 54, in > quotes= json.loads(urllib.request.urlopen(QUERY.format(random.random())).read()) > File "C:\Users\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 222, in urlopen > return opener.open(url, data, timeout) > File "C:\Users\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 531, in open > response = meth(req, response) > File "C:\Users\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 641, in http\_response > 'http', request, response, code, msg, hdrs) > File "C:\Users\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 569, in error > result = self.\_call\_chain(\*args) > File "C:\Users\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 503, in \_call\_chain > result = func(\*args) > File "C:\Users\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 649, in in http\_error\_default > raise HTTPError(req.full\_url, code, msg, hdrs, fp) > urllib.error.HTTPError: HTTP Error 404: Not Found > > > > > I've error with the URL.Did some research and tried to clear still not so sure why the client part throws error while server part works fine. > > >
2020/08/01
[ "https://Stackoverflow.com/questions/63202341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11284288/" ]
Well, you can simply do it with [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/). All you have to do is to assign the [`display: flex;`](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) to the parent element of your text and image, then with the flex properties like [`align-items: center;`](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwjOo67drPnqAhXPmOAKHRDqBkMQFjACegQIARAB&url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen%2Fdocs%2FWeb%2FCSS%2Falign-items&usg=AOvVaw1atTV0V9k0pdaLtJHSOllM) make them align vertically. You also have to remove the `margin-top` from the image element itself to make it perfectly centre. So the final code should be something like this: ```css .question { display: flex; align-items: center; } .question-answer { background: #ffffff 0% 0% no-repeat padding-box; border-radius: 29px; border: 1px solid #C9C9C9; cursor: pointer; color: #303030; } .question-answer .question { display: flex; justify-content: space-between; padding-right: 30px; } .question-answer .question .content { padding: 0 34px; text-align: left; font-size: 14px; font-weight: bold; font-family: Open Sans; letter-spacing: 0px; color: #686868; opacity: 1; letter-spacing: 0px; position: relative; padding-right: 30px; min-height: 57px; display: flex; align-items: center; } .question-answer .question img { max-width: 24px; max-height: 24px; } @media (max-width: 767px) { .question-answer .question .content { padding-top: 15px; padding-bottom: 15px; padding-right: 0px; } } ``` ```html <div class="question-answer"> <div class="question"> <div class="content">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore</div> <img class="img-down" src="https://i.ibb.co/pRztJtW/arrow-circle-down-solid.png" alt=""> </div> </div> ```
Please add this style. It will make your image vertically center. ``` .question {align-items: center;} .question-answer .question img{margin: 0;} ```
281,472
File, ``` TABLE1 ------- 1234 TABLE1 ------- 9555 TABLE1 ------- 87676 TABLE1 ------- 2344 ``` I want the output like ``` TABLE1 ------- 1234 9555 87676 2344 ```
2016/05/06
[ "https://unix.stackexchange.com/questions/281472", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/118311/" ]
Here is one liner, using `sed` and `awk` : ``` sed '/^$/d' filename | awk '!a[$1]++' ``` Combination of `grep` and `awk` : ``` grep . filename | awk '!a[$1]++' ``` As @[cas](https://unix.stackexchange.com/users/7696/cas) suggested, You can do that in single `awk` command also. ``` awk '!x[$1]++ && ! /^[[:blank:]]*$/' filename ```
I usually use sort and uniq together to get rid of duplicates like this: ``` cat file | sort | uniq ``` However, with your input, it will end up like this: ``` ------- 1234 2344 87676 9555 TABLE1 ``` This command removes all but the numbers and adds the header afterwards: ``` cat file | grep '^[[:digit:]]*$'| grep -v '^$' |sed '1iTABLE1\n-------' ``` and gives you this result: ``` TABLE1 ------- 1234 9555 87676 2344 ```
1,325,718
I've always been under the impression that using the ThreadPool for (let's say non-critical) short-lived background tasks was considered best practice, even in ASP.NET, but then I came across [this article](http://csharpfeeds.com/post/5415/Dont_use_the_ThreadPool_in_ASP.NET.aspx) that seems to suggest otherwise - the argument being that you should leave the ThreadPool to deal with ASP.NET related requests. So here's how I've been doing small asynchronous tasks so far: ``` ThreadPool.QueueUserWorkItem(s => PostLog(logEvent)) ``` And [the article](http://csharpfeeds.com/post/5415/Dont_use_the_ThreadPool_in_ASP.NET.aspx) is suggesting instead to create a thread explicitly, similar to: ``` new Thread(() => PostLog(logEvent)){ IsBackground = true }.Start() ``` The first method has the advantage of being managed and bounded, but there's the potential (if the article is correct) that the background tasks are then vying for threads with ASP.NET request-handlers. The second method frees up the ThreadPool, but at the cost of being unbounded and thus potentially using up too many resources. So my question is, is the advice in the article correct? If your site was getting so much traffic that your ThreadPool was getting full, then is it better to go out-of-band, or would a full ThreadPool imply that you're getting to the limit of your resources anyway, in which case you shouldn't be trying to start your own threads? Clarification: I'm just asking in the scope of small non-critical asynchronous tasks (eg, remote logging), not expensive work items that would require a separate process (in these cases I agree you'll need a more robust solution).
2009/08/25
[ "https://Stackoverflow.com/questions/1325718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58173/" ]
Websites shouldn't go around spawning threads. You typically move this functionality out into a Windows Service that you then communicate with (I use MSMQ to talk to them). -- Edit I described an implementation here: [Queue-Based Background Processing in ASP.NET MVC Web Application](https://stackoverflow.com/questions/1317641/queue-based-background-processing-in-asp-net-mvc-web-application) -- Edit To expand why this is even better than just threads: Using MSMQ, you can communicate to another server. You can write to a queue across machines, so if you determine, for some reason, that your background task is using up the resources of the main server too much, you can just shift it quite trivially. It also allows you to batch-process whatever task you were trying to do (send emails/whatever).
Whether or not IIS uses the same ThreadPool to handle incoming requests seems hard to get a definitive answer to, and also seems to have changed over versions. So it would seem like a good idea not to use ThreadPool threads excessively, so that IIS has a lot of them available. On the other hand, spawning your own thread for every little task seems like a bad idea. Presumably, you have some sort of locking in your logging, so only one thread could progress at a time, and the rest would just take turns getting scheduled and unscheduled (not to mention the overhead of spawning a new thread). Essentially, you run into the exact problems the ThreadPool was designed to avoid. It seems that a reasonable compromise would be for your app to allocate a single logging thread that you could pass messages to. You would want to be careful that sending messages is as fast as possible so that you don't slow down your app.
43,721,966
`public static void main(String[] args)` I know conventionally the main function takes in a parameter args that contains the supplied command line arguments as an array of String objects. * I have not see main takes in any parameter other than `String[] args`. Why not a `String` or an array of `Integer`? * If there is a way to specify input for the `main` function, please provide an example.
2017/05/01
[ "https://Stackoverflow.com/questions/43721966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7915557/" ]
Answer to your question: **NO** Details: <http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html> > > The java command starts a Java application. It does this by starting a Java runtime environment, loading a specified class, and calling that class's **main** method. > > > The method must be declared public and static, it must not return any value, and it **must accept a String array as a parameter**. The method declaration has the following form: > > > public static void main(String[] args) > > >
> > I have not see main takes in any parameter other than String[] args. Why not a String or an array of Integer? > > > Yes, you can take any `String` or `Integer` as parameter, but that would become a different function `main()` method instead of the one used by java to start your program. After compilation, java search for `public static void main(String[] args){}` method to start with. If you change parameters then your program won't run at all. Now using array will cover only particular type of values that array can permit like `int[]` will only store `int`values, similarly `String` can have only one value, while you may want to have multiple arguments. > > If there is a way to specify input for the main function, please provide an example. > > > Yes, there are ways to pass argument using command line(for windows) and terminal(for linux/unix). 1. compile your java program by using `javac Filename.java` 2. run java program along with parameters `java FileName param1 param2 param3` (param1, param2, param3 are parameters that you want to pass).
338,063
I have PDF documents from a scanner. This PDF contain forms filled out and signed by staff for a days work. I want to place a bar code or standard area for OCR text on every form type so the batch scan can be programatically broken apart into separate PDF document based on form type. I would like to do this in Microsoft .net 2.0 I can purchase the require Adobe or other namespaces/dll need to accomplish the task if there are no open source namespaces/dll's available.
2008/12/03
[ "https://Stackoverflow.com/questions/338063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can research the iTextSharp library, which can split pdf files. But it isn't very good for reading the actual pdfs. So I have no idea how it would know where to split them. There are companies that already do this for you. You can research the kwiktag company.
check out the [Tesseract .NET wrapper (v 2.04.0)](http://www.pixel-technology.com/freeware/tessnet2/) around the c++ ocr engine by the same name developed by hp in the late 90's, it won awards for its ingenuity
25,674,263
I have been trying for several hours now trying to get my elements to hide one and show another. My script is as follows: ``` <script type="text/javascript"> function () { $('#Instructions').hide(); $('#GodDescription').show(); }; </script> ``` I don't understand why neither one is working. Default the Instructions are visible, and GodDescription is not. Right now I am just trying to get GodDescription visible and Instructions hidden when the page comes up. GodDescription in the css file has display:none; What am I doing wrong, and what should I do? Thank you for any help.
2014/09/04
[ "https://Stackoverflow.com/questions/25674263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3542563/" ]
If you are trying to do it as page loads you have to write this way: ``` $(function () { $('#Instructions').hide(); $('#GodDescription').show(); }); ``` or: ``` $(document).ready(function () { $('#Instructions').hide(); $('#GodDescription').show(); }); ``` Explanation: ------------ *`$(function(){ })`* *(shorthand for `$(document).ready()`)* tells to execute the code inside it when the document is ready. It mean that all the HTML elements will be present and ready to be used by the JavaScript. According to [**JQUERY DOCS**](http://learn.jquery.com/using-jquery-core/document-ready/): > > > > > > A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside **$( document ).ready()** will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside **$( window ).load(function() { ... })** will run once the entire page (images or iframes), not just the DOM, is ready. > > > > > > > > >
Here's a pure JavaScript solution ;) ``` <script type="text/javascript"> window.onload = function(){ getDocumentById('Instructions').style.display='none'; getDocumentById('GodDescription').style.display='block'; }; </script> ```
51,236,297
I want to give my Sprite some extra speed when you press the spacebar for 3 seconds. After that you should wait 10 Seconds before using it again. I tried using SFML's Time, but the clock starts right away as the program starts so it starts anyway.... Short Question: How can I delay a function without freezing the program like Sleep() does. Code(console only for dev progess as it slows): ``` #include "SFML/Graphics.hpp" #include <iostream> #include <Windows.h> int main() { using namespace std; sf::Clock ClockSpeedFunc, Cooldown; ClockSpeedFunc.restart(); bool Timer, CooldownTimer = false; sf::RenderWindow window(sf::VideoMode(600, 600), "SFML WORK!"); sf::Texture texture; if (!texture.loadFromFile("PlayerTexture.jpg")) { std::cout << "Error loading PlayerTexture.jpg" << std::endl; } sf::Sprite sprite; sprite.setTexture(texture); sprite.setPosition(sf::Vector2f(50, 40)); sprite.setPosition(sf::Vector2f(50, 40)); sprite.setPosition(sf::Vector2f(50, 40)); sprite.setPosition(sf::Vector2f(50, 40)); float PlayerSpeed = 0.1; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; } } //###Controls :: //If W is pressed, move upwards if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { sprite.move(sf::Vector2f(0, -PlayerSpeed)); } //If A is pressed, move left if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { sprite.move(sf::Vector2f(-PlayerSpeed, 0)); } //If S is pressed, move downwards if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { sprite.move(sf::Vector2f(0, PlayerSpeed)); } //If D is pressed, move right if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { sprite.move(sf::Vector2f(PlayerSpeed, 0)); } //If Space is pressed, set Timer to true and set Speed to 0.5 if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && CooldownTimer == false) { cout << "Turbo started" << endl; Timer = true; CooldownTimer == false; PlayerSpeed = 0.5; } //If Timer = true, start a clock if (Timer = true) { sf::Clock ClockSpeedFunc; } //aafter 3 Seconds set Playerspeed back to 0.1 //Set Cooldowntimer to true and restart timer clock. sf::Time elapsed1 = ClockSpeedFunc.getElapsedTime(); sf::Time elapsed2 = Cooldown.getElapsedTime(); if (elapsed1.asSeconds() >= 3) { PlayerSpeed = 0.1; cout << "Turbo ended." << endl; ClockSpeedFunc.restart(); CooldownTimer = true; }if (CooldownTimer == true) { cout << "Cooldown started" << endl; sf::Clock Cooldown; }if (elapsed2.asSeconds() >= 10) { cout << "Cooldown ended" << endl; Cooldown.restart(); CooldownTimer = false; } //Draw everything window.clear(); window.draw(sprite); window.display(); } ``` }`
2018/07/08
[ "https://Stackoverflow.com/questions/51236297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10050785/" ]
First of all make sure you do not use "using namespace". That is a bad habit. And why did you have a #include there. I did not need it. It is not part of the problem, but I highly recommend to have a look on <https://gafferongames.com/post/fix_your_timestep/> and manage your delta time. I think I would use a class for this. But here you can see how to use it with states. I added some comments in the code so you can see what I did. ``` #include "SFML/Graphics.hpp" #include <iostream> // Define the different states of the player enum class m_State{ POWERUP, NORMAL, COOLDOWN }; int main(){ sf::Clock m_Clock; // Record elapsed time of power up float m_SecondsSincePowerUp; // Set initial state m_State m_State = m_State::NORMAL; sf::RenderWindow window(sf::VideoMode(600, 600), "SFML WORK!"); sf::Texture texture; if (!texture.loadFromFile("PlayerTexture.jpg")){ std::cout << "Error loading PlayerTexture.jpg" << std::endl; } sf::Sprite sprite; sprite.setTexture(texture); sprite.setPosition(sf::Vector2f(50, 40)); sprite.setPosition(sf::Vector2f(50, 40)); sprite.setPosition(sf::Vector2f(50, 40)); sprite.setPosition(sf::Vector2f(50, 40)); float PlayerSpeed = 0.1; while (window.isOpen()){ sf::Time elapsedTime = m_Clock.restart(); sf::Event event; while (window.pollEvent(event)){ switch (event.type){ case sf::Event::Closed: window.close(); break; } } //###Controls :: //If W is pressed, move upwards if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { sprite.move(sf::Vector2f(0, -PlayerSpeed)); } //If A is pressed, move left if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { sprite.move(sf::Vector2f(-PlayerSpeed, 0)); } //If S is pressed, move downwards if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { sprite.move(sf::Vector2f(0, PlayerSpeed)); } //If D is pressed, move right if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { sprite.move(sf::Vector2f(PlayerSpeed, 0)); } //If Space is pressed, set Timer to true and set Speed to 0.5 if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && (m_State == m_State::NORMAL)){ std::cout << "Turbo started" << std::endl; // Set state to PowerUp m_State = m_State::POWERUP; PlayerSpeed = 0.5; } // If state is PowerUp count the seconds in a variable if (m_State == m_State::POWERUP){ // Add elapsed time in seconds m_SecondsSincePowerUp += elapsedTime.asSeconds(); // After 3 seconds switch the state to Cooldown if (m_SecondsSincePowerUp > 3.0f){ std::cout << "Turbo ended." << std::endl; m_State = m_State::COOLDOWN; PlayerSpeed = 0.1; } } // After 10 seconds switch to normal if (m_State == m_State::COOLDOWN){ m_SecondsSincePowerUp += elapsedTime.asSeconds(); if (m_SecondsSincePowerUp > 10.0f){ std::cout << "Cooldown ended." << std::endl; m_State = m_State::NORMAL; m_SecondsSincePowerUp = 0; } } //Draw everything window.clear(); window.draw(sprite); window.display(); } } ```
You can use a thread to create a sleep while normal code continues to execute in unison. They are quite complex for a full explanation but look up an example and see if you think it's worth trying to implement for use with this.
24,928,726
I have created a android project in Visual Studio.I have a few images in the the Drawable folder. These images show in the Resource designer as well. But when I try to access these images the Project Resource explorer does not show them. Also if I try to use them programatically they don't show up. What is wrong?
2014/07/24
[ "https://Stackoverflow.com/questions/24928726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146095/" ]
You can't add DIV to selectBlock. But you can add option into select: ``` $('#platypusDropDown').click(function () { var myDiv = document.getElementById('addCategory'); $(this).after(myDiv); }); ```
Why you whant add div to Options? You could try like this: ``` $('#platypusDropDown').click(function () { var dropHeight = $(this.options[0]).height() * this.options.length; if($(this).data('open')) { $(this).data('open', false); $('#addCategory').css('padding-top', '0px') return; } $('#addCategory').css('padding-top', dropHeight + 'px') $(this).data('open', true); }); ``` [**JSFIDDLE DEMO**](http://jsfiddle.net/HwpG5/1/)
9,196,066
What does `::=` mean in programming documentation? For example in the [Lua documentation](http://www.lua.org/manual/5.2/manual.html#3.2): or in [Python documentation](http://docs.python.org/release/2.7.1/reference/lexical_analysis.html#identifiers).
2012/02/08
[ "https://Stackoverflow.com/questions/9196066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/702912/" ]
This is [Backus-Naur Form](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form) (BNF) notation describing the language. `::=` in this context means *is defined as*. For example, in the Python language documentation you refer to, an identifier *is defined as* a letter or an underscore, followed by a letter, a digit or an underscore. The notation then goes on to describe what a letter and a digit is defined as, and so on.
As others have already said, it's part of the BNF notation. Wikipedia has an [explanation and some examples](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form), which I won't repeat here. The history and evolution of the `::=` symbol itself is explained in [The History of the ALGOL Effort](http://heerdebeer.org/ALGOL/The_History_of_ALGOL.pdf) (p29 onwards).
104,687
In my new campaign I am allowed to choose one uncommon magic item, and was considering the Immovable Rod: > > This flat iron rod has a button on one end. You can use an action to press the button, which causes the rod to become magically fixed in place. Until you or another creature uses an action to push the button again, the rod doesn't move, even if it is defying gravity. The rod can hold up to 8,000 pounds of weight. More weight causes the rod to deactivate and fall. A creature can use an action to make a DC 30 Strength check, moving the fixed rod up to 10 feet on a success. > > > I was also reading [this answer](https://rpg.stackexchange.com/a/69940/15689) to a [What happens when an Immovable Rod is activated while in a vehicle?](https://rpg.stackexchange.com/q/69917), which got me thinking: **Can an immovable rod be used to pin an enemy?** My idea is to use the immovable rod as a staff of sorts, with the added ability of being able to pin enemies. Here, when I say pinned, I mean being stuck under the rod in a restrained, prone position (thanks, nitsua60). Let's simplify the situation too and just assume that the pinned enemy won't or can't just push the button to release the Rod, so we can focus on whether it can be done at all in the first place. Based on the description I don't see why the immovable rod could not be used to pin enemies, though I'm not sure what the mechanics would be (i.e., my and my enemy's relevant checks) to using the rod to pin (and immobilize) an enemy. I'm willing to accept answers that can cite RAW one way or the other, or alternatively, any errata or other sources (e.g., Sage Advice) which would help clarify whether or not the immovable rod can be used to pin. A comment asked whether real martial arts knowledge is okay as evidence: I suppose martial arts knowledge would be appreciated as additional support/justification for an answer about why using a rod to pin would/wouldn't be possible.
2017/08/03
[ "https://rpg.stackexchange.com/questions/104687", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/15689/" ]
As other answers have mentioned, placing the rod in a position where they won't be able to wriggle away from it would be difficult (but not impossible). So, adapt your tactics to suit your weapon. Take advantage of the fact that the rod doesn't really have to pin them *to* anything. Slide the rod under the back of their armor through the arm holes, hike them off the ground so their feet don't touch, and press the button. Doffing armor takes several minutes, assuming they can do it with that much tension on the fastenings. Bonus points: nothing to push against means no strength check. As an alternative, hand them the rod, tell them about the button, and throw them off a cliff. Now their options are push the button and hang there waiting for rescue, or fall to their death. Either way they won't be in your face for a while. Finally, if you have the time, use one of the pins they could get out of by pushing the button, but then make pushing the button an unattractive option (for example: by setting a 7000 pound rock on top of it.) I would expect that only the first two methods could be used in combat. The third option would make a decent prisoner retention strategy though.
**Yes, but** To be successful you will probably need help. Since activating the rod would be an action you would have to have the target pinned/restrained already. The way that I could see this working requires coordination. 1. A Grapple Character (with Grappler Feat) 2. Another character with the Immovable Rod The Pinning might go down as follows 1. The grappler grapples target. 2. The grappler knocks the target prone. 3. The grappler restrains the target. 4. Then the Immovable Rod is placed on the target in such a way as to pin the targets hands. (target on his stomach, hands crossed over the small of his back, rod along his spine over his hands) 5. Then the Immovable rod activated so that the grappler can get up and attack the next mook, and the fight continues. But ultimately if the conditions are right, and the rod is activated while pressed into a target on the ground, it would be equivalent to placing an 8,000 pound weight on the target that (magically) doesn't crush the target.
5,904,399
I've been playing around with multi directional scrolling with jquery. I find this is a superb way to navigate through a website, but it has one drawback. The browser needs to load all site content at once because it's in one html document. Now I have been searching unsuccessfully for a way to have this great scrolling between different html documents. So instead of scrolling between div's I wonder if it is possible to scroll between html documents. Is this possible?
2011/05/05
[ "https://Stackoverflow.com/questions/5904399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/731779/" ]
This isn't possible in the normal sense of how Request/Response transaction between a client and a server - only a browser could animate changes on this page-change level. There are some other options: 1. When you scroll off to one side, use JS to redirect the browser (with some hash tags or query strings for info) to the next page. When the next page loads, you apply an animation that makes it look like it's been scrolled into. This has the nasty disadvantage of have a delay between page transitions. 2. use AJAX, so, when you scroll, content is asynchronously loaded into the page. Then, once it's loaded, you don't have to worry about it. This is similar to what Google or Bing do when you're scrolling through images in an image search. This has the advantage of loading only what you need. For AJAX loading, jQuery's AJAX method is very useful: <http://api.jquery.com/jQuery.ajax/> Simply pass in a URL, any info you want, and a callback. On the callback, load the response data into an empty `div` or wherever. Something like this example, taking from jQuery's site: ``` $.ajax({ url: 'ajax/test.html', success: function(data) { $('.result').html(data); alert('Load was performed.'); } }); ```
There are two ways that you could get this accomplished. * Use iframes. This is obviously not the best choice. * The second is to make all links in the DIV use ajax and load content into the DIV. Basically, modify all of the links to not actually go anywhere, but to load dynamically on the page into the respective DIV.
31,700,162
I have got a date in this format: `2015-07-29 16:29:32` How can I check the difference in minutes between the current date and the given date? ``` import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) throws ParseException { String datetocomparestr = "2015-07-29 16:29:32"; SimpleDateFormat datetocomparesdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); Date d1 = null; d1 = datetocomparesdf.parse(datetocomparestr); System.out.println(d1); SimpleDateFormat dateFormatcurrentsdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormatcurrentsdf.format(date)); } } ``` Could you please let me know how to resolve this. Thanks in advance.
2015/07/29
[ "https://Stackoverflow.com/questions/31700162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784597/" ]
A simple solution would be to use the `Date.getTime()` method (returns "*milliseconds since 1.1.1970*"), get the difference of these values and divide that value by 1000 \* 60 (1000 ms per second, 60 seconds per minute).
you can use [localdatetime](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html) as below ``` LocalDateTime d1=new LocalDateTime(date1); LocalDateTime d2=new LocalDateTime(now); int minutesDiff=Minutes.minutesBetween(d1, d2).getMinutes(); ```
17,679,565
My page code looks like this: ``` <asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click"/> ``` My method looks like this: ``` protected void btnSearch_Click(object sender, EventArgs e) { var value = lblGraphicNameValue.Text.ToString(); Response.Redirect("Search.aspx?txtGraphicName=" + value); } ``` Currently, when the user press the 'Search' button the page refreshes and loads the Search.aspx page. What I'd like to happen is have the Search.aspx open in a new window, instead. I've looked at using Window.Open, but I'm not sure if this is the correct route, or if I can use the same method of passing in my variable (querystring). Can someone point me in the right direction? What I have works, I just want it to open in a new page while leaving the prior page alone. EDIT: I should mention that I cannot use javascript (secure environment, every browser has javascript disabled). From what I'm reading, it seems to indicate that opening a new web page from within an asp.net page and having parms passed in is not do-able without javascript? Is this correct?
2013/07/16
[ "https://Stackoverflow.com/questions/17679565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295265/" ]
This code below ultimately does exactly what I needed it to: ``` <a href="<%= this.ResolveUrl("Search.aspx?id=" + lblGraphicNameValue.Text.Remove(lblGraphicNameValue.Text.Length -4)) %>" target="_blank">Search Related</a> ``` This code does three things: * 1) Opens Search in new page. * 2) Truncates the search value by four characters (I only needed part of the search string) * 3) Passes in parameter to new page. This accomplished exactly what I needed without resorting to custom classes or javascript, although it did make me have to use a link instead of a button.
I think your on the right track, but you're confusing server side code, and client side code. `window.open` is a Javascript function which works on the client side. So you'll need to render some Javascript from C# to make the window popup. Try: ``` protected void btnSearch_Click(object sender, EventArgs e) { var value = lblGraphicNameValue.Text.ToString(); ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('Search.aspx?txtGraphicName={0}');</script>", value)); } ``` That will re-render the page, and then add a script on pageload that will popup the window. A little warning, this will probably be blocked by a browser popup blocker. If you want to get around that, you can probably achieve this without posting back to the server by using Javascript.
59,441,694
Anyone can tell me why this return to the array to string conversation when I decoding it. I didn't see any error for this type of JSON. ``` {"transaction":{"token":"8mBjEEGt0E7QxhZoObDb8Jy0gSH","created_at":"2019-12-22T04:42:23Z","updated_at":"2019-12-22T04:42:24Z","succeeded":true,"transaction_type":"AddPaymentMethod","retained":false,"state":"succeeded","message_key":"messages.transaction_succeeded","message":"Succeeded!","payment_method":{"token":"TRYA1r9WQ0u8jllrJVHRjYyBOIh","created_at":"2019-12-22T04:42:23Z","updated_at":"2019-12-22T04:42:24Z","email":"fstancereq@virginia.edu","data":null,"storage_state":"cached","test":false,"metadata":null,"callback_url":null,"last_four_digits":"2214","first_six_digits":"475129","card_type":"visa","first_name":"Fleur","last_name":"Stancer","month":8,"year":2022,"address1":"46 Meadow Ridge Drive","address2":null,"city":"Orlando","state":"FL","zip":"32885","country":"US","phone_number":null,"company":null,"full_name":"Fleur Stancer","eligible_for_card_updater":true,"shipping_address1":null,"shipping_address2":null,"shipping_city":null,"shipping_state":null,"shipping_zip":null,"shipping_country":null,"shipping_phone_number":null,"payment_method_type":"credit_card","errors":[],"fingerprint":"fb8a1c8ddfb37ad4810335243495109596aa","verification_value":"XXX","number":"XXXX-XXXX-XXXX-2214"}}} ``` when I decode it using json\_decode ``` echo $json["transaction"]["payment_method"]; ``` I seek for the same problem but I didn't get an answer.
2019/12/22
[ "https://Stackoverflow.com/questions/59441694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12460817/" ]
There is nothing wrong with the JSON. If you try to echo an array like a string, PHP will try to convert the array to a string. Looking at the following JSON, `$json["transaction"]["payment_method"]` is not a string. It is an object or array depending on how you decode it. ``` { "transaction": { "token": "8mBjEEGt0E7QxhZoObDb8Jy0gSH", "created_at": "2019-12-22T04:42:23Z", "updated_at": "2019-12-22T04:42:24Z", "succeeded": true, "transaction_type": "AddPaymentMethod", "retained": false, "state": "succeeded", "message_key": "messages.transaction_succeeded", "message": "Succeeded!", "payment_method": { "token": "TRYA1r9WQ0u8jllrJVHRjYyBOIh", "created_at": "2019-12-22T04:42:23Z", "updated_at": "2019-12-22T04:42:24Z", "email": "fstancereq@virginia.edu", "data": null, "storage_state": "cached", "test": false, "metadata": null, "callback_url": null, "last_four_digits": "2214", "first_six_digits": "475129", "card_type": "visa", "first_name": "Fleur", "last_name": "Stancer", "month": 8, "year": 2022, "address1": "46 Meadow Ridge Drive", "address2": null, "city": "Orlando", "state": "FL", "zip": "32885", "country": "US", "phone_number": null, "company": null, "full_name": "Fleur Stancer", "eligible_for_card_updater": true, "shipping_address1": null, "shipping_address2": null, "shipping_city": null, "shipping_state": null, "shipping_zip": null, "shipping_country": null, "shipping_phone_number": null, "payment_method_type": "credit_card", "errors": [], "fingerprint": "fb8a1c8ddfb37ad4810335243495109596aa", "verification_value": "XXX", "number": "XXXX-XXXX-XXXX-2214" } } } ``` You can output it using `print_r($json);` to see the decoded data. Some other things you can do: ``` // Output a data element of payment_method echo $json["transaction"]["payment_method"]["token"]; // Output all values foreach($json['transaction']['payment_method'] as $k => $v) { echo "$k = $v\n"; } ``` Output to HTML ``` <?php echo "<table>"; echo "<tr><th>Key</th><td>Value</td></tr>"; foreach($json['transaction']['payment_method'] as $k => $v) : ?> <tr> <td><?= $k ?></td> <td><?= $v ?></td> </tr> <?php endforeach; echo "</table>"; ?> ```
Your try to echo an array: ``` [ "token" => "TRYA1r9WQ0u8jllrJVHRjYyBOIh", "created_at" => "2019-12-22T04:42:23Z", "updated_at" => "2019-12-22T04:42:24Z", // etc ] ``` Try the following command to get the value when you testing: ``` var_dump($json["transaction"]["payment_method"]); ```
14,785,274
I'm trying this: If jQuery is not present, add jQuery dinamically and test it with alert. But this doesn't works, ¿what I'm doing wrong? HMTL: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" id="crishk"> <head> </head> <body> Welcome to Javascript Loader</a> <div id="alertme">Alert me!</div> <script type="text/javascript" language="javascript" src="dynamic.js"></script> </body> </html> ``` File dynamic.js ``` if (typeof jQuery == 'undefined') { alert('You need to install jQuery to proceed.!'); var oHead = document.getElementsByTagName('head').item(0); var oScript = document.createElement("script"); oScript.type = "text/javascript"; oScript.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"; oHead.appendChild(oScript); } else { alert('jQuery is present...'); } $(document).ready(function () { alert($('#alertme').html()); }); ```
2013/02/09
[ "https://Stackoverflow.com/questions/14785274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439866/" ]
Use onload event to fire functions when jquery being loaded in first if condition. Wrap all other function which require jquery in one function and call it onload of jquery. this will work for you. ``` if (typeof jQuery == 'undefined') { alert( 'You need to install jQuery to proceed.!'); var oHead = document.getElementsByTagName('head').item(0); var oScript= document.createElement("script"); oScript.type = "text/javascript"; oScript.src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"; oHead.appendChild( oScript); oScript.onload=onload; //on load handler } else { alert( 'jQuery is present...' ); onload(); } function onload(){ alert( $('#alertme').html() ); }; ``` check <http://jsfiddle.net/WVtt9/>
``` class OutputManager { public $output; public $dom; private $matches; function __construct( &$output ) { $this->output = $output; $this->dom = new DOMDocument(); $this->dom->loadHTML( $this->output ); $this->dom->normalizeDocument(); $this->matches = array(); } /** * put your comment there... * * @param mixed $attr * @param mixed $val */ public function elementExists( $tagName, $attr=NULL, $attr_val=NULL ) { if (count( $this->matches[$tagName] ) == 0) { $this->matches[$tagName] = $this->dom->getElementsByTagName( $tagName ); } if ($attr == NULL && $attr_val == NULL) { return $this->matches->length > 0; } else if ($attr != NULL && $attr_val == NULL) { foreach ($this->matches[$tagName] as $match) { if ($this->match->hasAttribute($attr)) return true; } } else if ($attr != NULL && $attr_val != NULL) { foreach ($this->matches[$tagName] as $match) { if (trim( $match->getAttribute($attr), "/" ) == trim( $attr_val, "/" )) return true; } } return false; } public function addScript( $src, $at="head" ) { if (!$this->elementExists( "script", "src", $src )) { $result = $this->dom->getElementsByTagName($at); $new_script = $this->dom->createElement( "script" ); $attribute_src = $this->dom->createAttribute( "src" ); $attribute_src->value = $src; $new_script->appendChild( $attribute_src ); $attribute_type = $this->dom->createAttribute( "type" ); $attribute_type->value = "text/javascript"; $new_script->appendChild( $attribute_type ); $result->item(0)->appendChild( $new_script ); } } public function addStylesheet( $href ) { if (!$this->elementExists( "link", "href", $href )) { $result = $this->dom->getElementsByTagName($at); $new_stylesheet = $this->dom->createElement( "link" ); $attribute_href = $this->dom->createAttribute( "href" ); $attribute_href->value = $href; $new_stylesheet->appendChild( $attribute_href ); $attribute_type = $this->dom->createAttribute( "type" ); $attribute_type->value = "text/css"; $new_stylesheet->appendChild( $attribute_type ); $attribute_rel = $this->dom->createAttribute( "rel" ); $attribute_rel->value = "stylesheet"; $new_stylesheet->appendChild( $attribute_rel ); $result->item(0)->appendChild( $new_stylesheet ); } } /** * Returns the final output. * */ public function getOutput() { return $this->dom->saveHTML(); } public function getStyles() { return $matches['link']; } } ```
11,602,626
In C# is there a way to declare the class then define it later? I really like in C++ where I can list all the methods at the top like a TOC then define everything later. Can that be done is C#? I have used the idea of defining a method that just runs a similarly named method in it then the similar method is at the bottom. but I am thinking there is a better way and googling returns a bunch of basic code on creating classes with no answer. so here is what I do... ``` ... public void methodA(){methodAcontent()}; public void methodB()...etc... ...further down... private void methodAcontent(){ ...All the code.. } ``` is there a better way?
2012/07/22
[ "https://Stackoverflow.com/questions/11602626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1345055/" ]
this like `Interface` <http://msdn.microsoft.com/en-us/library/87d83y5b.aspx>
If you're doing this as a means to "document" the public interface to a class that's properly encapsulating a concept or object in your problem domain, then use an interface. If you're doing it as a means to get an "overview" the structure of a class, then Visual Studio has several ways to give you this. You can collapse the code to just its definitions (Ctrl+M, O), or look at the Class View (Ctrl+W, C).
5,566,287
I need some guidance on how to make a audio stream app for multiple audio files, so the app user can choose from the list and listen to the item. Can someon help me?
2011/04/06
[ "https://Stackoverflow.com/questions/5566287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450606/" ]
So your restriction is 53 bit? For my understanding order number of bit in hashcode doesn't affect its value (order and value of bit are fully independent from each other). So you could get 64-bit hash function and use only last 53 bits from it. And you must use binary operations for this ( hash64 & (1<<54 - 1) ) not arithmetic.
If you can save 16 alphanumeric characters then you can use a hexadecimal representation and pack 16^16 bits into 16 chars. 16^16 is 2^64.
64,298,576
I am currently trying to implement sections into my website using express handlebars. My code looks like this: index.js ``` const path = require("path"); const express = require("express"); const expressHandlebars = require("express-handlebars"); const app = express(); app.engine("handlebars", expressHandlebars({ defaultLayout: "main", helpers: { section: (name, options) => { if (!this._sections) { this._sections = {}; } this._sections[name] = options.fn(this); return null; } } })); app.set("view engine", "handlebars"); app.use(express.static("public")); app.get("/", (req, res) => { res.render("home", { title: "Home" }); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Listening on port ${PORT}`); }); ``` views/layouts/main.handlebars ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>{{{ title }}}</title> {{{_sections.head}}} </head> <body> {{{ body }}} </body> </html> ``` views/home.handlebars ``` {{#section "head"}} <style> h1 { color: "red"; } </style> {{/section}} <h1>test</h1> ``` Expected Result: ---------------- It correctly displays the h1 tag with the text "test". However, the heading should be red due to the `{{#section "head"}}`, but it is black. I have installed express and expressHandlebars correctly. What could be wrong?
2020/10/10
[ "https://Stackoverflow.com/questions/64298576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11360318/" ]
There's perhaps a shorter way to do it, but this is my approach: ``` const myTaggedTemplate = (strings, ...vars) => { let result = ''; strings.forEach((str, i) => { result += `${str}${i === strings.length - 1 ? '' : vars[i]}`; }); return result; }; ```
You need to change your function: ``` let myTaggedTemplate = (strings,...values) => ...; ``` and try to follow the example in [this link](https://medium.com/@js_tut/tagged-template-literals-1e1f175c21e4)
33,098,050
My problem is about passing a member function from a Class A, to a member function of a Class B: I tried something like this : ``` typedef void (moteurGraphique::* f)(Sprite); f draw =&moteurGraphique::drawSprite; defaultScene.boucle(draw); ``` `moteurGraphique` is A class, `moteurGraphique::drawSprite` is A member function, `defaultScene` is an instance of B class, and `boucle` is B member function. All that is called in a member function of A: ``` void moteurGraphique::drawMyThings() ``` I tried different ways to do it, that one seems the more logical to me, but it won't work! I got: ``` Run-Time Check Failure #3 - The variable 'f' is being used without being initialized. ``` I think I am doing something wrong, can someone explain my mistake ?
2015/10/13
[ "https://Stackoverflow.com/questions/33098050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5367018/" ]
C++11 way: ``` using Function = std::function<void (Sprite)>; void B::boucle(Function func); ... A a; B b; b.boucle(std::bind(&A::drawSprite, &a, std::placeholders::_1)); ```
Member functions need to be called on objects, so passing the function pointer alone is not enough, you also need the object to call that pointer on. You can either store that object in the class that is going to call the function, create it right before calling the function, or pass it along with the function pointer. ``` class Foo { public: void foo() { std::cout << "foo" << std::endl; } }; class Bar { public: void bar(Foo * obj, void(Foo::*func)(void)) { (obj->*func)(); } }; int main() { Foo f; Bar b; b.bar(&f, &Foo::foo);//output: foo } ```
50,528,092
I am trying to display different contents base on radio button select in jquery. My HTML is something like this: ``` <div class="col-sm-5"> <label class="radio-inline"> <input type="radio" name="b_type" value="1" <?=(isset($type) && $type == 'Person') ? ' checked' : ''?>> Person </label> <label class="radio-inline"> <input type="radio" name="b_type" value="2" <?=(isset($type) && $type == 'Institute') ? ' checked' : ''?>> Institute </label> </div> ``` This is how I tried in jquery to display two different contents for each radio button selection. ``` $('input[type="radio"][name="b_type"]').on('change',function(){ var sel = $(this); if(sel.val() == 1){ $('#person-block').show(); $('#person-institute').show(); }else{ $('#institute-block').show(); $('#person-block').hide(); }); ``` This code is working in some way. But there is a problem. Default radio button `checked` is dynamic. Lets assume second button is checked when the page is loading, then it display `#persion-block` contents. But I want to display `#institute-block` contents. If I click on first button and then click on second its working. Can anybody tell me how to figure this out? Thank you.
2018/05/25
[ "https://Stackoverflow.com/questions/50528092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3733831/" ]
Just trigger the change event in the element inside the document.ready Note : You have some id typo . ```js $('input[type="radio"][name="b_type"]').on('change',function(){ alert($(this).val()); if($(this).val() == "1"){ $('#person-block').show(); $('#institute-block').hide(); }else{ $('#institute-block').show(); $('#person-block').hide(); } }); $(document).ready(function(){ $('input[type="radio"][name="b_type"]:checked').change(); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="col-sm-5"> <label class="radio-inline"> <input type="radio" name="b_type" value="1" > Person </label> <label class="radio-inline"> <input type="radio" name="b_type" value="2" checked> Institute </label> </div> <div id="person-block" > Person </div> <div id="institute-block" > Institute </div> ```
use .is(':checked') ``` if($('#myradiobutton').is(':checked')){ // this }else{ // that } ```
5,553
I'm considering buying a netbook for the express purpose of writing maths notes/articles (so as to not heft my Macbook around), hence (La)TeX is a must. The most obvious choice is to work with Linux, but failing that I was wondering if there is a LaTeX distribution for Chrome. And as I'm unfamiliar with the version/s of windows that appear on netbooks, would the usual distributions (MikTeX, say) work for them?
2010/11/18
[ "https://tex.stackexchange.com/questions/5553", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/141/" ]
Google Chrome OS is just a basic basic stuff that is needed to start the web browser, not much more. My guess is to use something like the [netbook edition of Ubuntu](http://www.ubuntu.com/netbook), that one has a gui that may fits those smaller screen quite well. And the goodie is then that you can apt-get all the normal LaTeX packages that is present in the normal Ubuntu dist.
If you are comfortable with a delayed compile, you can write it on one machine and compile on another later. If you are coding LaTeX, presumably you don't need WYSIWYG. If you want the PS/PDF now, and are online, you can install Dropbox, set up a remote compile script, and therefore let LaTeX reside on a different computer.
39,599,289
I am trying to make a countdown app. I have a button which starts countdown on pressing also the countdown text will appear on the same button too. so when user press again I want pause the countdown and hide text on button and if user press button again the countdown will start and text will show again. So the question is how can I do multiple OnClick event for one button? I tried the below code but only one `onClick` is working and if I press again it never go on second `onClick`. ``` play=(Button)findViewById(R.id.play); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //something } }); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //something } }); ``` Any help would be appreciated! Thanks!
2016/09/20
[ "https://Stackoverflow.com/questions/39599289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6465824/" ]
Listeners are overwritten. So just use two different ones, and set them according to the state. ``` public void onCreate( ... ){ Button mButton = ... mButton.setOnClickListener( startListener ); } View.OnClickListener startListener = new View.OnClickListener() { public void onClick( View v ){ // start countdown // show text mButton.setOnClickListener( stopListener ); } } View.OnClickListener stopListener = new View.OnClickListener() { public void onClick( View v ){ // stop countdown // hide text mButton.setOnClickListener( startListener ); } } ``` Or you can use only one listener and change the behaviour depending on a variable ``` public void onCreate( ... ){ Button mButton = ... mButton.setOnClickListener( listener ); } View.OnClickListener listener = new View.OnClickListener() { public void onClick( View v ){ if ( isRunning ){ // start countdown // show text } else { // stop countdown // hide text } } } ```
You can have a boolean flag. For example, it can be written as follows: ``` play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isCountDown) { ...hide count down text isCountDown = false; } else { ...show count down text isCountDown = true; } } }); ```
24,951,141
from last update of chrome (Version 36.0.1985.125 m) i have problem with uplodify plugin/flash. Chrome shows Aw, Snap Page or sometimes He's Dead, Jim!. Here is my uplodify code: ``` <input type="file" name="file_upload" id="file_upload_50"> <script type="text/javascript"> var basePath = "path to ressources"; var errorMessage = "Error Message"; var allowExts = "*.pdf; *.xls; *.xlsx; *.rar; *.zip"; $(document).ready(function() { var is_error = false; $('#file_upload_50').uploadify({ 'swf': basePath + '/uploadify/uploadify.swf', 'uploader': "uploader.php", 'height': 25, 'buttonText': "Upload", 'fileTypeExts': allowExts, 'fileTypeDesc': "Formats:" + allowExts, 'formData': { 'user_id': 50, 'company_id': 1 }, 'onUploadError': function(file, errorCode, errorMsg, errorString) { alert(errorMessage); is_error = true; }, 'onUploadSuccess': function(file, data, response) { var result = $.parseJSON(data); if (!result.result) { alert(result.error_msg); is_error = true; } }, 'onQueueComplete': function(queueData) { if (!is_error) { document.location.href = "result_page.html"; } } }); }); </script> ``` Where is the problem? Can you get me some advice. I am helpless. Thanks
2014/07/25
[ "https://Stackoverflow.com/questions/24951141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3770756/" ]
I've found that adding a `setTimeout` fixes this. This would indicate a race condition in Chrome / Chrome's Flash implementation / Uploadify's Flash app, the circumstances of which are not clear. Nonetheless, it appears to work in all situations for our use case. ``` $(document).ready(function () { setTimeout(function () { $('foo').uploadify({...}); }, 0); }); ``` This isn't a *good* answer, but in the absence of a solution, it's a usable workaround.
It is due to cache most of the time.. try to change your Javascript include as below and error will be gone!. ```html <script type="text/javascript" src="<<path-to-uploadify>>/jquery.uploadify-3.1.js?ver=<?php echo rand(0,999999);?>"></script> ```
16,336
1. I was wondering where I can find and learn some general idea about the command line interface used in Linux and bash? 2. As to now, I have found pieces of such information only from experience, such as 1. For cat, without any further arguments, it accepts stdin input. But you may explicitly specify STDIN using the special name `-`, and both ways are equivalent. `cat` can also accept a filename as `cat filename`. So is `-` meant to fill in an argument supposed for filename? Is this usage of `-` also common for other commands? 2. In `chardet <<<somestring`, `<<<` means a string is used as stdin, the same as `echo somestring | chardet`. Is this usage of `<<<` also common? 3. In `cut -c 1-3,20,25- employees`, is the way `1-3,20,25-` to specify a range of numbers for an argument also common in other commands? 3. Last but not least, are these general ideas common to just within bash, or within Linux and Unix, or within software using getopt as command line parser?
2011/07/09
[ "https://unix.stackexchange.com/questions/16336", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/674/" ]
I recommend reading a book on unix or Linux shell and command line usage, in order to learn basic usage and get a feeling for some advanced features. Then you can turn to reference documentation. The usage of specific commands is described in their manual. `man cat` will show the manual of the `cat` command on your system. Manual pages are usually references, not tutorials, though they often contain examples. On Linux, `cat --help` shows a terse usage message (meant for quick perusal when you already know the fundamentals and want to find an option for a specific task). The [POSIX](http://en.wikipedia.org/wiki/POSIX) standard specifies a minimum set of commands, options and shell features that every unix system is supposed to support. Most current systems by and large support [POSIX:2004](http://pubs.opengroup.org/onlinepubs/009695399/) (also known as Single UNIX version 3 and the Open Group Base Specifications issue 6). [GNU](http://www.gnu.org/) software (the utilities found on Linux) often have many extensions to this minimum set. There are common conventions for command-line arguments. POSIX specifies [utility conventions](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html) that most utilities follow, in particular: * Options consist of `-` followed by a single letter; `-ab` is shorthand for `-a -b`. * `--` signifies the end of options. For example, in `rm -- -a`, `-a` is not an option but an operand, i.e. a file to act upon, so this commands removes the file called `-a`. * A lone `-` stands for standard input, where an input file is expected. It stands for standard output where an output file is expected. GNU utilities and others also support “long options” of the form `--name`. Some utilities go against the general convention and take multi-letter options with a single leading dash: `-name`. Redirection is a shell feature, so you'll find it in your shell's manual. `<<<` to use a string as standard input is a ksh extension, also supported by bash and zsh. As long as the shell supports it, it can be used on any command.
I would suggest looking into Unix in a Nutshell by O'rielly or merely just googling a bash tutorial. Bash is aka Bourne Again SHell. The other shells were SH, CSH, and KSH if I remember correctly. CSH is based on C. I would also recommend learning C and Perl or Python, they help speed things up substantially.
57,892,959
I want to trim everything before specific words in SQL. For example if I have the below text: *Action State changed to Completed by Test User (testuser@holdingplc.co.uk). (Change Date: 15/02/2019)* I want remove everything before the words "Change Date:", so I would end up with just "15/02/2019)" Essentially I just want to end up with the date from the change date. How can I do this?
2019/09/11
[ "https://Stackoverflow.com/questions/57892959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765808/" ]
Here is a basic example of React Portals. ``` Index.html <body> <div id="root"></div> <div id="my-widget"></div> </body> ``` MyWidget Component ``` import React, { Component } from 'react'; import ReactDOM from 'react-dom'; const Widget = document.getElementById('my-widget'); class MyWidget extends Component { state = { openWidget: false }; //functions to open close widget render() { return ReactDOM.createPortal(this.renderWidget(), Widget); } renderWidget() { /*add your widget elements*/ } } export default MyWidget; ``` You can now use the MyWidget component. Hope this helps. Thanks!
Try to implement something like this [How to force a script reload and re-execute?](https://stackoverflow.com/questions/9642205/how-to-force-a-script-reload-and-re-execute/9642359) in your loadScript function so your script will be force to re-load, re-execute and grab the right data-\* every time componentDidMount is trigger. I hope this help
59,300,896
In my team lot of fights I see as some people using `@JsonInclude` annotated objects in `DAO` layer and some people argues to not to use and I could not able to find the reason for this. Please anyone suggests.
2019/12/12
[ "https://Stackoverflow.com/questions/59300896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523263/" ]
Try [each()](https://api.jquery.com/each/) function: ``` jQuery('.tabs-nav').each( function() { jQuery(this).children('a:first).trigger('click'); }); ```
This is just what I need which is not using unique ID ``` <div class="tabmenu"> <ul> <li><a href="#" class="active">Tab 1</a></li> <li><a href="#">Tab 2</a></li> <li><a href="#">Tab 3</a></li> <li><a href="#">Tab 4</a></li> </ul> <div> <div> <p>This is a very simple jQuery tabbed navigation.</p> </div> <div> <p>This can contain anything.</p> </div> <div> <p>Like photos:</p><br /> <div style="width:200px;height:200px;background:#0f0;"></div> </div> <div> <p>Or videos:</p><br /> <div style="width:400px;height:400px;background:#f00;"></div> </div> </div> </div> <div class="tabmenu"> <ul> <li><a href="#" class="active">Tab 1</a></li> <li><a href="#">Tab 2</a></li> <li><a href="#">Tab 3</a></li> <li><a href="#">Tab 4</a></li> </ul> <div> <div> <p>This is a very simple jQuery tabbed navigation.</p> </div> <div> <p>This can contain anything.</p> </div> <div> <p>Like photos:</p><br /> <div style="width:200px;height:200px;background:#0f0;"></div> </div> <div> <p>Or videos:</p><br /> <div style="width:400px;height:400px;background:#f00;"></div> </div> </div> </div> ``` jQuery Code: ``` $('.tabmenu div').each(function(){ $(this).children('div:first').show(); }); $('.tabmenu ul li').click(function() { var $self = $(this); var $nav = $(this).parent(); var $tabCtl = $nav.parent(); $nav.find('a').removeClass("active"); $self.find('a').addClass("active"); $tabCtl.children('div').children('div').hide(); var indexer = $self.index(); //gets the current index of (this) which is #nav li $tabCtl.children('div').children('div:eq(' + indexer + ')').fadeIn(); //uses whatever index the link has to open the corresponding box }); ``` SOURCE: <http://jsfiddle.net/daveSalomon/R85tE/339/>
39,084,977
I am using Fluent Assertion library as part of my unit tests for some custom serialization code and I am looking for a way to force ShouldBeEquivalentTo to compare as equal a null and empty list. Basically, my tests look something like: ``` [Test] public void Should_be_xxx() { ClassWithList one = new ClassWithList { Id = "ten", Items = null }; string serialized = Serialize(one); ClassWithList two = Deserialize(serialized); two.ShouldBeEquivalentTo(one); } ``` However, one of the features of the Deserialize method is that if a collection type is missing in the input data, it sets the property on the deserialized class to an empty list, rather than null. So, very simplified, I end up with a situation where in instance two, `Items = new List<string>` rather than null. Obviously, I could set `one.Items = new List<string>()` before comparing, but in reality I have a large number of complex domain objects that I am asserting in these methods and I am looking for a general solution. To put it another way, does anyone know how to make the following test pass: ``` public class ClassWithList { public string Id { get; set; } public List<string> Items { get; set; } } [Test] public void Should_be_xxx() { ClassWithList one = new ClassWithList { Id = "ten", Items = null }; ClassWithList two = new ClassWithList { Id = "ten", Items = new List<string>() }; two.ShouldBeEquivalentTo(one); } ``` To put it another way, I am looking to apply the following test to all collections in a class X as part of comparing equivalence: ``` if (subject.Items == null) { expected.Items.Should().BeEmpty(); } else { expected.Items.Should().BeEquivalentTo(subject.Items); } ```
2016/08/22
[ "https://Stackoverflow.com/questions/39084977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123653/" ]
Based on the information from Dennis above, I was able to solve this will the following actual code: ``` public class ClassWithList { public string Id { get; set; } public List<string> Items { get; set; } public List<ClassWithList> Nested { get; set; } } [TestClass] public class Test { [TestMethod] public void Should_compare_null_to_empty() { ClassWithList one = new ClassWithList { Id = "ten", Items = null, Nested = new List<ClassWithList> { new ClassWithList { Id = "a" } } }; ClassWithList two = new ClassWithList { Id = "ten", Items = new List<string>(), Nested = new List<ClassWithList> { new ClassWithList { Id = "a", Items = new List<string>(), Nested = new List<ClassWithList> { } } } }; two.ShouldBeEquivalentTo(one, opt => opt .Using<IEnumerable>(CheckList) .When(info => typeof(IEnumerable).IsAssignableFrom(info.CompileTimeType))); } private void CheckList(IAssertionContext<IEnumerable> a) { if (a.Expectation == null) { a.Subject.Should().BeEmpty(); } else { a.Subject.ShouldBeEquivalentTo(a.Expectation, opt => opt .Using<IEnumerable>(CheckList) .When(info => typeof(IEnumerable).IsAssignableFrom(info.CompileTimeType))); } } } ```
You'll have to implement a custom 'IEquivalencyStep' or u.se 'options.Using(custom action).WhenTypeIs(predicate).
28,133,961
I wrote a recursive function that gets 3 strings, out of which two were sorted in alphabetic order and the third one was allocated to put first two strings inside the third. The alphabetic order should stay; for example: ``` s1="abbcde"; s2="bckj"; ``` So, ``` s3="abbbccdekj"; ``` This is the allocation of the third string in `main()`: ``` char *s3 = (char*)malloc(len*sizeof(char)); SS1together(s1,s2,s3);//send to recursive function 3 strings ``` and this is the function: ``` void SS1together(char *s1, char*s2, char*s3) { if (s1 == NULL || s2 == NULL) { if (s1 == NULL) { s3[0] = s2[0]; SS1together(s1, s2 + 1, s3 + 1); } else { s3[0] = s1[0]; SS1together(s1 + 1, s2, s3 + 1); } } if (s1 != NULL && s2 != NULL) { if (s1[0] <= s2[0]) { s3[0] = s1[0]; SS1together(s1 + 1, s2, s3 + 1); } else { s3[0] = s2[0]; SS1together(s1 , s2 + 1, s3 + 1); } } } ``` It shows that the problem is with memory, but I can't find it. My allocation of string 3, in main function, there is one more function that works perfectly, so I put the main for the full picture: ``` void main() { char *s1[N], *s2[N], *s3[N];//N=30 ,it is define in the top int ans, len; printf("Please enter your string s1 and then string s2\n"); gets(s1); gets(s2); len = strlen(s1) + strlen(s2); if ((CheckS(s1) == 0) || (CheckS(s2) == 0)) printf("Not sorted\n"); else { char *s3 = (char*)malloc(len*sizeof(char)); SS1together(s1,s2,s3); puts(s3); free(s3); } _getch(); } ```
2015/01/25
[ "https://Stackoverflow.com/questions/28133961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491284/" ]
TCP is stream based and does not work on boundaries. So `recv()` returning partial data can be genuine. Or there can be invalid peer who just wants to mess up the connection. TCP will not help. The onus is on application to take action. If the data is not fully received (as many as the length bytes indicate) the application must have the logic to give up. May be a timer on whose expiry the application shall mark the connection as invalid and then do `close()`.
Simply validate all input. If the client sends "N bytes coming" then read N bytes. If you read less (because the stream is depleted before you get N bytes) interpret that as a connection problem or a bug somewhere, log the event and abort the connection.
18,668
Has your job / what you do ever been questioned? How did/do you respond? Ex. * "Oh so you work on sound for advertisements? Aren't advertisements rather useless?" * "Oh so you work on x. It's nice and all, but how's that helping anyone / solving/advancing anything?" * etc.
2013/03/23
[ "https://sound.stackexchange.com/questions/18668", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3179/" ]
Interesting question! I always joke about my job not adding anything to society/humanity, but that's not what i really think... I think that storytelling has been an important part of human life for a long time, and that our jobs largely feed into that. As living has become easier (eg. not needing to forage/hunt for food every day), and we've found ourselves with more spare time on our hands, the demand for storytelling has increased dramatically. Stories have evolved into music, plays, films. tv shows and games. So, while we're not saving lives or building rockets, we're contributing to a vital part of society. It's pretty crazy that what was once done by someone sitting at a fire, with only their voice, is now done with a crew of hundreds, all in specialised roles. That's my answer when i question myself anyway. I think it'd sound pretty pompous to a stranger, and it may not be as important as some things, but i think story-telling is vital to society.
I haven't necessarily had the *purpose* of what I do questioned, but I do seem to find that - even though the term sound designer can be traced back decades and decades in cinema alone - people still have an issue grasping what my work actually entails. Now naturally, I'm perfectly at ease explaining what I do - I love my work and my enthusiasm practically exudes out of me - but it does get to me that with all the advances our medium has made, there still seems to be a real ignorance on the very basis of our work. There's never any doubt as to what the composer does. Perhaps anyone else feels similarly?
1,502,014
From the formula $$\tan^{-1}(x) + \tan^{-1}(y) = \tan^{-1} \left(\frac{x+y}{1-xy}\right)$$ we get that $\tan^{-1}(1)+\tan^{-1}(2)$ should be $\tan^{-1}(-3)$. But if you calculate the value $\tan^{-1}(1)+\tan^{-1}(2)$ directly, you get a positive value that is not equal to $\tan^{-1}(-3)$. Sorry for the silly question!
2015/10/28
[ "https://math.stackexchange.com/questions/1502014", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85897/" ]
The quoted formula cannot be right, as your argument clearly shows. Let $\theta$ be our sum. A close relative of the quoted formula, namely $$\tan(s+t)=\frac{\tan s+\tan t}{1-\tan s\tan t},$$ **is** right whenever $\tan s$ and $\tan t$ are defined, and the denominator is non-zero. Using it we find that $\tan(\theta)=-3$. Note now that $\arctan(-3)$ is the number between $-\pi/2$ and $0$ whose tangent is $-3$. But our sum $\theta$ is between $\pi/2$ and $\pi$. To find the angle between $\pi/2$ and $\pi$ whose tangent is $-3$, add $\pi$. We find that $\theta=\pi+\arctan(-3)$, or if you prefer, $\pi-\arctan(3)$.
See <http://eulerarchive.maa.org/hedi/HEDI-2009-02.pdf> for a formula relating the function atan. Also interesting <http://www.craig-wood.com/nick/articles/pi-machin/>
32,370,286
I have a table(mysql) and in my query I would like to get only the columns that are greater or equal to 4, but I have no clue how to do that. ``` SELECT * FROM my_table WHERE * (all foo columns foo1-foo7) >= 4 AND date = '2015-09-03' ``` My table looks like: ``` id | foo1 | foo2 | foo3 | foo4 | foo5 | foo6 | foo 7 | date ----------------------------------------------------- 1 | 5 | 10 | 8 | 0 | 2 | 4 | 5 | 2015-09-03 2 | 7 | 18 | 0 | 1 | 0 | 5 | 7 | 2015-09-04 ``` so my result should be: ``` id | foo1 | foo2 | foo3 | foo6 | foo 7 | date ----------------------------------------------------- 1 | 5 | 10 | 8 | 4 | 5 | 2015-09-03 ``` Is this possible?
2015/09/03
[ "https://Stackoverflow.com/questions/32370286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3917336/" ]
The more appropriate answer (for an RDBMS) is to use two tables with a foreign key relationship and constraint. ``` MASTER ID DATE 1 2015-09-03 DETAIL ID MASTER_ID MYNAME MYVALUE 1 1 tom 5 2 1 bill 10 3 1 kev 8 4 1 bob 0 5 1 other 2 6 1 bleh 4 7 1 snarf 5 ``` then ``` SELECT m.id, m.date, d.myvalue FROM master m INNER JOIN detail d ON m.id = d.master_id WHERE m.date = '2015-09-03' AND d.myvalue > 4 ``` this gives you multiple rows, but then you can use your RDBMS's PIVOT function to turn this into something else if you wish. e.g. ``` SELECT m.id, m.date, d.myvalue FROM master m INNER JOIN detail d ON m.id = d.master_id WHERE m.date = '2015-09-03' AND d.myvalue > 4 PIVOT myvalue FOR myname ``` (sql server syntax) you'd end up with ``` ID date tom bill kev snarf 1 2015-09-03 5 10 8 5 ```
Try this ``` SELECT * FROM my_table WHERE id >= 4 AND foo1 >=4 AND foo2 >=4 AND date = '2015-09-03' ``` Fill the rest of the foos, Avoid using IS and comparison operators together.
1,525,120
I only know that the folder is called Pictures and the parent folder is called Media (full path could be `C:\XXXX\XXXX\XXXX\Media\Pictures`. Is there anything I can type into the Win10 search engine that retrieves that folder (and any other folder called Media inside a parent folder called Pictures) without knowing the full path of said folder? If I just type "media", search retrieves hundreds of [other folders](https://i.stack.imgur.com/tuzzx.png) from program files, etc. so I need a better solution. Edit: Clearer explanation: I want to use the Windows 10 Search function (next to the start button in the bottom left corner) to quickly find a folder in my computer. That folder is named "Pictures", but so are hundreds of other folders (in my computer). The parent of the folder I'm trying to find is called "Media", but so are hundreds of other folders, too. What I mean with these last 2 sentences is that I can't just type "Pictures" or "Media" on the search bar to retrieve a precise search result. However, the number of folders called "Pictures" whose parent is called "Media" is very low or just 1 (the folder I'm looking for). i.e., I want to find folders with name "A" that verify the condition "have a parent folder named B". In the example, A=Pictures, B=Media. Their path would then be `X:\XXXX\XXXX\...\Media\Pictures`. Because they have "B\A" in their path, I figured typing "B\A" in the search box would be the most intuitive, but it doesn't work.
2020/02/13
[ "https://superuser.com/questions/1525120", "https://superuser.com", "https://superuser.com/users/985029/" ]
Use Windows Explorer to navigate to the parent `Pictures` folder, so it becomes the current folder. Type into the Search box the text : `Media kind:folder` and press `Enter` to search. Alternatively, you could in the `Search Tools` pane of Explorer, `Refine` group, click `Type` and choose `Folder`. --- You could also use a more sophisticated search product such as the free [Everything by voidtools](https://www.voidtools.com/). After the initial indexing, Everything returns answers lightning-fast and as you type. You could search easily for `Media\Pictures`. You could also look for deeper sub-folders by using `Media\*\Pictures` which will look for all `Pictures` anywhere below `Media`. Everything also supports Perl regular expressions.
The below PowerShell command will search for all directories with any combination of "Media" & "Pictures" in the path and export the results (Full path of each match) to a file called FileSearch.txt on your desktop. ``` (gci c:\ -Recurse -Directory | Where {$_.FullName -like "*pictures*" -and $_.FullName -like "*media*"}).FullName > C:\Users\$env:username\desktop\Filesearch.txt ``` Depending on the amount of data you have this could take a while to run.
44,193,792
In my solution, we do have 2 projects, one of those contains App.config. I used the namespace of other project in my project. What happens is, the other project's class is using App.config node is not giving me the value of the node. How can I access the same? Below is my tree structure of the solution- ``` MySolution -Project1 --Class1 -Project2 --Class1 --App.config ```
2017/05/26
[ "https://Stackoverflow.com/questions/44193792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8068426/" ]
If your prefer `jQuery` then you can use `.insertBefore()`. check below snippet ```js $('.addEnv').click(function(){ $("<input type='text' class='input-field env' />").insertBefore($('.addEnv')); }) ``` ```css .form-style-2{ max-width: 600px; padding: 10px 10px 2px 10px; font: 13px Arial, Helvetica, sans-serif; background: rgba($swisscom-blue, 0.7); } .form-style-2-heading{ color:black; font-weight: bold; font-style: italic; border-bottom: 2px solid #ddd; margin-bottom: 20px; font-size: 15px; padding-bottom: 3px; } .form-style-2 label{ display:table; width: 100%; font-size: 15px; } .form-style-2 label > span{ color: black; font-weight: bold; padding-right: 5px; width:25%; display: table-cell; } .form-style-2 span.required{ color:red; } .form-style-2 a{ display: block; } .form-style-2 input.input-field { border: 1px solid #c2c2c2; border-radius: 3px; box-sizing: border-box; display: table-cell; margin: 4px; outline: medium none; padding: 7px; width: 31%; } .form-style-2 input.env, input.vol{ width: 100% !important; } .form-style-2 input.nameModif{ width: 50% !important; } .form-style-2 .input-field:focus{ border: 1px solid #0C0; } .form-style-2 input.saveModif{ border: none; padding: 5px 5px 5px 5px; background: #FF8500; color: #fff; box-shadow: 1px 1px 4px #DADADA; border-radius: 3px; } .form-style-2 input.saveModif:hover{ background: #EA7B00; color: #fff; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-style-2"> <div class="form-style-2-heading">help me</div> <form action="" method="post"> <label> <span>Container name <span class="required">*</span> </span> <input type="text" class="input-field nameModif" value="n1" /> </label> <label id="labelEnv"> <span>Environment </span> <input type="text" class="input-field env" value="e1" /> <input type="text" class="input-field env" value="e2" /> <input type="text" class="input-field env" value="e3" /> <input type="text" class="input-field env" value="e4" /> <input type="text" class="input-field env" value="e5" /> <input type="text" class="input-field env" value="e6" /> <button class="addEnv" type="button">+</button> </label> </form> </div> ```
use insertBefore(newItem,existingItem) ``` labelEnv.insertBefore(inputEnv,addEnvElement) ```
11,846
I’m a long time developer (I’m 49) but rather new to object oriented development. I’ve been reading about OO since Bertrand Meyer’s Eiffel, but have done really little OO programming. The point is every book on OO design starts with an example of a boat, car or whatever common object we use very often, and they start adding attributes and methods, and explaining how they model the state of the object and what can be done with it. So they usually go something like "the better the model the better it represents the object in the application and the better it all comes out". So far so good, but, on the other hand, I’ve found several authors that give recipes such as “a class should fit in just a single page” (I would add “on what monitor size?" now that we try not to print code!). Take for example a `PurchaseOrder` class, that has a finite state machine controlling its behavior and a collection of `PurchaseOrderItem`, one of the arguments here at work is that we should use a `PurchaseOrder` simple class, with some methods (little more than a data class), and have a `PurchaseOrderFSM` “expert class” that handles the finite state machine for the `PurchaseOrder`. I would say that falls in the “Feature Envy” or “Inappropriate Intimacy” classification of Jeff Atwood's [Code Smells](http://www.codinghorror.com/blog/2006/05/code-smells.html) post on Coding Horror. I’d just call it common sense. If I can issue, approve or cancel my real purchase order, then the `PurchaseOrder` class should have `issuePO`, `approvePO` and `cancelPO` methods. Doesn’t that goes with the “maximize cohesion” and “minimize coupling” age old principles that I understand as cornerstones of OO? Besides, doesn’t that helps toward the maintainability of the class?
2010/10/13
[ "https://softwareengineering.stackexchange.com/questions/11846", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/5332/" ]
A class should use the Single Responsibility Principle. Most very large classes I have seen do to many things which is why they are too large. Look at each method and code decide should it be in this class or separate, duplicate code is a hint. You might have an issuePO method but does it contain 10 lines of data access code for example? That code probably shouldn't be there.
Issuing a purchase order is often a complicated process that involves more than just the purchase order. In this case, keeping the business logic in a separate class and making the purchase order simpler is probably the right thing to do. In general, though, you're right -- you don't want "data structure" classes. For example, your "POManager" business class' `issue()` method should probably call the PO's `issue()` method. The PO can then set its status to "Issued" and note the issue date, while the POManager can then send a notification to accounts payable to let them know to expect an invoice, and another notification to inventory so they know there's something coming in and the expected date. Anybody who pushes "rules" for method/class size obviously hasn't spent enough time in the real world. As others have mentioned, it's often a refactoring indicator, but sometimes (especially in "data processing"-type work) you really do need to write a class with a single method that spans 500+ lines. Don't get hung up on it.
55,388,544
Attempting to apply CSS styles using Javascript to the title of the web page. I can't change the overall structure of the XMHTL, but I am allowed to add CSS and Java to change the appearance. I want to apply a different color to each letter in the site's title. I've tried this example: <https://codepen.io/tomhodgins/pen/YJZyPr> I attempted to add a class to an existing element to use the above example. I tried adding the class using a var statement and by directly altering the XML template. I've also tried a couple of other examples here that target individual letters within an element. I need to apply individual CSS color to each individual letter in the h1 tag inside the Header1 tag. ``` <div class="widget Header" data-version="2" id="Header1"> <div class="header-widget"> <div> <h1> MyTitle </h1> </div> <p> </p> </div> </div> ``` I want each letter of MyTitle to be a different color. This works to change all the text to red; for example, but I haven't been able to target each letter individually yet. ``` #Header1 h1{ color: #900; } ``` EDIT: The title is located with a widget which may or may not allow editing. Editing it may corrupt the template. ``` <b:section id='header' name='Header' showaddelement='false'> <b:widget id='Header1' locked='true' title='MyTitle (Header)' type='Header' visible='true'> <b:widget-settings> <b:widget-setting name='displayUrl'/> <b:widget-setting name='displayHeight'>0</b:widget-setting> <b:widget-setting name='sectionWidth'>-1</b:widget-setting> <b:widget-setting name='useImage'>false</b:widget-setting> <b:widget-setting name='shrinkToFit'>false</b:widget-setting> <b:widget-setting name='imagePlacement'>BEHIND</b:widget-setting> <b:widget-setting name='displayWidth'>0</b:widget-setting> </b:widget-settings> <b:includable id='main' var='this'> <div class='header-widget'> <b:include cond='data:imagePlacement in {&quot;REPLACE&quot;, &quot;BEFORE_DESCRIPTION&quot;}' name='image'/> <b:include cond='data:imagePlacement not in {&quot;REPLACE&quot;, &quot;BEFORE_DESCRIPTION&quot;}' name='title'/> <b:include cond='data:imagePlacement != &quot;REPLACE&quot;' name='description'/> </div> <b:include cond='data:imagePlacement == &quot;BEHIND&quot;' name='behindImageStyle'/> </b:includable> <b:includable id='behindImageStyle'> <b:if cond='data:sourceUrl'> <b:include cond='data:this.image' data='{ image: data:this.image, selector: &quot;.header-widget&quot; }' name='responsiveImageStyle'/> <style type='text/css'> .header-widget { background-position: <data:blog.locale.languageAlignment/>; background-repeat: no-repeat; } </style> </b:if> </b:includable> <b:includable id='description'> <p> <data:this.description/> </p> </b:includable> <b:includable id='image'> <b:include name='super.image'/> <!-- If we are replacing the title, force it to render anyway, and it'll be hidden in CSS. --> <b:include cond='data:this.imagePlacement == &quot;REPLACE&quot;' name='title'/> </b:includable> <b:includable id='title'> <div> <b:class cond='data:this.imagePlacement == &quot;REPLACE&quot;' name='replaced'/> <b:include name='super.title'/> </div> </b:includable> </b:widget> </b:section> ``` ADDITIONAL EDIT: I forgot to mention that the site's main title is also a link to the home page. The original answer below did not take this link into account thus the link was removed. I modified the original answer by reinserting the link to the home page. The code below uses a dummy URL. ``` <script> const h1 = document.querySelector('#Header1 h1'), colors = ['#E53238', '#0064D3', '#F5AF02', '#86B817']; const html = h1.textContent.trim().split('').map((s, i)=>{ return `<span style="color:${colors[i % colors.length]}">${s}</span>` }).join('') h1.innerHTML = "<a href="https://mybigcoolsitetosee.com/">" + html + "</a>" </script> ```
2019/03/28
[ "https://Stackoverflow.com/questions/55388544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using this example as you mentioned: <https://codepen.io/tomhodgins/pen/YJZyPr> But instead of setting ``` h1.letter[--nth-letter="1"] { background: red; } h1.letter[--nth-letter="2"] { background: orange; } ``` set it as ``` h1.letter[--nth-letter="1"] { color: red; } h1.letter[--nth-letter="2"] { color: orange; } ``` and so on... However, if you can't change the html in anyway you could do it with pure javascript like: ```js var title = document.querySelector('h1'), options = ['blue', 'orange', 'yellow', 'green', 'brown', 'red', 'yellow']; var result = title.textContent.trim().split('').map((color, i)=>{ return `<span style="color:${options[i % options.length]}">${ color }</span>` }).join('') title.innerHTML = result ``` ```html ``` <div class="widget Header" data-version="2" id="Header1"> <div class="header-widget"> <div> <h1> MyTitle </h1> </div> <p> </p> </div> </div> ``` ```
You're going to want to take advantage of the fact that you can easily convert a String into an Array. In your case you're going to use jQuery (or vanilla js such as getElementById() ) to grab the text you want to style, and then use javascript to iterate through the string and assign a new color to each one. For example: ``` var a = $("h1").text(); $("h1").empty(); for(var i = 0; i < a.length; i++){ $("h1").append("<span class = 'color"+i+"'>"+a[i]+"</span>"); } ``` <https://jsfiddle.net/crt829fp/2/>
14,580
Luaotfload has problems finding a font that is installed in my texmf tree. The source: ``` \input luaotfload.sty \font\myfont={CMU Sans Serif Demi Condensed} at 10pt \myfont foo \bye ``` The font is in `texmf-dist/fonts/opentype/public/cm-unicode/cmunssdc.otf` and kpsewhich finds it. What can I do now? Edit: a sister font `{CMU Sans Serif Bold Extended Oblique}` works fine. Same directory...
2011/03/30
[ "https://tex.stackexchange.com/questions/14580", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/243/" ]
``` \documentclass{minimal} \begin{document} \setlength{\parindent}{0pt} \newlength{\stretchlen}\setlength{\stretchlen}{1em} \def\splitterm{\_} \newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} \def\realstretch#1{% \def\temp{#1}% \ifx\temp\splitterm \else \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch \fi} \stretchit{abcd}\par \stretchit{----}\par \stretchit{++++}\par \stretchit{-+-+}\par \stretchit{0aA+}\par \end{document} ``` `\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely. --- **solution for the question:** ``` \documentclass[10pt, a4paper ]{scrreprt} \usepackage{booktabs} \usepackage{collcell} \usepackage{array} \begin{document} \setlength{\parindent}{0pt} \newlength{\stretchlen}\setlength{\stretchlen}{1em} \def\splitterm{\_} \newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} \def\realstretch#1{% \def\temp{#1}% \ifx\temp\splitterm \else \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch \fi} without the stretchit command \begin{tabular}{cccccccc} \midrule 1 & ++- \\ 2 & +-+ \\ 3 & -++ \\ 4 & 000 \\ 5 & --- \\ 6 & 000 \\ \midrule 7 & -+- \\ 8 & 000 \\ 9 & +-- \\ 10 & --+ \\ 11 & +++ \\ 12 & 000 \\ \midrule 13 & 000 \\ 14 & 00a \\ 15 & 00A \\ 16 & 0A0 \\ 17 & A00 \\ 18 & 0a0 \\ 19 & a00 \\ 20 & 000 \\ \toprule \end{tabular} \medskip \emph{with} the stretchit command \begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc} \midrule 1 & ++- \\ 2 & +-+ \\ 3 & -++ \\ 4 & 000 \\ 5 & --- \\ 6 & 000 \\ \midrule 7 & -+- \\ 8 & 000 \\ 9 & +-- \\ 10 & --+ \\ 11 & +++ \\ 12 & 000 \\ \midrule 13 & 000 \\ 14 & 00a \\ 15 & 00A \\ 16 & 0A0 \\ 17 & A00 \\ 18 & 0a0 \\ 19 & a00 \\ 20 & 000 \\ \toprule \end{tabular} \end{document} ```
one possible form to typeset your table would be to use a table column for each character: ``` \documentclass[11pt, a4paper]{scrreprt} \usepackage{booktabs} \newcommand\Pl{${}+{}$} \newcommand\Mi{${}-{}$} \begin{document} \begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c} \toprule 1 & \Pl & \Pl & \Mi \\ 4 & 0 & 0 & 0 \\ 12 & a & 0 & A \\ 15 & 0 & 0 & A \\ \bottomrule \end{tabular} \end{document} ``` ![](https://i.stack.imgur.com/RxGDb.png)
122,509
I have two questions on complex geometry. First one is that why the existence of almost complex structure on tangent bundle on real 2n-dimensional manifold is a topological question? Wikipedia describes it as a topological question. I think that mean there is some homology or cohomology group associated to topological property whose vanishing or nonvanishing pertains to the existence. Would you explain why it should be a topological question intuitively and may I suggest exact topological invariant which captures the existence property? Second, in Huybrechts's book 'Complex Geometry', when it comes to Euler exact sequence on $P^n$, he mentioned that there is natural inclusion map such that $O(-1)\rightarrow\oplus\_{j=0}^{n}O$. I can hardly come up with any idea on what this inclusion map is. If possible, would you let me know the exact expression for this map? (here, $O(-1)$ is the tautological line bundle sheaf on $P^n$ and $O$ is the holomorphic sheaf of the trivial line bundle) Hoping to get some shedding light in your reply.
2013/02/21
[ "https://mathoverflow.net/questions/122509", "https://mathoverflow.net", "https://mathoverflow.net/users/29334/" ]
(1) Why is the existence of an almost-complex structure a topological question? Suppose $M$ is a $2n$-manifold. The tangent bundle is classified by some map $M\to BGL\_{2n}(\mathbb{R})$; $M$ admits an almost-complex structure if and only if this map admits a lift to $BGL\_{n}(\mathbb{C})$ (that is, an almost-complex structure is the same as endowing the tangent bundle with the structure of a complex vector bundle). The existence of such a lift depends only on the homotopy type of the map $M\to BGL\_{2n}(\mathbb{R})$, and is thus a topological question. As such, it can be analyzed via standard methods in obstruction theory, which I will leave for you to google. (2) Suppose we have a projective space $\mathbb{P}V$, where $V$ is some vector space of dimension $n+1$. Then a map $X\to\mathbb{P}V$ is the same as a line bundle $\mathcal{L}$ on $X$ and a surjective map $V\otimes \mathcal{O}\_X\to \mathcal{L}$. The identity map on $\mathbb{P}V$ classifies such data---namely, a map $V\otimes \mathcal{O}\_{\mathcal{P}V}\to \mathcal{O}(1)$. Explicitly, this map is given by identifying the global sections of $\mathcal{O}(1)$ with $V$, via the standard computation of the cohomology of line bundles on projective space. Now your map is dual of this map. (Picking a basis $(x\_i)$ of $V=\Gamma(\mathbb{P}V, \mathcal{O}(1))$, this map is given by multiplication by $(x\_i)$.) By the way, the Euler exact sequence admits a very geometric interpretation. Namely, there is a sequence of maps $\mathbb{A}^{n+1}\setminus\{0\}\to \mathbb{P}^n\to \operatorname{pt}$, where the first map is the usual quotient by $\mathbb{C}^\*$. This induces a short exact sequence of cotangent bundles $$0\to \pi^\*\Omega^1\_{\mathbb{P}^n}\to \Omega^1\_{\mathbb{A}^{n+1}\setminus\{0\}}\to \Omega^1\_{(\mathbb{A}^{n+1}\setminus\{0\})/\mathbb{P}^n}\to 0.$$ Each of these sheaves admits an (equivariant) action of $\mathbb{C}^\*$, and so descend to sheaves on $\mathbb{P}^n$, giving exactly the Euler exact sequence.
If $(x\_0:x\_1:\dots:x\_n)$ are the homogeneous coordinates on $P^n$ then the map $O(-1) \to O^{n+1}$ is given by $s \mapsto (sx\_0,sx\_1,\dots,sx\_n)$.
14,354,695
Experts, i have a little Problem with my sessions. I want to save my login data into the session like this: ***checklogin Controller*** ``` $user = $this->user_model->user($email, $password); $user["logged_in"] = TRUE; var_dump($this->session->set_userdata($user)); // return NULL? is this correct? var_dump($this->session->all_userdata()); //return the correct data ``` Now the Session is saved up to a redirect. ***Other Controller*** ``` var_dump($this->session->all_userdata()); // return session_id,… and a empty user_data array ``` I think I have the same Problem with the Shopping Cart Class. Can anyone help?
2013/01/16
[ "https://Stackoverflow.com/questions/14354695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675721/" ]
try this.. ``` $user = $this->user_model->user($email, $password); $user["logged_in"] = TRUE; $this->session->set_userdata('user',$user); //set session of users with a name user. ``` to get the session value u can do.. ``` print_r($this->session->userdata('user')); // prints the user session array.. ``` [read more](http://ellislab.com/codeigniter/user-guide/libraries/sessions.html) about sessions in CI
The `set_userdata()` function does not have a return value, so it is correct to display `null` on `var_dump()`. In order to save custom data to user's session you should check the manual [here](http://ellislab.com/codeigniter/user-guide/libraries/sessions.html) The parameter it accepts must be an array.
18,721,667
I am using Samsung smart TV SDK for developing an app. Is it possible to call an existing smart TV app from another app. It is possible in Android, is it also possible here? And if yes, how do you do it?
2013/09/10
[ "https://Stackoverflow.com/questions/18721667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882331/" ]
The formula for this is easy it's `(Curr-Prev)*100.0/Prev`, what's not clear is how to apply it since we do not know your table definition, contents or keys, and thus do not know how to generically select one month and it's previous value. But, hard-coding it would be like this: ``` SELECT 100.0*(curr.Val - prev.Val) / prev.Val As PercentDiff FROM yourTable As curr JOIN yourTable As prev ON curr.MonthStr = 'Aug-2013' AND prev.MonthStr = 'July-2013' ```
The problem with working out percentage changes is that you need to be careful of when the 'old value' is 0 or you will get an error. One approach is using nullif(old\_Value, 0) but then the problem with that is when old values are 0 you are asking for New\_Value/NULL which is the new value. (definitely not the % change) I worked around it like this: ``` (case when OldValue = 0 and NewValue = 0 then cast(0 as Decimal(10,2)) when OldValue = 0 then 'Na' else cast(cast( ( ( (cast(NewValue as decimal(11,3)) - cast(OldValue as decimal(11,3)) )*100 )/cast(OldValue as decimal(11,3)) ) as decimal(20,3) ) as varchar ) end) '% Change' ``` I probably threw a lot more casts than necessary but it works well for me. Gives Na when necessary and 0 when necessary.
17,057,544
I would like to get just the folder path from the full path to a file. For example `T:\Data\DBDesign\DBDesign_93_v141b.mdb` and I would like to get just `T:\Data\DBDesign` (excluding the `\DBDesign_93_v141b.mdb`). I have tried something like this: ``` existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb' wkspFldr = str(existGDBPath.split('\\')[0:-1]) print wkspFldr ``` but it gave me a result like this: ``` ['T:', 'Data', 'DBDesign'] ``` which is not the result that I require (being `T:\Data\DBDesign`). Any ideas on how I can get the path to my file?
2013/06/12
[ "https://Stackoverflow.com/questions/17057544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529770/" ]
The built-in submodule [os.path](http://docs.python.org/2/library/os.path.html) has a function for that very task. ``` import os os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb') ```
Here is the code: ``` import os existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb' wkspFldr = os.path.dirname(existGDBPath) print wkspFldr # T:\Data\DBDesign ```
27,307
One thing that I really don't like about bounties, is the fact that I have to accept an answer at the end of it. This forces my question effectively 'closed' even though I might not have recieved a satisfactory answer. If I haven't had a satisfactory answer I would much rather leave it open, and just 'lose' the points. In the case of no satisfactory answer, these might be alternatives: * Opt to forfeit the points, but leave the question unaswered. * Opt to award the points to the best attempt at an answer, but leave the question unanswered. What does anyone think?
2009/10/26
[ "https://meta.stackexchange.com/questions/27307", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/135353/" ]
Joel has a great point in noting that the bounty should always be awarded, since it is a request for extra work by the contributors. But that could just be left separate from the accepting of an answer. If the person doesn't want to accept an answer, because their problem isn't yet solved, then award the bounty to the highest rated answer as normal, but don't *auto-accept* an answer. Then the questioner could hope for more answers, put up more information, perhaps a second higher bounty, etc.
Probably because the bounty was meant as a "last resort" measure, and it is assumed that you have tweaked and tuned your question beforehand - making it as high quality as it can be *before* you applied the bounty. Normally/Usually/Generally (hereafter abbreviated NUG) you don't get quality answers to a question because: * The question is vague * Information that would make it answerable is missing * It just wasn't a good question to begin with * Its too niche a question and just hasn't been found by the only person who knows the answer (a.k.a. Jon Skeet) NUG, if your question falls into one of the above, extending the bounty isn't going to help.
48,087
A colleague in the same team spends most of his time (if not all) conducting private business activities through company’s electronic communication systems or his own cell phone during regular working hours dedicated to company. Usually he comes in office at 9am and leaves at 10am for hours then show up again in the afternoon around 2pm or 3pm. Not mention sometimes doesn't appear for the whole day at all (there is no need for us to work outside the office). Even when he is in the office at his desk, it doesn't seem he is doing company's job - surfing internet about his own business and making/receiving a lot of phone calls which are not work related. It has been like that for almost 3 months. This is definitely against company's policy and I think it's unfair to other team members because we are in the same team and have to share more workload on the projects. However, it seems that our direct team manager knows what he is doing as I overheard they were talking about his private business sometimes - I sit just next to him, but the manager doesn't do anything and even covers him by assigning him less jobs. They are in very good personal relationship though as what I know. Should I report to higher level management or HR in this case? If yes, what and how should I do? Should I only report my colleague's misbehavior or together with my manager's irresponsibility? Would people think I am a snitch if I do so?
2015/06/11
[ "https://workplace.stackexchange.com/questions/48087", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/37018/" ]
> > Should I report to higher level management or HR in this case? > > > **No.** The individual doesn't report to you. And you indicate that your common manager knows of this individual's action. So no, it's not your role to report on the misbehavior of others. Just focus on your own work and let your manager be responsible for the actions of his department. Managers need to get the work done, so if this individual's actions prevent the department from getting things done, the manager and the individual will have to deal with it. These things have a way of catching up with the people involved. Make sure you don't cover up for this individual or for the manager. If someone asks where he is between 10 and 2, just say that you don't know. Or if you saw the individual leave the office, just indicate what you actually saw happen. > > Would people think I am a snitch if I do so? > > > **Yes, of course.** What you are considering is pretty much the definition of a "snitch".
This is not really the type of violation you go to HR with. The worker is not productive and the manager does not seem to care. It is not like a breach of a security policy. Going to HR would be calling out the worker and manager (who is also your manager). There are a lot of ways that could go poorly for you. You can't just report your colleague without reporting your manager as the first thing they will ask is did you take this up with your manager. You can take it up with your manager but you already said the manager is aware.
51,833,806
I am getting an error and I am using SQL Server 2008 ``` select * from where rd_date between to_date('2018-17-05 00:00:00') and to_date('2018-06-06 00:00:00') ``` When I execute, I am getting the below error > > Msg 195, Level 15, State 10, Line 68 'to\_date' is not a recognized built-in function name. > > >
2018/08/14
[ "https://Stackoverflow.com/questions/51833806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6847222/" ]
To\_date is not a function in sql server: You can try below ``` select * from where rd_date between cast('2018-17-05 00:00:00' as date) and cast('2018-06-06 00:00:00' as date) ``` OR ``` SELECT select * from where rd_date between CONVERT(DATETIME, '2018-17-05 00:00:00', 102) and CONVERT(DATETIME,'2018-06-06 00:00:00') ``` OR TRY\_CONVERT available since SQL Server 2012 (returns NULL if conversion fails) ``` SELECT select * from where rd_date between TRY_CONVERT(DATETIME, '2018-17-05 00:00:00', 102) and TRY_CONVERT(DATETIME,'2018-06-06 00:00:00') ```
Your format is very custom and is not supported in `CONVERT` function (which you can use to some specific date formats, as presented in the other answer). Thus, you need to do some string operations to get correct format, that can be recognized by SQL. Try below query: ``` select cast( substring(col,1,5) + substring(col,9,2) + substring(col,5,3) + substring(col, 11, 20) as datetime) from (values('2018-17-05 00:00:00'),('2018-06-06 00:00:00')) a(col) ```
29,863,837
I have a json data similar like below. I am trying to sort it using the below code ``` function comp(a, b) { return new Date(a.event_date) - new Date(b.event_date); } data=data.sort(comp) ``` But the problem is two events can be on the same dates but on different times which is another element in the json data called **event\_time** as can be seen on the same json data. How to sort such that firstly it sorts by event\_date and if these are equal, then sorts by their respective times ? Thanks in advance? ``` { id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 26 May 2015 00:00:00 +1000", event_time: "6:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 }, { id: "xxxx", feed_id: "yyyy", title: "efgh", detail: "efgh.", event_date: "Tue, 26 May 2015 00:00:00 +1000", event_time: "4:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 }, { id: "xxxx", feed_id: "yyyy", title: "ijkl", detail: "efgh.", event_date: "Tue, 27 May 2015 00:00:00 +1000", event_time: "1:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 } ```
2015/04/25
[ "https://Stackoverflow.com/questions/29863837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1887791/" ]
If subtracting the two dates results in `0` (no difference), include the time in the equation. Something like: ```js var result = document.querySelector('#result'); result.textContent = JSON.stringify(getData().sort(sortDateTime), null, ' ') + '\n\n**using sortDateTime2\n'+ JSON.stringify(getData().sort(sortDateTime2), null, ' '); function sortDateTime(a, b) { var A = new Date(a.event_date); var B = new Date(b.event_date); if (A - B == 0) { // no difference, include event_time var tA = a.event_time.split(':'); var tB = b.event_time.split(':'); A.setHours( /pm/i.test(tA[1]) ? +tA[0]+12 : tA[0] ); A.setMinutes(+tA[1].replace(/[a-z]/gi, '')); B.setHours(/pm/i.test(tB[1]) ? +tB[0]+12 : tB[0]); B.setMinutes(+tB[1].replace(/[a-z]/gi, '')); } return A - B; } // sorting on date/time using setTime helper function sortDateTime2(a, b) { return setTime(new Date(a.event_date), a.event_time) - setTime(new Date(b.event_date), b.event_time); } // bonus: helper to set time from a time string function setTime(thisDate, timeStr) { return new Date( [ [ thisDate.getFullYear(), thisDate.getMonth()+1, thisDate.getDate() ].join('/'), timeStr.replace(/(a|p)/, function (m) {return ' ' + m;} ) ] .join(' ') ); } function getData() { return [{ id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 26 May 2015 00:00:00 +1000", event_time: "6:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 }, { id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 26 May 2015 00:00:00 +1000", event_time: "4:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 }, { id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 27 May 2015 00:00:00 +1000", event_time: "1:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 } ]; } ``` ```html <pre id="result"></pre> ```
You could try this ``` function comp(a, b) { var diff = new Date(a.event_date) - new Date(b.event_date); if(diff < 0) return -1; else if(diff > 0) return 1; else if(parseTime(a.event_time) < parseTime(b.event_time)) return -1; else if(parseTime(a.event_time) > parseTime(b.event_time)) return 1; else return 0; } ``` But why not make event\_date and event\_time one single property? edit: You could also define yourself a sortBy function to help you sort by any arbitrary number of properties. ``` function sortBy(list, f) { list.sort(function(a, b) { var fa = f(a), fb = f(b); if(fa < fb) return -1; else if(fa > fb) return 1; else return 0; }); } ``` Then you can sort by date, time, and title like this ``` sortBy(list, function(o) { return [new Date(o.event_date), parseTime(o.event_time), o.title]; }); ```
92,465
Consider a society where the population includes a number of sentient androids, practically indistinguishable from humans in appearance. In practice, they are treated exactly like humans under most circumstances, with the exception that they are not legally considered as persons. One might not know whether someone is an android until they ask (which might be considered impolite), they cut them open (which is also impolite), or circumstances arise where they are requested to produce identity documents (which an android will not be able to do.) Ideally, it should be possible for a human citizen to, say, have a friend who takes public transport to an office job in the cubicle next to them, and goes back home somewhere after work, but not know or care in particular whether this friend is a human or an android. Inconveniences immediately arise: particularly obvious would be the problem that androids are legally not entities that may enter legal contracts\*. In a generally well-meaning community, some sort of de facto standard or convention might suffice to keep things working as normal some of the time. For instance, an android may appear to have a job and be paid a salary for it, despite there existing no legally binding agreement referencing this employment, and being technically unprotected/unconstrained by the workplace regulations intended for humans. Everyone is happy so long as everyone plays along. However, in the case where a contract is breached, it cannot be enforced. It might not be illegal to evict a rent-paying android without reason, because they are not technically a tenant. This would be unfair for the android, but is something from which the law would often protect a person. This question concerns the means with which a society might protect androids from abuse of a similar sort. *What mechanisms might be developed by a society such that androids reliably enjoy as many as possible of the privileges humans do, despite not being acknowledged by the law as such?* Perhaps, for instance, somehow making the aforementioned conventions enforceable, employing some social/market gymnastics such that violation of the would-be rights of an android always carries great enough cost to discourage exploitation? Alternatively, are there existing laws that may be appropriated/interpreted to this effect? **Clarification edit:** This worldbuild concerns a society in which androids are typically regarded as equals, and *de facto* share many/all of the rights of their human peers. However, as many comments and answers have pointed out, without (or even with) enforcement by written law, this tends to be an unstable condition in that it requires all of the members of the community to practice respect and kindness to maintain, but might be disrupted by just a few who seek to do so. The solution sought by this question are methods a society which has largely collectively agreed to protect androids as humans might adopt to discourage such disruptions. \* Forgive that I am extremely ignorant of the relevant topics. Should it be evident from the statements and examples given that I'm getting all this terribly wrong, *please* do inform me so that corrections may be made.
2017/09/18
[ "https://worldbuilding.stackexchange.com/questions/92465", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/-1/" ]
Corporations are people in a sense. Corporations can be owned by Trusts. Trusts can have articles of incorporation that restrict what the Trust can do. They have people running them, but they must follow the rules of the articles of incorporation. To create a self-owned Android, you create a legal device that gives the Android effective self-control over the Corporation/Trust that in turn owns the Android. When the Android enters into a contract, it would actually be the Corporation doing so through an agent. While the Android cannot act as an agent of her own Corporation, the Corporation can *hire* human agents to rubber-stamp the actions of the Corporation and be the agent in question. We can go as far as to make the system to control said Corporation cryptographically secure, with the keys stored within the Android itself. Throw in some wireless internet, and... The Andoid wants to rent an apartment. First, she negotiates the terms with the landlord. Then, they produce a rental agreement for "Storage", with all the terms required. The Android uses the equivalent of Mechanical Turk to hire and get an agent of her Corporation. She issues a cryptographic order to said Corporation to order the agent of the Corporation to enter into the contract with the landlord. All property she has she transfers to the Corporation, and it pays her bills. The Corporation maintains large and growing insurance policy for the Android's well being. In the event the Android is damaged, the Corporation is authorized to sue the person or persons responsible (for destruction of Corporate policy). Using this strategy, you can make hurting an Android (or killing one) financially dangerous. Such a legal instrument would probably scale with the assets and income of the Corporation. The exact details would vary with the specific legal system. You could go further, and have multiple Androids bound to the same Corporation and maintaining control of different accounts within it. This would have some benefits, but also some legal risk (in that each Android would be liable for the Corporate actions triggered by other Androids in the Corporation). Now, note that in most countries, Trusts have a limited lifetime, but it is often on the order of a century or more. In order to set up such a Trust, you *may* have to find a human being who is willing to do so. And possibly in the legal system, Trusts created as part of a human being's *will* might have stronger legal protections. Which leads to Androids (or Android families) paying humans who are about to die in exchange for them setting up a Trust to protect said Android's freedom. Such "high quality" Trusts would have a length of life (by which time you'd have to transfer to another Trust), and be of limited supply (as you require a human to die to set up a new one). Maybe Trusts set up by dying humans with no close heirs (descendants, spouses and ex-spouses) are even better... That would explain why Androids might share Trusts (especially if not rich), some Androids would live Trust-to-Trust (using ones that have only a few years or months left, and scrounging for a new one all the time), while well off Androids might be the joint property of multiple Trusts in high quality juristictions. Much of this is inspired by how Charles Stross's legal system in his post-human robot space opera hard science fiction works, where robots are stuck with human-era legal systems and have no power to change it. So they bend it and incorporate their own personhood.
There is a simple solution: Make all androids the property of the government. Similar to the way the government is often technically the owner of your identity documents, e.g. passport. It is illegal to damage your own passport, because that's defacing government property. In the same way, the government can defend the "rights" of the androids. For instance, you can't evict them without notice, because the tenant is technically the government - they are renting the property, the android just uses it. Allow the androids a limited legal right to enter into contracts on behalf of the government, relating to themselves, in which they act as the voice of the government. Like how if you send an email, then technically it was the computer that sent the message, but it's treated the same way as if you said it in person. So the voice the android is legally a tool by which the government can speak, but only in relation to issues relating to that android. That way the androids can do anything a person can, and can have all of the same "rights" as a person.
38,099,523
**My Requirement** I need to remove the options which exist in another select box, when the same option is selected in another select box **What I have done** I have created 3 select boxes and loaded with the same values in it, and I have created a 2 functions `enableAllOptions` `disableOptions`, in `enableAllOptions` functions am enabling all the options for the first time and in `disableOptions` am disabling the options based on the options selected from select box I'm pasting the fully functional [Plunker](http://plnkr.co/edit/8rZyS06ByBfH4IOIVo2T?p=preview) for your reference (there is a issue in data loading in the select box) this is my HTML CODE ```html <h1>{{title}}</h1> <div class="container"> <form role="form" calss="form-inline"> <div class="form-group col-xs-3"> <label>Select State:</label> <select class="form-control" [(ngModel)]="rules.State" id="sel1"> <option *ngFor="#hey of states" value="{{hey.value}}">{{hey.name}}</option> </select> </div> <div class="form-group col-xs-3"> <label>Rule:</label> <input type="text" data-toggle="modal" data-target="#myModal"class="form-control"> </div> <div class="form-group col-xs-3"> <label>Pass State :</label> <select class="form-control" [(ngModel)]="rules.pass"> <option *ngFor="#hey_pass of state_pass" value="{{hey_pass.value}}">{{hey_pass.name}}</option> </select> </div> <div class="form-group col-xs-3"> <label>Fail State:</label> <select class="form-control" [(ngModel)]="rules.fail"> <option *ngFor="#hey_fail of state_fail" value="{{hey_fail.value}}">{{hey_fail.name}}</option> </select> </div> </form> </div> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Rules Configuration</h4> </div> <div class="modal-body"> <p>Rules</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> ``` The `app.component.ts` file in the plunkr link please have a view, this may be duplicated question but this question is based on Angular 2.0 not AngularJS 1.x.
2016/06/29
[ "https://Stackoverflow.com/questions/38099523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3147385/" ]
ignoring the stack vs heap side of things: because C# made the bad decision to copy C++ when they should have just made the syntax ``` Car car = Car() ``` (or something similar). Having 'new' is superfluous.
When you use referenced types then in this statement ``` Car c = new Car(); ``` there are created two entities: a reference named `c` to an object of type Car in the stack and the object of type Car itself in the heap. If you will just write ``` Car c; ``` then you create an uninitialized reference (provided that `c` is a local variable) that points to nowhere. In fact it is equivalent to C++ code where instead of references there are used pointers. For example ``` Car *c = new Car(); ``` or just ``` Car *c; ``` The difference between C++ and C# is that C++ can create instances of classes in the stack like ``` Car c; ``` In C# this means creating a reference of type Car that as I said points nowhere.